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)?
40 //#define TEST_CMDLINE
41 //#define TEST_DATETIME
43 //#define TEST_DLLLOADER
44 //#define TEST_ENVIRON
45 //#define TEST_EXECUTE
47 //#define TEST_FILECONF
48 //#define TEST_FILENAME
51 //#define TEST_INFO_FUNCTIONS
55 //#define TEST_LONGLONG
57 //#define TEST_PATHLIST
58 //#define TEST_REGCONF
59 //#define TEST_REGISTRY
60 //#define TEST_SOCKETS
61 //#define TEST_STREAMS
62 //#define TEST_STRINGS
63 //#define TEST_THREADS
65 //#define TEST_VCARD -- don't enable this (VZ)
70 // ----------------------------------------------------------------------------
71 // test class for container objects
72 // ----------------------------------------------------------------------------
74 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
76 class Bar
// Foo is already taken in the hash test
79 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
82 static size_t GetNumber() { return ms_bars
; }
84 const char *GetName() const { return m_name
; }
89 static size_t ms_bars
;
92 size_t Bar::ms_bars
= 0;
94 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
96 // ============================================================================
98 // ============================================================================
100 // ----------------------------------------------------------------------------
102 // ----------------------------------------------------------------------------
104 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
106 // replace TABs with \t and CRs with \n
107 static wxString
MakePrintable(const wxChar
*s
)
110 (void)str
.Replace(_T("\t"), _T("\\t"));
111 (void)str
.Replace(_T("\n"), _T("\\n"));
112 (void)str
.Replace(_T("\r"), _T("\\r"));
117 #endif // MakePrintable() is used
119 // ----------------------------------------------------------------------------
120 // wxFontMapper::CharsetToEncoding
121 // ----------------------------------------------------------------------------
125 #include <wx/fontmap.h>
127 static void TestCharset()
129 static const wxChar
*charsets
[] =
131 // some vali charsets
140 // and now some bogus ones
147 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
149 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(charsets
[n
]);
150 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
152 wxTheFontMapper
->GetEncodingName(enc
).c_str(),
153 wxTheFontMapper
->GetEncodingDescription(enc
).c_str());
157 #endif // TEST_CHARSET
159 // ----------------------------------------------------------------------------
161 // ----------------------------------------------------------------------------
165 #include <wx/cmdline.h>
166 #include <wx/datetime.h>
168 static void ShowCmdLine(const wxCmdLineParser
& parser
)
170 wxString s
= "Input files: ";
172 size_t count
= parser
.GetParamCount();
173 for ( size_t param
= 0; param
< count
; param
++ )
175 s
<< parser
.GetParam(param
) << ' ';
179 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
180 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
185 if ( parser
.Found("o", &strVal
) )
186 s
<< "Output file:\t" << strVal
<< '\n';
187 if ( parser
.Found("i", &strVal
) )
188 s
<< "Input dir:\t" << strVal
<< '\n';
189 if ( parser
.Found("s", &lVal
) )
190 s
<< "Size:\t" << lVal
<< '\n';
191 if ( parser
.Found("d", &dt
) )
192 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
193 if ( parser
.Found("project_name", &strVal
) )
194 s
<< "Project:\t" << strVal
<< '\n';
199 #endif // TEST_CMDLINE
201 // ----------------------------------------------------------------------------
203 // ----------------------------------------------------------------------------
209 static void TestDirEnumHelper(wxDir
& dir
,
210 int flags
= wxDIR_DEFAULT
,
211 const wxString
& filespec
= wxEmptyString
)
215 if ( !dir
.IsOpened() )
218 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
221 printf("\t%s\n", filename
.c_str());
223 cont
= dir
.GetNext(&filename
);
229 static void TestDirEnum()
231 wxDir
dir(wxGetCwd());
233 puts("Enumerating everything in current directory:");
234 TestDirEnumHelper(dir
);
236 puts("Enumerating really everything in current directory:");
237 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
239 puts("Enumerating object files in current directory:");
240 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
242 puts("Enumerating directories in current directory:");
243 TestDirEnumHelper(dir
, wxDIR_DIRS
);
245 puts("Enumerating files in current directory:");
246 TestDirEnumHelper(dir
, wxDIR_FILES
);
248 puts("Enumerating files including hidden in current directory:");
249 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
253 #elif defined(__WXMSW__)
256 #error "don't know where the root directory is"
259 puts("Enumerating everything in root directory:");
260 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
262 puts("Enumerating directories in root directory:");
263 TestDirEnumHelper(dir
, wxDIR_DIRS
);
265 puts("Enumerating files in root directory:");
266 TestDirEnumHelper(dir
, wxDIR_FILES
);
268 puts("Enumerating files including hidden in root directory:");
269 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
271 puts("Enumerating files in non existing directory:");
272 wxDir
dirNo("nosuchdir");
273 TestDirEnumHelper(dirNo
);
278 // ----------------------------------------------------------------------------
280 // ----------------------------------------------------------------------------
282 #ifdef TEST_DLLLOADER
284 #include <wx/dynlib.h>
286 static void TestDllLoad()
288 #if defined(__WXMSW__)
289 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
290 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
291 #elif defined(__UNIX__)
292 // weird: using just libc.so does *not* work!
293 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
294 static const wxChar
*FUNC_NAME
= _T("strlen");
296 #error "don't know how to test wxDllLoader on this platform"
299 puts("*** testing wxDllLoader ***\n");
301 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
304 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
308 typedef int (*strlenType
)(char *);
309 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
312 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
313 FUNC_NAME
, LIB_NAME
);
317 if ( pfnStrlen("foo") != 3 )
319 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
327 wxDllLoader::UnloadLibrary(dllHandle
);
331 #endif // TEST_DLLLOADER
333 // ----------------------------------------------------------------------------
335 // ----------------------------------------------------------------------------
339 #include <wx/utils.h>
341 static wxString
MyGetEnv(const wxString
& var
)
344 if ( !wxGetEnv(var
, &val
) )
347 val
= wxString(_T('\'')) + val
+ _T('\'');
352 static void TestEnvironment()
354 const wxChar
*var
= _T("wxTestVar");
356 puts("*** testing environment access functions ***");
358 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
359 wxSetEnv(var
, _T("value for wxTestVar"));
360 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
361 wxSetEnv(var
, _T("another value"));
362 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
364 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
365 printf("PATH = %s\n", MyGetEnv(_T("PATH")));
368 #endif // TEST_ENVIRON
370 // ----------------------------------------------------------------------------
372 // ----------------------------------------------------------------------------
376 #include <wx/utils.h>
378 static void TestExecute()
380 puts("*** testing wxExecute ***");
383 #define COMMAND "cat -n ../../Makefile" // "echo hi"
384 #define SHELL_COMMAND "echo hi from shell"
385 #define REDIRECT_COMMAND COMMAND // "date"
386 #elif defined(__WXMSW__)
387 #define COMMAND "command.com -c 'echo hi'"
388 #define SHELL_COMMAND "echo hi"
389 #define REDIRECT_COMMAND COMMAND
391 #error "no command to exec"
394 printf("Testing wxShell: ");
396 if ( wxShell(SHELL_COMMAND
) )
401 printf("Testing wxExecute: ");
403 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
408 #if 0 // no, it doesn't work (yet?)
409 printf("Testing async wxExecute: ");
411 if ( wxExecute(COMMAND
) != 0 )
412 puts("Ok (command launched).");
417 printf("Testing wxExecute with redirection:\n");
418 wxArrayString output
;
419 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
425 size_t count
= output
.GetCount();
426 for ( size_t n
= 0; n
< count
; n
++ )
428 printf("\t%s\n", output
[n
].c_str());
435 #endif // TEST_EXECUTE
437 // ----------------------------------------------------------------------------
439 // ----------------------------------------------------------------------------
444 #include <wx/ffile.h>
445 #include <wx/textfile.h>
447 static void TestFileRead()
449 puts("*** wxFile read test ***");
451 wxFile
file(_T("testdata.fc"));
452 if ( file
.IsOpened() )
454 printf("File length: %lu\n", file
.Length());
456 puts("File dump:\n----------");
458 static const off_t len
= 1024;
462 off_t nRead
= file
.Read(buf
, len
);
463 if ( nRead
== wxInvalidOffset
)
465 printf("Failed to read the file.");
469 fwrite(buf
, nRead
, 1, stdout
);
479 printf("ERROR: can't open test file.\n");
485 static void TestTextFileRead()
487 puts("*** wxTextFile read test ***");
489 wxTextFile
file(_T("testdata.fc"));
492 printf("Number of lines: %u\n", file
.GetLineCount());
493 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
497 puts("\nDumping the entire file:");
498 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
500 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
502 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
504 puts("\nAnd now backwards:");
505 for ( s
= file
.GetLastLine();
506 file
.GetCurrentLine() != 0;
507 s
= file
.GetPrevLine() )
509 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
511 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
515 printf("ERROR: can't open '%s'\n", file
.GetName());
521 static void TestFileCopy()
523 puts("*** Testing wxCopyFile ***");
525 static const wxChar
*filename1
= _T("testdata.fc");
526 static const wxChar
*filename2
= _T("test2");
527 if ( !wxCopyFile(filename1
, filename2
) )
529 puts("ERROR: failed to copy file");
533 wxFFile
f1(filename1
, "rb"),
536 if ( !f1
.IsOpened() || !f2
.IsOpened() )
538 puts("ERROR: failed to open file(s)");
543 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
545 puts("ERROR: failed to read file(s)");
549 if ( (s1
.length() != s2
.length()) ||
550 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
552 puts("ERROR: copy error!");
556 puts("File was copied ok.");
562 if ( !wxRemoveFile(filename2
) )
564 puts("ERROR: failed to remove the file");
572 // ----------------------------------------------------------------------------
574 // ----------------------------------------------------------------------------
578 #include <wx/confbase.h>
579 #include <wx/fileconf.h>
581 static const struct FileConfTestData
583 const wxChar
*name
; // value name
584 const wxChar
*value
; // the value from the file
587 { _T("value1"), _T("one") },
588 { _T("value2"), _T("two") },
589 { _T("novalue"), _T("default") },
592 static void TestFileConfRead()
594 puts("*** testing wxFileConfig loading/reading ***");
596 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
597 _T("testdata.fc"), wxEmptyString
,
598 wxCONFIG_USE_RELATIVE_PATH
);
600 // test simple reading
601 puts("\nReading config file:");
602 wxString
defValue(_T("default")), value
;
603 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
605 const FileConfTestData
& data
= fcTestData
[n
];
606 value
= fileconf
.Read(data
.name
, defValue
);
607 printf("\t%s = %s ", data
.name
, value
.c_str());
608 if ( value
== data
.value
)
614 printf("(ERROR: should be %s)\n", data
.value
);
618 // test enumerating the entries
619 puts("\nEnumerating all root entries:");
622 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
625 printf("\t%s = %s\n",
627 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
629 cont
= fileconf
.GetNextEntry(name
, dummy
);
633 #endif // TEST_FILECONF
635 // ----------------------------------------------------------------------------
637 // ----------------------------------------------------------------------------
641 #include <wx/filename.h>
643 static struct FileNameInfo
645 const wxChar
*fullname
;
651 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
652 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
653 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
654 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
655 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
656 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
657 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
658 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
661 static void TestFileNameConstruction()
663 puts("*** testing wxFileName construction ***");
665 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
667 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
669 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
670 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
672 puts("ERROR (couldn't be normalized)");
676 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
683 static void TestFileNameSplit()
685 puts("*** testing wxFileName splitting ***");
687 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
689 const FileNameInfo
&fni
= filenames
[n
];
690 wxString path
, name
, ext
;
691 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
693 printf("%s -> path = '%s', name = '%s', ext = '%s'",
694 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
695 if ( path
!= fni
.path
)
696 printf(" (ERROR: path = '%s')", fni
.path
);
697 if ( name
!= fni
.name
)
698 printf(" (ERROR: name = '%s')", fni
.name
);
699 if ( ext
!= fni
.ext
)
700 printf(" (ERROR: ext = '%s')", fni
.ext
);
707 static void TestFileNameComparison()
712 static void TestFileNameOperations()
717 static void TestFileNameCwd()
722 #endif // TEST_FILENAME
724 // ----------------------------------------------------------------------------
726 // ----------------------------------------------------------------------------
734 Foo(int n_
) { n
= n_
; count
++; }
742 size_t Foo::count
= 0;
744 WX_DECLARE_LIST(Foo
, wxListFoos
);
745 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
747 #include <wx/listimpl.cpp>
749 WX_DEFINE_LIST(wxListFoos
);
751 static void TestHash()
753 puts("*** Testing wxHashTable ***\n");
757 hash
.DeleteContents(TRUE
);
759 printf("Hash created: %u foos in hash, %u foos totally\n",
760 hash
.GetCount(), Foo::count
);
762 static const int hashTestData
[] =
764 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
768 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
770 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
773 printf("Hash filled: %u foos in hash, %u foos totally\n",
774 hash
.GetCount(), Foo::count
);
776 puts("Hash access test:");
777 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
779 printf("\tGetting element with key %d, value %d: ",
781 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
784 printf("ERROR, not found.\n");
788 printf("%d (%s)\n", foo
->n
,
789 (size_t)foo
->n
== n
? "ok" : "ERROR");
793 printf("\nTrying to get an element not in hash: ");
795 if ( hash
.Get(1234) || hash
.Get(1, 0) )
797 puts("ERROR: found!");
801 puts("ok (not found)");
805 printf("Hash destroyed: %u foos left\n", Foo::count
);
810 // ----------------------------------------------------------------------------
812 // ----------------------------------------------------------------------------
818 WX_DECLARE_LIST(Bar
, wxListBars
);
819 #include <wx/listimpl.cpp>
820 WX_DEFINE_LIST(wxListBars
);
822 static void TestListCtor()
824 puts("*** Testing wxList construction ***\n");
828 list1
.Append(new Bar(_T("first")));
829 list1
.Append(new Bar(_T("second")));
831 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
832 list1
.GetCount(), Bar::GetNumber());
837 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
838 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
840 list1
.DeleteContents(TRUE
);
843 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
848 // ----------------------------------------------------------------------------
850 // ----------------------------------------------------------------------------
855 #include "wx/utils.h" // for wxSetEnv
857 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
859 // find the name of the language from its value
860 static const char *GetLangName(int lang
)
862 static const char *languageNames
[] =
883 "ARABIC_SAUDI_ARABIA",
908 "CHINESE_SIMPLIFIED",
909 "CHINESE_TRADITIONAL",
931 "ENGLISH_NEW_ZEALAND",
932 "ENGLISH_PHILIPPINES",
933 "ENGLISH_SOUTH_AFRICA",
954 "GERMAN_LIECHTENSTEIN",
996 "MALAY_BRUNEI_DARUSSALAM",
1008 "NORWEGIAN_NYNORSK",
1015 "PORTUGUESE_BRAZILIAN",
1040 "SPANISH_ARGENTINA",
1044 "SPANISH_COSTA_RICA",
1045 "SPANISH_DOMINICAN_REPUBLIC",
1047 "SPANISH_EL_SALVADOR",
1048 "SPANISH_GUATEMALA",
1052 "SPANISH_NICARAGUA",
1056 "SPANISH_PUERTO_RICO",
1059 "SPANISH_VENEZUELA",
1096 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1097 return languageNames
[lang
];
1102 static void TestDefaultLang()
1104 puts("*** Testing wxLocale::GetSystemLanguage ***");
1106 static const wxChar
*langStrings
[] =
1108 NULL
, // system default
1115 _T("de_DE.iso88591"),
1117 _T("?"), // invalid lang spec
1118 _T("klingonese"), // I bet on some systems it does exist...
1121 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1123 const char *langStr
= langStrings
[n
];
1125 wxSetEnv(_T("LC_ALL"), langStr
);
1127 int lang
= gs_localeDefault
.GetSystemLanguage();
1128 printf("Locale for '%s' is %s.\n",
1129 langStr
? langStr
: "system default", GetLangName(lang
));
1133 #endif // TEST_LOCALE
1135 // ----------------------------------------------------------------------------
1137 // ----------------------------------------------------------------------------
1141 #include <wx/mimetype.h>
1143 static void TestMimeEnum()
1145 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1147 wxArrayString mimetypes
;
1149 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1151 printf("*** All %u known filetypes: ***\n", count
);
1156 for ( size_t n
= 0; n
< count
; n
++ )
1158 wxFileType
*filetype
=
1159 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1162 printf("nothing known about the filetype '%s'!\n",
1163 mimetypes
[n
].c_str());
1167 filetype
->GetDescription(&desc
);
1168 filetype
->GetExtensions(exts
);
1170 filetype
->GetIcon(NULL
);
1173 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1176 extsAll
<< _T(", ");
1180 printf("\t%s: %s (%s)\n",
1181 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1187 static void TestMimeOverride()
1189 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1191 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1192 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1194 if ( wxFile::Exists(mailcap
) )
1195 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1197 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1199 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1202 if ( wxFile::Exists(mimetypes
) )
1203 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1205 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1207 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1213 static void TestMimeFilename()
1215 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1217 static const wxChar
*filenames
[] =
1224 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1226 const wxString fname
= filenames
[n
];
1227 wxString ext
= fname
.AfterLast(_T('.'));
1228 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1231 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1236 if ( !ft
->GetDescription(&desc
) )
1237 desc
= _T("<no description>");
1240 if ( !ft
->GetOpenCommand(&cmd
,
1241 wxFileType::MessageParameters(fname
, _T(""))) )
1242 cmd
= _T("<no command available>");
1244 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1245 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1254 static void TestMimeAssociate()
1256 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1258 wxFileTypeInfo
ftInfo(
1259 _T("application/x-xyz"),
1260 _T("xyzview '%s'"), // open cmd
1261 _T(""), // print cmd
1262 _T("XYZ File") // description
1263 _T(".xyz"), // extensions
1264 NULL
// end of extensions
1266 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1268 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1271 wxPuts(_T("ERROR: failed to create association!"));
1275 // TODO: read it back
1284 // ----------------------------------------------------------------------------
1285 // misc information functions
1286 // ----------------------------------------------------------------------------
1288 #ifdef TEST_INFO_FUNCTIONS
1290 #include <wx/utils.h>
1292 static void TestOsInfo()
1294 puts("*** Testing OS info functions ***\n");
1297 wxGetOsVersion(&major
, &minor
);
1298 printf("Running under: %s, version %d.%d\n",
1299 wxGetOsDescription().c_str(), major
, minor
);
1301 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1303 printf("Host name is %s (%s).\n",
1304 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1309 static void TestUserInfo()
1311 puts("*** Testing user info functions ***\n");
1313 printf("User id is:\t%s\n", wxGetUserId().c_str());
1314 printf("User name is:\t%s\n", wxGetUserName().c_str());
1315 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1316 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1321 #endif // TEST_INFO_FUNCTIONS
1323 // ----------------------------------------------------------------------------
1325 // ----------------------------------------------------------------------------
1327 #ifdef TEST_LONGLONG
1329 #include <wx/longlong.h>
1330 #include <wx/timer.h>
1332 // make a 64 bit number from 4 16 bit ones
1333 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1335 // get a random 64 bit number
1336 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1338 #if wxUSE_LONGLONG_WX
1339 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1340 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1341 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1342 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1343 #endif // wxUSE_LONGLONG_WX
1345 static void TestSpeed()
1347 static const long max
= 100000000;
1354 for ( n
= 0; n
< max
; n
++ )
1359 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1362 #if wxUSE_LONGLONG_NATIVE
1367 for ( n
= 0; n
< max
; n
++ )
1372 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1374 #endif // wxUSE_LONGLONG_NATIVE
1380 for ( n
= 0; n
< max
; n
++ )
1385 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1389 static void TestLongLongConversion()
1391 puts("*** Testing wxLongLong conversions ***\n");
1395 for ( size_t n
= 0; n
< 100000; n
++ )
1399 #if wxUSE_LONGLONG_NATIVE
1400 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1402 wxASSERT_MSG( a
== b
, "conversions failure" );
1404 puts("Can't do it without native long long type, test skipped.");
1407 #endif // wxUSE_LONGLONG_NATIVE
1409 if ( !(nTested
% 1000) )
1421 static void TestMultiplication()
1423 puts("*** Testing wxLongLong multiplication ***\n");
1427 for ( size_t n
= 0; n
< 100000; n
++ )
1432 #if wxUSE_LONGLONG_NATIVE
1433 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1434 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1436 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1437 #else // !wxUSE_LONGLONG_NATIVE
1438 puts("Can't do it without native long long type, test skipped.");
1441 #endif // wxUSE_LONGLONG_NATIVE
1443 if ( !(nTested
% 1000) )
1455 static void TestDivision()
1457 puts("*** Testing wxLongLong division ***\n");
1461 for ( size_t n
= 0; n
< 100000; n
++ )
1463 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1464 // multiplication will not overflow)
1465 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1467 // get a random long (not wxLongLong for now) to divide it with
1472 #if wxUSE_LONGLONG_NATIVE
1473 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1475 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1476 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1477 #else // !wxUSE_LONGLONG_NATIVE
1478 // verify the result
1479 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1480 #endif // wxUSE_LONGLONG_NATIVE
1482 if ( !(nTested
% 1000) )
1494 static void TestAddition()
1496 puts("*** Testing wxLongLong addition ***\n");
1500 for ( size_t n
= 0; n
< 100000; n
++ )
1506 #if wxUSE_LONGLONG_NATIVE
1507 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1508 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1509 "addition failure" );
1510 #else // !wxUSE_LONGLONG_NATIVE
1511 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1512 #endif // wxUSE_LONGLONG_NATIVE
1514 if ( !(nTested
% 1000) )
1526 static void TestBitOperations()
1528 puts("*** Testing wxLongLong bit operation ***\n");
1532 for ( size_t n
= 0; n
< 100000; n
++ )
1536 #if wxUSE_LONGLONG_NATIVE
1537 for ( size_t n
= 0; n
< 33; n
++ )
1540 #else // !wxUSE_LONGLONG_NATIVE
1541 puts("Can't do it without native long long type, test skipped.");
1544 #endif // wxUSE_LONGLONG_NATIVE
1546 if ( !(nTested
% 1000) )
1558 static void TestLongLongComparison()
1560 puts("*** Testing wxLongLong comparison ***\n");
1562 static const long testLongs
[] =
1573 static const long ls
[2] =
1579 wxLongLongWx lls
[2];
1583 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1587 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1589 res
= lls
[m
] > testLongs
[n
];
1590 printf("0x%lx > 0x%lx is %s (%s)\n",
1591 ls
[m
], testLongs
[n
], res
? "true" : "false",
1592 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1594 res
= lls
[m
] < testLongs
[n
];
1595 printf("0x%lx < 0x%lx is %s (%s)\n",
1596 ls
[m
], testLongs
[n
], res
? "true" : "false",
1597 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1599 res
= lls
[m
] == testLongs
[n
];
1600 printf("0x%lx == 0x%lx is %s (%s)\n",
1601 ls
[m
], testLongs
[n
], res
? "true" : "false",
1602 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1610 #endif // TEST_LONGLONG
1612 // ----------------------------------------------------------------------------
1614 // ----------------------------------------------------------------------------
1616 #ifdef TEST_PATHLIST
1618 static void TestPathList()
1620 puts("*** Testing wxPathList ***\n");
1622 wxPathList pathlist
;
1623 pathlist
.AddEnvList("PATH");
1624 wxString path
= pathlist
.FindValidPath("ls");
1627 printf("ERROR: command not found in the path.\n");
1631 printf("Command found in the path as '%s'.\n", path
.c_str());
1635 #endif // TEST_PATHLIST
1637 // ----------------------------------------------------------------------------
1638 // registry and related stuff
1639 // ----------------------------------------------------------------------------
1641 // this is for MSW only
1644 #undef TEST_REGISTRY
1649 #include <wx/confbase.h>
1650 #include <wx/msw/regconf.h>
1652 static void TestRegConfWrite()
1654 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
1655 regconf
.Write(_T("Hello"), wxString(_T("world")));
1658 #endif // TEST_REGCONF
1660 #ifdef TEST_REGISTRY
1662 #include <wx/msw/registry.h>
1664 // I chose this one because I liked its name, but it probably only exists under
1666 static const wxChar
*TESTKEY
=
1667 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1669 static void TestRegistryRead()
1671 puts("*** testing registry reading ***");
1673 wxRegKey
key(TESTKEY
);
1674 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1677 puts("ERROR: test key can't be opened, aborting test.");
1682 size_t nSubKeys
, nValues
;
1683 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1685 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1688 printf("Enumerating values:\n");
1692 bool cont
= key
.GetFirstValue(value
, dummy
);
1695 printf("Value '%s': type ", value
.c_str());
1696 switch ( key
.GetValueType(value
) )
1698 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1699 case wxRegKey::Type_String
: printf("SZ"); break;
1700 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1701 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1702 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1703 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1704 default: printf("other (unknown)"); break;
1707 printf(", value = ");
1708 if ( key
.IsNumericValue(value
) )
1711 key
.QueryValue(value
, &val
);
1717 key
.QueryValue(value
, val
);
1718 printf("'%s'", val
.c_str());
1720 key
.QueryRawValue(value
, val
);
1721 printf(" (raw value '%s')", val
.c_str());
1726 cont
= key
.GetNextValue(value
, dummy
);
1730 static void TestRegistryAssociation()
1733 The second call to deleteself genertaes an error message, with a
1734 messagebox saying .flo is crucial to system operation, while the .ddf
1735 call also fails, but with no error message
1740 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1742 key
= "ddxf_auto_file" ;
1743 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1745 key
= "ddxf_auto_file" ;
1746 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1749 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1751 key
= "program \"%1\"" ;
1753 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1755 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1757 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1759 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1763 #endif // TEST_REGISTRY
1765 // ----------------------------------------------------------------------------
1767 // ----------------------------------------------------------------------------
1771 #include <wx/socket.h>
1772 #include <wx/protocol/protocol.h>
1773 #include <wx/protocol/http.h>
1775 static void TestSocketServer()
1777 puts("*** Testing wxSocketServer ***\n");
1779 static const int PORT
= 3000;
1784 wxSocketServer
*server
= new wxSocketServer(addr
);
1785 if ( !server
->Ok() )
1787 puts("ERROR: failed to bind");
1794 printf("Server: waiting for connection on port %d...\n", PORT
);
1796 wxSocketBase
*socket
= server
->Accept();
1799 puts("ERROR: wxSocketServer::Accept() failed.");
1803 puts("Server: got a client.");
1805 server
->SetTimeout(60); // 1 min
1807 while ( socket
->IsConnected() )
1813 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1815 // don't log error if the client just close the connection
1816 if ( socket
->IsConnected() )
1818 puts("ERROR: in wxSocket::Read.");
1838 printf("Server: got '%s'.\n", s
.c_str());
1839 if ( s
== _T("bye") )
1846 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1847 socket
->Write("\r\n", 2);
1848 printf("Server: wrote '%s'.\n", s
.c_str());
1851 puts("Server: lost a client.");
1856 // same as "delete server" but is consistent with GUI programs
1860 static void TestSocketClient()
1862 puts("*** Testing wxSocketClient ***\n");
1864 static const char *hostname
= "www.wxwindows.org";
1867 addr
.Hostname(hostname
);
1870 printf("--- Attempting to connect to %s:80...\n", hostname
);
1872 wxSocketClient client
;
1873 if ( !client
.Connect(addr
) )
1875 printf("ERROR: failed to connect to %s\n", hostname
);
1879 printf("--- Connected to %s:%u...\n",
1880 addr
.Hostname().c_str(), addr
.Service());
1884 // could use simply "GET" here I suppose
1886 wxString::Format("GET http://%s/\r\n", hostname
);
1887 client
.Write(cmdGet
, cmdGet
.length());
1888 printf("--- Sent command '%s' to the server\n",
1889 MakePrintable(cmdGet
).c_str());
1890 client
.Read(buf
, WXSIZEOF(buf
));
1891 printf("--- Server replied:\n%s", buf
);
1895 #endif // TEST_SOCKETS
1897 // ----------------------------------------------------------------------------
1899 // ----------------------------------------------------------------------------
1903 #include <wx/protocol/ftp.h>
1907 #define FTP_ANONYMOUS
1909 #ifdef FTP_ANONYMOUS
1910 static const char *directory
= "/pub";
1911 static const char *filename
= "welcome.msg";
1913 static const char *directory
= "/etc";
1914 static const char *filename
= "issue";
1917 static bool TestFtpConnect()
1919 puts("*** Testing FTP connect ***");
1921 #ifdef FTP_ANONYMOUS
1922 static const char *hostname
= "ftp.wxwindows.org";
1924 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1925 #else // !FTP_ANONYMOUS
1926 static const char *hostname
= "localhost";
1929 fgets(user
, WXSIZEOF(user
), stdin
);
1930 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
1934 printf("Password for %s: ", password
);
1935 fgets(password
, WXSIZEOF(password
), stdin
);
1936 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
1937 ftp
.SetPassword(password
);
1939 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
1940 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
1942 if ( !ftp
.Connect(hostname
) )
1944 printf("ERROR: failed to connect to %s\n", hostname
);
1950 printf("--- Connected to %s, current directory is '%s'\n",
1951 hostname
, ftp
.Pwd().c_str());
1957 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
1958 static void TestFtpWuFtpd()
1961 static const char *hostname
= "ftp.eudora.com";
1962 if ( !ftp
.Connect(hostname
) )
1964 printf("ERROR: failed to connect to %s\n", hostname
);
1968 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
1969 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1972 printf("ERROR: couldn't get input stream for %s\n", filename
);
1976 size_t size
= in
->StreamSize();
1977 printf("Reading file %s (%u bytes)...", filename
, size
);
1979 char *data
= new char[size
];
1980 if ( !in
->Read(data
, size
) )
1982 puts("ERROR: read error");
1986 printf("Successfully retrieved the file.\n");
1995 static void TestFtpList()
1997 puts("*** Testing wxFTP file listing ***\n");
2000 if ( !ftp
.ChDir(directory
) )
2002 printf("ERROR: failed to cd to %s\n", directory
);
2005 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2007 // test NLIST and LIST
2008 wxArrayString files
;
2009 if ( !ftp
.GetFilesList(files
) )
2011 puts("ERROR: failed to get NLIST of files");
2015 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2016 size_t count
= files
.GetCount();
2017 for ( size_t n
= 0; n
< count
; n
++ )
2019 printf("\t%s\n", files
[n
].c_str());
2021 puts("End of the file list");
2024 if ( !ftp
.GetDirList(files
) )
2026 puts("ERROR: failed to get LIST of files");
2030 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2031 size_t count
= files
.GetCount();
2032 for ( size_t n
= 0; n
< count
; n
++ )
2034 printf("\t%s\n", files
[n
].c_str());
2036 puts("End of the file list");
2039 if ( !ftp
.ChDir(_T("..")) )
2041 puts("ERROR: failed to cd to ..");
2044 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2047 static void TestFtpDownload()
2049 puts("*** Testing wxFTP download ***\n");
2052 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2055 printf("ERROR: couldn't get input stream for %s\n", filename
);
2059 size_t size
= in
->StreamSize();
2060 printf("Reading file %s (%u bytes)...", filename
, size
);
2063 char *data
= new char[size
];
2064 if ( !in
->Read(data
, size
) )
2066 puts("ERROR: read error");
2070 printf("\nContents of %s:\n%s\n", filename
, data
);
2078 static void TestFtpFileSize()
2080 puts("*** Testing FTP SIZE command ***");
2082 if ( !ftp
.ChDir(directory
) )
2084 printf("ERROR: failed to cd to %s\n", directory
);
2087 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2089 if ( ftp
.FileExists(filename
) )
2091 int size
= ftp
.GetFileSize(filename
);
2093 printf("ERROR: couldn't get size of '%s'\n", filename
);
2095 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2099 printf("ERROR: '%s' doesn't exist\n", filename
);
2103 static void TestFtpMisc()
2105 puts("*** Testing miscellaneous wxFTP functions ***");
2107 if ( ftp
.SendCommand("STAT") != '2' )
2109 puts("ERROR: STAT failed");
2113 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2116 if ( ftp
.SendCommand("HELP SITE") != '2' )
2118 puts("ERROR: HELP SITE failed");
2122 printf("The list of site-specific commands:\n\n%s\n",
2123 ftp
.GetLastResult().c_str());
2127 static void TestFtpInteractive()
2129 puts("\n*** Interactive wxFTP test ***");
2135 printf("Enter FTP command: ");
2136 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2139 // kill the last '\n'
2140 buf
[strlen(buf
) - 1] = 0;
2142 // special handling of LIST and NLST as they require data connection
2143 wxString
start(buf
, 4);
2145 if ( start
== "LIST" || start
== "NLST" )
2148 if ( strlen(buf
) > 4 )
2151 wxArrayString files
;
2152 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2154 printf("ERROR: failed to get %s of files\n", start
.c_str());
2158 printf("--- %s of '%s' under '%s':\n",
2159 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2160 size_t count
= files
.GetCount();
2161 for ( size_t n
= 0; n
< count
; n
++ )
2163 printf("\t%s\n", files
[n
].c_str());
2165 puts("--- End of the file list");
2170 char ch
= ftp
.SendCommand(buf
);
2171 printf("Command %s", ch
? "succeeded" : "failed");
2174 printf(" (return code %c)", ch
);
2177 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2181 puts("\n*** done ***");
2184 static void TestFtpUpload()
2186 puts("*** Testing wxFTP uploading ***\n");
2189 static const char *file1
= "test1";
2190 static const char *file2
= "test2";
2191 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2194 printf("--- Uploading to %s ---\n", file1
);
2195 out
->Write("First hello", 11);
2199 // send a command to check the remote file
2200 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2202 printf("ERROR: STAT %s failed\n", file1
);
2206 printf("STAT %s returned:\n\n%s\n",
2207 file1
, ftp
.GetLastResult().c_str());
2210 out
= ftp
.GetOutputStream(file2
);
2213 printf("--- Uploading to %s ---\n", file1
);
2214 out
->Write("Second hello", 12);
2221 // ----------------------------------------------------------------------------
2223 // ----------------------------------------------------------------------------
2227 #include <wx/wfstream.h>
2228 #include <wx/mstream.h>
2230 static void TestFileStream()
2232 puts("*** Testing wxFileInputStream ***");
2234 static const wxChar
*filename
= _T("testdata.fs");
2236 wxFileOutputStream
fsOut(filename
);
2237 fsOut
.Write("foo", 3);
2240 wxFileInputStream
fsIn(filename
);
2241 printf("File stream size: %u\n", fsIn
.GetSize());
2242 while ( !fsIn
.Eof() )
2244 putchar(fsIn
.GetC());
2247 if ( !wxRemoveFile(filename
) )
2249 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2252 puts("\n*** wxFileInputStream test done ***");
2255 static void TestMemoryStream()
2257 puts("*** Testing wxMemoryInputStream ***");
2260 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2262 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2263 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2264 while ( !memInpStream
.Eof() )
2266 putchar(memInpStream
.GetC());
2269 puts("\n*** wxMemoryInputStream test done ***");
2272 #endif // TEST_STREAMS
2274 // ----------------------------------------------------------------------------
2276 // ----------------------------------------------------------------------------
2280 #include <wx/timer.h>
2281 #include <wx/utils.h>
2283 static void TestStopWatch()
2285 puts("*** Testing wxStopWatch ***\n");
2288 printf("Sleeping 3 seconds...");
2290 printf("\telapsed time: %ldms\n", sw
.Time());
2293 printf("Sleeping 2 more seconds...");
2295 printf("\telapsed time: %ldms\n", sw
.Time());
2298 printf("And 3 more seconds...");
2300 printf("\telapsed time: %ldms\n", sw
.Time());
2303 puts("\nChecking for 'backwards clock' bug...");
2304 for ( size_t n
= 0; n
< 70; n
++ )
2308 for ( size_t m
= 0; m
< 100000; m
++ )
2310 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2312 puts("\ntime is negative - ERROR!");
2322 #endif // TEST_TIMER
2324 // ----------------------------------------------------------------------------
2326 // ----------------------------------------------------------------------------
2330 #include <wx/vcard.h>
2332 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2335 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2339 wxString(_T('\t'), level
).c_str(),
2340 vcObj
->GetName().c_str());
2343 switch ( vcObj
->GetType() )
2345 case wxVCardObject::String
:
2346 case wxVCardObject::UString
:
2349 vcObj
->GetValue(&val
);
2350 value
<< _T('"') << val
<< _T('"');
2354 case wxVCardObject::Int
:
2357 vcObj
->GetValue(&i
);
2358 value
.Printf(_T("%u"), i
);
2362 case wxVCardObject::Long
:
2365 vcObj
->GetValue(&l
);
2366 value
.Printf(_T("%lu"), l
);
2370 case wxVCardObject::None
:
2373 case wxVCardObject::Object
:
2374 value
= _T("<node>");
2378 value
= _T("<unknown value type>");
2382 printf(" = %s", value
.c_str());
2385 DumpVObject(level
+ 1, *vcObj
);
2388 vcObj
= vcard
.GetNextProp(&cookie
);
2392 static void DumpVCardAddresses(const wxVCard
& vcard
)
2394 puts("\nShowing all addresses from vCard:\n");
2398 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2402 int flags
= addr
->GetFlags();
2403 if ( flags
& wxVCardAddress::Domestic
)
2405 flagsStr
<< _T("domestic ");
2407 if ( flags
& wxVCardAddress::Intl
)
2409 flagsStr
<< _T("international ");
2411 if ( flags
& wxVCardAddress::Postal
)
2413 flagsStr
<< _T("postal ");
2415 if ( flags
& wxVCardAddress::Parcel
)
2417 flagsStr
<< _T("parcel ");
2419 if ( flags
& wxVCardAddress::Home
)
2421 flagsStr
<< _T("home ");
2423 if ( flags
& wxVCardAddress::Work
)
2425 flagsStr
<< _T("work ");
2428 printf("Address %u:\n"
2430 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2433 addr
->GetPostOffice().c_str(),
2434 addr
->GetExtAddress().c_str(),
2435 addr
->GetStreet().c_str(),
2436 addr
->GetLocality().c_str(),
2437 addr
->GetRegion().c_str(),
2438 addr
->GetPostalCode().c_str(),
2439 addr
->GetCountry().c_str()
2443 addr
= vcard
.GetNextAddress(&cookie
);
2447 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2449 puts("\nShowing all phone numbers from vCard:\n");
2453 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2457 int flags
= phone
->GetFlags();
2458 if ( flags
& wxVCardPhoneNumber::Voice
)
2460 flagsStr
<< _T("voice ");
2462 if ( flags
& wxVCardPhoneNumber::Fax
)
2464 flagsStr
<< _T("fax ");
2466 if ( flags
& wxVCardPhoneNumber::Cellular
)
2468 flagsStr
<< _T("cellular ");
2470 if ( flags
& wxVCardPhoneNumber::Modem
)
2472 flagsStr
<< _T("modem ");
2474 if ( flags
& wxVCardPhoneNumber::Home
)
2476 flagsStr
<< _T("home ");
2478 if ( flags
& wxVCardPhoneNumber::Work
)
2480 flagsStr
<< _T("work ");
2483 printf("Phone number %u:\n"
2488 phone
->GetNumber().c_str()
2492 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2496 static void TestVCardRead()
2498 puts("*** Testing wxVCard reading ***\n");
2500 wxVCard
vcard(_T("vcard.vcf"));
2501 if ( !vcard
.IsOk() )
2503 puts("ERROR: couldn't load vCard.");
2507 // read individual vCard properties
2508 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2512 vcObj
->GetValue(&value
);
2517 value
= _T("<none>");
2520 printf("Full name retrieved directly: %s\n", value
.c_str());
2523 if ( !vcard
.GetFullName(&value
) )
2525 value
= _T("<none>");
2528 printf("Full name from wxVCard API: %s\n", value
.c_str());
2530 // now show how to deal with multiply occuring properties
2531 DumpVCardAddresses(vcard
);
2532 DumpVCardPhoneNumbers(vcard
);
2534 // and finally show all
2535 puts("\nNow dumping the entire vCard:\n"
2536 "-----------------------------\n");
2538 DumpVObject(0, vcard
);
2542 static void TestVCardWrite()
2544 puts("*** Testing wxVCard writing ***\n");
2547 if ( !vcard
.IsOk() )
2549 puts("ERROR: couldn't create vCard.");
2554 vcard
.SetName("Zeitlin", "Vadim");
2555 vcard
.SetFullName("Vadim Zeitlin");
2556 vcard
.SetOrganization("wxWindows", "R&D");
2558 // just dump the vCard back
2559 puts("Entire vCard follows:\n");
2560 puts(vcard
.Write());
2564 #endif // TEST_VCARD
2566 // ----------------------------------------------------------------------------
2567 // wide char (Unicode) support
2568 // ----------------------------------------------------------------------------
2572 #include <wx/strconv.h>
2573 #include <wx/fontenc.h>
2574 #include <wx/encconv.h>
2575 #include <wx/buffer.h>
2577 static void TestUtf8()
2579 puts("*** Testing UTF8 support ***\n");
2581 static const char textInUtf8
[] =
2583 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2584 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2585 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2586 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2587 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2588 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2589 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2594 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2596 puts("ERROR: UTF-8 decoding failed.");
2600 // using wxEncodingConverter
2602 wxEncodingConverter ec
;
2603 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2604 ec
.Convert(wbuf
, buf
);
2605 #else // using wxCSConv
2606 wxCSConv
conv(_T("koi8-r"));
2607 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2609 puts("ERROR: conversion to KOI8-R failed.");
2614 printf("The resulting string (in koi8-r): %s\n", buf
);
2618 #endif // TEST_WCHAR
2620 // ----------------------------------------------------------------------------
2622 // ----------------------------------------------------------------------------
2626 #include "wx/filesys.h"
2627 #include "wx/fs_zip.h"
2628 #include "wx/zipstrm.h"
2630 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
2632 static void TestZipStreamRead()
2634 puts("*** Testing ZIP reading ***\n");
2636 static const wxChar
*filename
= _T("foo");
2637 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
2638 printf("Archive size: %u\n", istr
.GetSize());
2640 printf("Dumping the file '%s':\n", filename
);
2641 while ( !istr
.Eof() )
2643 putchar(istr
.GetC());
2647 puts("\n----- done ------");
2650 static void DumpZipDirectory(wxFileSystem
& fs
,
2651 const wxString
& dir
,
2652 const wxString
& indent
)
2654 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
2655 TESTFILE_ZIP
, dir
.c_str());
2656 wxString wildcard
= prefix
+ _T("/*");
2658 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
2659 while ( !dirname
.empty() )
2661 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
2663 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2668 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
2670 DumpZipDirectory(fs
, dirname
,
2671 indent
+ wxString(_T(' '), 4));
2673 dirname
= fs
.FindNext();
2676 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
2677 while ( !filename
.empty() )
2679 if ( !filename
.StartsWith(prefix
, &filename
) )
2681 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2686 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
2688 filename
= fs
.FindNext();
2692 static void TestZipFileSystem()
2694 puts("*** Testing ZIP file system ***\n");
2696 wxFileSystem::AddHandler(new wxZipFSHandler
);
2698 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
2700 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
2705 // ----------------------------------------------------------------------------
2707 // ----------------------------------------------------------------------------
2711 #include <wx/zstream.h>
2712 #include <wx/wfstream.h>
2714 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2715 static const char *TEST_DATA
= "hello and hello again";
2717 static void TestZlibStreamWrite()
2719 puts("*** Testing Zlib stream reading ***\n");
2721 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2722 wxZlibOutputStream
ostr(fileOutStream
, 0);
2723 printf("Compressing the test string... ");
2724 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2727 puts("(ERROR: failed)");
2734 puts("\n----- done ------");
2737 static void TestZlibStreamRead()
2739 puts("*** Testing Zlib stream reading ***\n");
2741 wxFileInputStream
fileInStream(FILENAME_GZ
);
2742 wxZlibInputStream
istr(fileInStream
);
2743 printf("Archive size: %u\n", istr
.GetSize());
2745 puts("Dumping the file:");
2746 while ( !istr
.Eof() )
2748 putchar(istr
.GetC());
2752 puts("\n----- done ------");
2757 // ----------------------------------------------------------------------------
2759 // ----------------------------------------------------------------------------
2761 #ifdef TEST_DATETIME
2765 #include <wx/date.h>
2767 #include <wx/datetime.h>
2772 wxDateTime::wxDateTime_t day
;
2773 wxDateTime::Month month
;
2775 wxDateTime::wxDateTime_t hour
, min
, sec
;
2777 wxDateTime::WeekDay wday
;
2778 time_t gmticks
, ticks
;
2780 void Init(const wxDateTime::Tm
& tm
)
2789 gmticks
= ticks
= -1;
2792 wxDateTime
DT() const
2793 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2795 bool SameDay(const wxDateTime::Tm
& tm
) const
2797 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2800 wxString
Format() const
2803 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2805 wxDateTime::GetMonthName(month
).c_str(),
2807 abs(wxDateTime::ConvertYearToBC(year
)),
2808 year
> 0 ? "AD" : "BC");
2812 wxString
FormatDate() const
2815 s
.Printf("%02d-%s-%4d%s",
2817 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2818 abs(wxDateTime::ConvertYearToBC(year
)),
2819 year
> 0 ? "AD" : "BC");
2824 static const Date testDates
[] =
2826 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2827 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2828 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2829 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2830 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2831 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2832 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2833 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2834 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2835 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2836 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2837 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2838 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2839 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2840 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2843 // this test miscellaneous static wxDateTime functions
2844 static void TestTimeStatic()
2846 puts("\n*** wxDateTime static methods test ***");
2848 // some info about the current date
2849 int year
= wxDateTime::GetCurrentYear();
2850 printf("Current year %d is %sa leap one and has %d days.\n",
2852 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2853 wxDateTime::GetNumberOfDays(year
));
2855 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2856 printf("Current month is '%s' ('%s') and it has %d days\n",
2857 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2858 wxDateTime::GetMonthName(month
).c_str(),
2859 wxDateTime::GetNumberOfDays(month
));
2862 static const size_t nYears
= 5;
2863 static const size_t years
[2][nYears
] =
2865 // first line: the years to test
2866 { 1990, 1976, 2000, 2030, 1984, },
2868 // second line: TRUE if leap, FALSE otherwise
2869 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2872 for ( size_t n
= 0; n
< nYears
; n
++ )
2874 int year
= years
[0][n
];
2875 bool should
= years
[1][n
] != 0,
2876 is
= wxDateTime::IsLeapYear(year
);
2878 printf("Year %d is %sa leap year (%s)\n",
2881 should
== is
? "ok" : "ERROR");
2883 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2887 // test constructing wxDateTime objects
2888 static void TestTimeSet()
2890 puts("\n*** wxDateTime construction test ***");
2892 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2894 const Date
& d1
= testDates
[n
];
2895 wxDateTime dt
= d1
.DT();
2898 d2
.Init(dt
.GetTm());
2900 wxString s1
= d1
.Format(),
2903 printf("Date: %s == %s (%s)\n",
2904 s1
.c_str(), s2
.c_str(),
2905 s1
== s2
? "ok" : "ERROR");
2909 // test time zones stuff
2910 static void TestTimeZones()
2912 puts("\n*** wxDateTime timezone test ***");
2914 wxDateTime now
= wxDateTime::Now();
2916 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2917 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2918 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2919 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2920 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2921 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2923 wxDateTime::Tm tm
= now
.GetTm();
2924 if ( wxDateTime(tm
) != now
)
2926 printf("ERROR: got %s instead of %s\n",
2927 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2931 // test some minimal support for the dates outside the standard range
2932 static void TestTimeRange()
2934 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2936 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
2938 printf("Unix epoch:\t%s\n",
2939 wxDateTime(2440587.5).Format(fmt
).c_str());
2940 printf("Feb 29, 0: \t%s\n",
2941 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
2942 printf("JDN 0: \t%s\n",
2943 wxDateTime(0.0).Format(fmt
).c_str());
2944 printf("Jan 1, 1AD:\t%s\n",
2945 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
2946 printf("May 29, 2099:\t%s\n",
2947 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
2950 static void TestTimeTicks()
2952 puts("\n*** wxDateTime ticks test ***");
2954 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2956 const Date
& d
= testDates
[n
];
2957 if ( d
.ticks
== -1 )
2960 wxDateTime dt
= d
.DT();
2961 long ticks
= (dt
.GetValue() / 1000).ToLong();
2962 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2963 if ( ticks
== d
.ticks
)
2969 printf(" (ERROR: should be %ld, delta = %ld)\n",
2970 d
.ticks
, ticks
- d
.ticks
);
2973 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
2974 ticks
= (dt
.GetValue() / 1000).ToLong();
2975 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2976 if ( ticks
== d
.gmticks
)
2982 printf(" (ERROR: should be %ld, delta = %ld)\n",
2983 d
.gmticks
, ticks
- d
.gmticks
);
2990 // test conversions to JDN &c
2991 static void TestTimeJDN()
2993 puts("\n*** wxDateTime to JDN test ***");
2995 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2997 const Date
& d
= testDates
[n
];
2998 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2999 double jdn
= dt
.GetJulianDayNumber();
3001 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3008 printf(" (ERROR: should be %f, delta = %f)\n",
3009 d
.jdn
, jdn
- d
.jdn
);
3014 // test week days computation
3015 static void TestTimeWDays()
3017 puts("\n*** wxDateTime weekday test ***");
3019 // test GetWeekDay()
3021 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3023 const Date
& d
= testDates
[n
];
3024 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3026 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3029 wxDateTime::GetWeekDayName(wday
).c_str());
3030 if ( wday
== d
.wday
)
3036 printf(" (ERROR: should be %s)\n",
3037 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3043 // test SetToWeekDay()
3044 struct WeekDateTestData
3046 Date date
; // the real date (precomputed)
3047 int nWeek
; // its week index in the month
3048 wxDateTime::WeekDay wday
; // the weekday
3049 wxDateTime::Month month
; // the month
3050 int year
; // and the year
3052 wxString
Format() const
3055 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3057 case 1: which
= "first"; break;
3058 case 2: which
= "second"; break;
3059 case 3: which
= "third"; break;
3060 case 4: which
= "fourth"; break;
3061 case 5: which
= "fifth"; break;
3063 case -1: which
= "last"; break;
3068 which
+= " from end";
3071 s
.Printf("The %s %s of %s in %d",
3073 wxDateTime::GetWeekDayName(wday
).c_str(),
3074 wxDateTime::GetMonthName(month
).c_str(),
3081 // the array data was generated by the following python program
3083 from DateTime import *
3084 from whrandom import *
3085 from string import *
3087 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3088 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3090 week = DateTimeDelta(7)
3093 year = randint(1900, 2100)
3094 month = randint(1, 12)
3095 day = randint(1, 28)
3096 dt = DateTime(year, month, day)
3097 wday = dt.day_of_week
3099 countFromEnd = choice([-1, 1])
3102 while dt.month is month:
3103 dt = dt - countFromEnd * week
3104 weekNum = weekNum + countFromEnd
3106 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3108 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3109 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3112 static const WeekDateTestData weekDatesTestData
[] =
3114 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3115 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3116 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3117 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3118 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3119 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3120 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3121 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3122 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3123 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3124 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3125 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3126 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3127 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3128 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3129 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3130 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3131 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3132 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3133 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3136 static const char *fmt
= "%d-%b-%Y";
3139 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3141 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3143 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3145 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3147 const Date
& d
= wd
.date
;
3148 if ( d
.SameDay(dt
.GetTm()) )
3154 dt
.Set(d
.day
, d
.month
, d
.year
);
3156 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3161 // test the computation of (ISO) week numbers
3162 static void TestTimeWNumber()
3164 puts("\n*** wxDateTime week number test ***");
3166 struct WeekNumberTestData
3168 Date date
; // the date
3169 wxDateTime::wxDateTime_t week
; // the week number in the year
3170 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3171 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3172 wxDateTime::wxDateTime_t dnum
; // day number in the year
3175 // data generated with the following python script:
3177 from DateTime import *
3178 from whrandom import *
3179 from string import *
3181 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3182 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3184 def GetMonthWeek(dt):
3185 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3186 if weekNumMonth < 0:
3187 weekNumMonth = weekNumMonth + 53
3190 def GetLastSundayBefore(dt):
3191 if dt.iso_week[2] == 7:
3194 return dt - DateTimeDelta(dt.iso_week[2])
3197 year = randint(1900, 2100)
3198 month = randint(1, 12)
3199 day = randint(1, 28)
3200 dt = DateTime(year, month, day)
3201 dayNum = dt.day_of_year
3202 weekNum = dt.iso_week[1]
3203 weekNumMonth = GetMonthWeek(dt)
3206 dtSunday = GetLastSundayBefore(dt)
3208 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3209 weekNumMonth2 = weekNumMonth2 + 1
3210 dtSunday = dtSunday - DateTimeDelta(7)
3212 data = { 'day': rjust(`day`, 2), \
3213 'month': monthNames[month - 1], \
3215 'weekNum': rjust(`weekNum`, 2), \
3216 'weekNumMonth': weekNumMonth, \
3217 'weekNumMonth2': weekNumMonth2, \
3218 'dayNum': rjust(`dayNum`, 3) }
3220 print " { { %(day)s, "\
3221 "wxDateTime::%(month)s, "\
3224 "%(weekNumMonth)s, "\
3225 "%(weekNumMonth2)s, "\
3226 "%(dayNum)s }," % data
3229 static const WeekNumberTestData weekNumberTestDates
[] =
3231 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3232 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3233 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3234 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3235 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3236 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3237 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3238 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3239 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3240 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3241 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3242 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3243 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3244 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3245 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3246 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3247 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3248 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3249 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3250 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3253 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3255 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3256 const Date
& d
= wn
.date
;
3258 wxDateTime dt
= d
.DT();
3260 wxDateTime::wxDateTime_t
3261 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3262 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3263 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3264 dnum
= dt
.GetDayOfYear();
3266 printf("%s: the day number is %d",
3267 d
.FormatDate().c_str(), dnum
);
3268 if ( dnum
== wn
.dnum
)
3274 printf(" (ERROR: should be %d)", wn
.dnum
);
3277 printf(", week in month is %d", wmon
);
3278 if ( wmon
== wn
.wmon
)
3284 printf(" (ERROR: should be %d)", wn
.wmon
);
3287 printf(" or %d", wmon2
);
3288 if ( wmon2
== wn
.wmon2
)
3294 printf(" (ERROR: should be %d)", wn
.wmon2
);
3297 printf(", week in year is %d", week
);
3298 if ( week
== wn
.week
)
3304 printf(" (ERROR: should be %d)\n", wn
.week
);
3309 // test DST calculations
3310 static void TestTimeDST()
3312 puts("\n*** wxDateTime DST test ***");
3314 printf("DST is%s in effect now.\n\n",
3315 wxDateTime::Now().IsDST() ? "" : " not");
3317 // taken from http://www.energy.ca.gov/daylightsaving.html
3318 static const Date datesDST
[2][2004 - 1900 + 1] =
3321 { 1, wxDateTime::Apr
, 1990 },
3322 { 7, wxDateTime::Apr
, 1991 },
3323 { 5, wxDateTime::Apr
, 1992 },
3324 { 4, wxDateTime::Apr
, 1993 },
3325 { 3, wxDateTime::Apr
, 1994 },
3326 { 2, wxDateTime::Apr
, 1995 },
3327 { 7, wxDateTime::Apr
, 1996 },
3328 { 6, wxDateTime::Apr
, 1997 },
3329 { 5, wxDateTime::Apr
, 1998 },
3330 { 4, wxDateTime::Apr
, 1999 },
3331 { 2, wxDateTime::Apr
, 2000 },
3332 { 1, wxDateTime::Apr
, 2001 },
3333 { 7, wxDateTime::Apr
, 2002 },
3334 { 6, wxDateTime::Apr
, 2003 },
3335 { 4, wxDateTime::Apr
, 2004 },
3338 { 28, wxDateTime::Oct
, 1990 },
3339 { 27, wxDateTime::Oct
, 1991 },
3340 { 25, wxDateTime::Oct
, 1992 },
3341 { 31, wxDateTime::Oct
, 1993 },
3342 { 30, wxDateTime::Oct
, 1994 },
3343 { 29, wxDateTime::Oct
, 1995 },
3344 { 27, wxDateTime::Oct
, 1996 },
3345 { 26, wxDateTime::Oct
, 1997 },
3346 { 25, wxDateTime::Oct
, 1998 },
3347 { 31, wxDateTime::Oct
, 1999 },
3348 { 29, wxDateTime::Oct
, 2000 },
3349 { 28, wxDateTime::Oct
, 2001 },
3350 { 27, wxDateTime::Oct
, 2002 },
3351 { 26, wxDateTime::Oct
, 2003 },
3352 { 31, wxDateTime::Oct
, 2004 },
3357 for ( year
= 1990; year
< 2005; year
++ )
3359 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3360 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3362 printf("DST period in the US for year %d: from %s to %s",
3363 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3365 size_t n
= year
- 1990;
3366 const Date
& dBegin
= datesDST
[0][n
];
3367 const Date
& dEnd
= datesDST
[1][n
];
3369 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3375 printf(" (ERROR: should be %s %d to %s %d)\n",
3376 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3377 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3383 for ( year
= 1990; year
< 2005; year
++ )
3385 printf("DST period in Europe for year %d: from %s to %s\n",
3387 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3388 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3392 // test wxDateTime -> text conversion
3393 static void TestTimeFormat()
3395 puts("\n*** wxDateTime formatting test ***");
3397 // some information may be lost during conversion, so store what kind
3398 // of info should we recover after a round trip
3401 CompareNone
, // don't try comparing
3402 CompareBoth
, // dates and times should be identical
3403 CompareDate
, // dates only
3404 CompareTime
// time only
3409 CompareKind compareKind
;
3411 } formatTestFormats
[] =
3413 { CompareBoth
, "---> %c" },
3414 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3415 { CompareBoth
, "Date is %x, time is %X" },
3416 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3417 { CompareNone
, "The day of year: %j, the week of year: %W" },
3418 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3421 static const Date formatTestDates
[] =
3423 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3424 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3426 // this test can't work for other centuries because it uses two digit
3427 // years in formats, so don't even try it
3428 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3429 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3430 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3434 // an extra test (as it doesn't depend on date, don't do it in the loop)
3435 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3437 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3441 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3442 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3444 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3445 printf("%s", s
.c_str());
3447 // what can we recover?
3448 int kind
= formatTestFormats
[n
].compareKind
;
3452 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3455 // converion failed - should it have?
3456 if ( kind
== CompareNone
)
3459 puts(" (ERROR: conversion back failed)");
3463 // should have parsed the entire string
3464 puts(" (ERROR: conversion back stopped too soon)");
3468 bool equal
= FALSE
; // suppress compilaer warning
3476 equal
= dt
.IsSameDate(dt2
);
3480 equal
= dt
.IsSameTime(dt2
);
3486 printf(" (ERROR: got back '%s' instead of '%s')\n",
3487 dt2
.Format().c_str(), dt
.Format().c_str());
3498 // test text -> wxDateTime conversion
3499 static void TestTimeParse()
3501 puts("\n*** wxDateTime parse test ***");
3503 struct ParseTestData
3510 static const ParseTestData parseTestDates
[] =
3512 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3513 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3516 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3518 const char *format
= parseTestDates
[n
].format
;
3520 printf("%s => ", format
);
3523 if ( dt
.ParseRfc822Date(format
) )
3525 printf("%s ", dt
.Format().c_str());
3527 if ( parseTestDates
[n
].good
)
3529 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3536 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3541 puts("(ERROR: bad format)");
3546 printf("bad format (%s)\n",
3547 parseTestDates
[n
].good
? "ERROR" : "ok");
3552 static void TestDateTimeInteractive()
3554 puts("\n*** interactive wxDateTime tests ***");
3560 printf("Enter a date: ");
3561 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3564 // kill the last '\n'
3565 buf
[strlen(buf
) - 1] = 0;
3568 const char *p
= dt
.ParseDate(buf
);
3571 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3577 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3580 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3581 dt
.Format("%b %d, %Y").c_str(),
3583 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3584 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3585 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3588 puts("\n*** done ***");
3591 static void TestTimeMS()
3593 puts("*** testing millisecond-resolution support in wxDateTime ***");
3595 wxDateTime dt1
= wxDateTime::Now(),
3596 dt2
= wxDateTime::UNow();
3598 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3599 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3600 printf("Dummy loop: ");
3601 for ( int i
= 0; i
< 6000; i
++ )
3603 //for ( int j = 0; j < 10; j++ )
3606 s
.Printf("%g", sqrt(i
));
3615 dt2
= wxDateTime::UNow();
3616 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3618 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3620 puts("\n*** done ***");
3623 static void TestTimeArithmetics()
3625 puts("\n*** testing arithmetic operations on wxDateTime ***");
3627 static const struct ArithmData
3629 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3630 : span(sp
), name(nam
) { }
3634 } testArithmData
[] =
3636 ArithmData(wxDateSpan::Day(), "day"),
3637 ArithmData(wxDateSpan::Week(), "week"),
3638 ArithmData(wxDateSpan::Month(), "month"),
3639 ArithmData(wxDateSpan::Year(), "year"),
3640 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3643 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3645 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3647 wxDateSpan span
= testArithmData
[n
].span
;
3651 const char *name
= testArithmData
[n
].name
;
3652 printf("%s + %s = %s, %s - %s = %s\n",
3653 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3654 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3656 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3657 if ( dt1
- span
== dt
)
3663 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3666 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3667 if ( dt2
+ span
== dt
)
3673 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3676 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3677 if ( dt2
+ 2*span
== dt1
)
3683 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3690 static void TestTimeHolidays()
3692 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3694 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3695 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3696 dtEnd
= dtStart
.GetLastMonthDay();
3698 wxDateTimeArray hol
;
3699 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3701 const wxChar
*format
= "%d-%b-%Y (%a)";
3703 printf("All holidays between %s and %s:\n",
3704 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3706 size_t count
= hol
.GetCount();
3707 for ( size_t n
= 0; n
< count
; n
++ )
3709 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3715 static void TestTimeZoneBug()
3717 puts("\n*** testing for DST/timezone bug ***\n");
3719 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3720 for ( int i
= 0; i
< 31; i
++ )
3722 printf("Date %s: week day %s.\n",
3723 date
.Format(_T("%d-%m-%Y")).c_str(),
3724 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3726 date
+= wxDateSpan::Day();
3732 static void TestTimeSpanFormat()
3734 puts("\n*** wxTimeSpan tests ***");
3736 static const char *formats
[] =
3738 _T("(default) %H:%M:%S"),
3739 _T("%E weeks and %D days"),
3740 _T("%l milliseconds"),
3741 _T("(with ms) %H:%M:%S:%l"),
3742 _T("100%% of minutes is %M"), // test "%%"
3743 _T("%D days and %H hours"),
3746 wxTimeSpan
ts1(1, 2, 3, 4),
3748 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3750 printf("ts1 = %s\tts2 = %s\n",
3751 ts1
.Format(formats
[n
]).c_str(),
3752 ts2
.Format(formats
[n
]).c_str());
3760 // test compatibility with the old wxDate/wxTime classes
3761 static void TestTimeCompatibility()
3763 puts("\n*** wxDateTime compatibility test ***");
3765 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3766 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3768 double jdnNow
= wxDateTime::Now().GetJDN();
3769 long jdnMidnight
= (long)(jdnNow
- 0.5);
3770 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3772 jdnMidnight
= wxDate().Set().GetJulianDate();
3773 printf("wxDateTime for today: %s\n",
3774 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3776 int flags
= wxEUROPEAN
;//wxFULL;
3779 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3780 for ( int n
= 0; n
< 7; n
++ )
3782 printf("Previous %s is %s\n",
3783 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3784 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3790 #endif // TEST_DATETIME
3792 // ----------------------------------------------------------------------------
3794 // ----------------------------------------------------------------------------
3798 #include <wx/thread.h>
3800 static size_t gs_counter
= (size_t)-1;
3801 static wxCriticalSection gs_critsect
;
3802 static wxCondition gs_cond
;
3804 class MyJoinableThread
: public wxThread
3807 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3808 { m_n
= n
; Create(); }
3810 // thread execution starts here
3811 virtual ExitCode
Entry();
3817 wxThread::ExitCode
MyJoinableThread::Entry()
3819 unsigned long res
= 1;
3820 for ( size_t n
= 1; n
< m_n
; n
++ )
3824 // it's a loooong calculation :-)
3828 return (ExitCode
)res
;
3831 class MyDetachedThread
: public wxThread
3834 MyDetachedThread(size_t n
, char ch
)
3838 m_cancelled
= FALSE
;
3843 // thread execution starts here
3844 virtual ExitCode
Entry();
3847 virtual void OnExit();
3850 size_t m_n
; // number of characters to write
3851 char m_ch
; // character to write
3853 bool m_cancelled
; // FALSE if we exit normally
3856 wxThread::ExitCode
MyDetachedThread::Entry()
3859 wxCriticalSectionLocker
lock(gs_critsect
);
3860 if ( gs_counter
== (size_t)-1 )
3866 for ( size_t n
= 0; n
< m_n
; n
++ )
3868 if ( TestDestroy() )
3878 wxThread::Sleep(100);
3884 void MyDetachedThread::OnExit()
3886 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3888 wxCriticalSectionLocker
lock(gs_critsect
);
3889 if ( !--gs_counter
&& !m_cancelled
)
3893 void TestDetachedThreads()
3895 puts("\n*** Testing detached threads ***");
3897 static const size_t nThreads
= 3;
3898 MyDetachedThread
*threads
[nThreads
];
3900 for ( n
= 0; n
< nThreads
; n
++ )
3902 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3905 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3906 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3908 for ( n
= 0; n
< nThreads
; n
++ )
3913 // wait until all threads terminate
3919 void TestJoinableThreads()
3921 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3923 // calc 10! in the background
3924 MyJoinableThread
thread(10);
3927 printf("\nThread terminated with exit code %lu.\n",
3928 (unsigned long)thread
.Wait());
3931 void TestThreadSuspend()
3933 puts("\n*** Testing thread suspend/resume functions ***");
3935 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3939 // this is for this demo only, in a real life program we'd use another
3940 // condition variable which would be signaled from wxThread::Entry() to
3941 // tell us that the thread really started running - but here just wait a
3942 // bit and hope that it will be enough (the problem is, of course, that
3943 // the thread might still not run when we call Pause() which will result
3945 wxThread::Sleep(300);
3947 for ( size_t n
= 0; n
< 3; n
++ )
3951 puts("\nThread suspended");
3954 // don't sleep but resume immediately the first time
3955 wxThread::Sleep(300);
3957 puts("Going to resume the thread");
3962 puts("Waiting until it terminates now");
3964 // wait until the thread terminates
3970 void TestThreadDelete()
3972 // As above, using Sleep() is only for testing here - we must use some
3973 // synchronisation object instead to ensure that the thread is still
3974 // running when we delete it - deleting a detached thread which already
3975 // terminated will lead to a crash!
3977 puts("\n*** Testing thread delete function ***");
3979 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3983 puts("\nDeleted a thread which didn't start to run yet.");
3985 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3989 wxThread::Sleep(300);
3993 puts("\nDeleted a running thread.");
3995 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3999 wxThread::Sleep(300);
4005 puts("\nDeleted a sleeping thread.");
4007 MyJoinableThread
thread3(20);
4012 puts("\nDeleted a joinable thread.");
4014 MyJoinableThread
thread4(2);
4017 wxThread::Sleep(300);
4021 puts("\nDeleted a joinable thread which already terminated.");
4026 #endif // TEST_THREADS
4028 // ----------------------------------------------------------------------------
4030 // ----------------------------------------------------------------------------
4034 static void PrintArray(const char* name
, const wxArrayString
& array
)
4036 printf("Dump of the array '%s'\n", name
);
4038 size_t nCount
= array
.GetCount();
4039 for ( size_t n
= 0; n
< nCount
; n
++ )
4041 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4045 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4047 printf("Dump of the array '%s'\n", name
);
4049 size_t nCount
= array
.GetCount();
4050 for ( size_t n
= 0; n
< nCount
; n
++ )
4052 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4056 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4057 const wxString
& second
)
4059 return first
.length() - second
.length();
4062 int wxCMPFUNC_CONV
IntCompare(int *first
,
4065 return *first
- *second
;
4068 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4071 return *second
- *first
;
4074 static void TestArrayOfInts()
4076 puts("*** Testing wxArrayInt ***\n");
4087 puts("After sort:");
4091 puts("After reverse sort:");
4092 a
.Sort(IntRevCompare
);
4096 #include "wx/dynarray.h"
4098 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4099 #include "wx/arrimpl.cpp"
4100 WX_DEFINE_OBJARRAY(ArrayBars
);
4102 static void TestArrayOfObjects()
4104 puts("*** Testing wxObjArray ***\n");
4108 Bar
bar("second bar");
4110 printf("Initially: %u objects in the array, %u objects total.\n",
4111 bars
.GetCount(), Bar::GetNumber());
4113 bars
.Add(new Bar("first bar"));
4116 printf("Now: %u objects in the array, %u objects total.\n",
4117 bars
.GetCount(), Bar::GetNumber());
4121 printf("After Empty(): %u objects in the array, %u objects total.\n",
4122 bars
.GetCount(), Bar::GetNumber());
4125 printf("Finally: no more objects in the array, %u objects total.\n",
4129 #endif // TEST_ARRAYS
4131 // ----------------------------------------------------------------------------
4133 // ----------------------------------------------------------------------------
4137 #include "wx/timer.h"
4138 #include "wx/tokenzr.h"
4140 static void TestStringConstruction()
4142 puts("*** Testing wxString constructores ***");
4144 #define TEST_CTOR(args, res) \
4147 printf("wxString%s = %s ", #args, s.c_str()); \
4154 printf("(ERROR: should be %s)\n", res); \
4158 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4159 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4160 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4161 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4163 static const wxChar
*s
= _T("?really!");
4164 const wxChar
*start
= wxStrchr(s
, _T('r'));
4165 const wxChar
*end
= wxStrchr(s
, _T('!'));
4166 TEST_CTOR((start
, end
), _T("really"));
4171 static void TestString()
4181 for (int i
= 0; i
< 1000000; ++i
)
4185 c
= "! How'ya doin'?";
4188 c
= "Hello world! What's up?";
4193 printf ("TestString elapsed time: %ld\n", sw
.Time());
4196 static void TestPChar()
4204 for (int i
= 0; i
< 1000000; ++i
)
4206 strcpy (a
, "Hello");
4207 strcpy (b
, " world");
4208 strcpy (c
, "! How'ya doin'?");
4211 strcpy (c
, "Hello world! What's up?");
4212 if (strcmp (c
, a
) == 0)
4216 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4219 static void TestStringSub()
4221 wxString
s("Hello, world!");
4223 puts("*** Testing wxString substring extraction ***");
4225 printf("String = '%s'\n", s
.c_str());
4226 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4227 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4228 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4229 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4230 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4231 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4233 static const wxChar
*prefixes
[] =
4237 _T("Hello, world!"),
4238 _T("Hello, world!!!"),
4244 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4246 wxString prefix
= prefixes
[n
], rest
;
4247 bool rc
= s
.StartsWith(prefix
, &rest
);
4248 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4251 printf(" (the rest is '%s')\n", rest
.c_str());
4262 static void TestStringFormat()
4264 puts("*** Testing wxString formatting ***");
4267 s
.Printf("%03d", 18);
4269 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4270 printf("Number 18: %s\n", s
.c_str());
4275 // returns "not found" for npos, value for all others
4276 static wxString
PosToString(size_t res
)
4278 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4279 : wxString::Format(_T("%u"), res
);
4283 static void TestStringFind()
4285 puts("*** Testing wxString find() functions ***");
4287 static const wxChar
*strToFind
= _T("ell");
4288 static const struct StringFindTest
4292 result
; // of searching "ell" in str
4295 { _T("Well, hello world"), 0, 1 },
4296 { _T("Well, hello world"), 6, 7 },
4297 { _T("Well, hello world"), 9, wxString::npos
},
4300 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4302 const StringFindTest
& ft
= findTestData
[n
];
4303 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4305 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4306 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4308 size_t resTrue
= ft
.result
;
4309 if ( res
== resTrue
)
4315 printf(_T("(ERROR: should be %s)\n"),
4316 PosToString(resTrue
).c_str());
4323 static void TestStringTokenizer()
4325 puts("*** Testing wxStringTokenizer ***");
4327 static const wxChar
*modeNames
[] =
4331 _T("return all empty"),
4336 static const struct StringTokenizerTest
4338 const wxChar
*str
; // string to tokenize
4339 const wxChar
*delims
; // delimiters to use
4340 size_t count
; // count of token
4341 wxStringTokenizerMode mode
; // how should we tokenize it
4342 } tokenizerTestData
[] =
4344 { _T(""), _T(" "), 0 },
4345 { _T("Hello, world"), _T(" "), 2 },
4346 { _T("Hello, world "), _T(" "), 2 },
4347 { _T("Hello, world"), _T(","), 2 },
4348 { _T("Hello, world!"), _T(",!"), 2 },
4349 { _T("Hello,, world!"), _T(",!"), 3 },
4350 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4351 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4352 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4353 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4354 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4355 { _T("01/02/99"), _T("/-"), 3 },
4356 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4359 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4361 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4362 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4364 size_t count
= tkz
.CountTokens();
4365 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4366 MakePrintable(tt
.str
).c_str(),
4368 MakePrintable(tt
.delims
).c_str(),
4369 modeNames
[tkz
.GetMode()]);
4370 if ( count
== tt
.count
)
4376 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4381 // if we emulate strtok(), check that we do it correctly
4382 wxChar
*buf
, *s
= NULL
, *last
;
4384 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4386 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4387 wxStrcpy(buf
, tt
.str
);
4389 s
= wxStrtok(buf
, tt
.delims
, &last
);
4396 // now show the tokens themselves
4398 while ( tkz
.HasMoreTokens() )
4400 wxString token
= tkz
.GetNextToken();
4402 printf(_T("\ttoken %u: '%s'"),
4404 MakePrintable(token
).c_str());
4414 printf(" (ERROR: should be %s)\n", s
);
4417 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4421 // nothing to compare with
4426 if ( count2
!= count
)
4428 puts(_T("\tERROR: token count mismatch"));
4437 static void TestStringReplace()
4439 puts("*** Testing wxString::replace ***");
4441 static const struct StringReplaceTestData
4443 const wxChar
*original
; // original test string
4444 size_t start
, len
; // the part to replace
4445 const wxChar
*replacement
; // the replacement string
4446 const wxChar
*result
; // and the expected result
4447 } stringReplaceTestData
[] =
4449 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4450 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4451 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4452 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4453 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4456 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4458 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4460 wxString original
= data
.original
;
4461 original
.replace(data
.start
, data
.len
, data
.replacement
);
4463 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4464 data
.original
, data
.start
, data
.len
, data
.replacement
,
4467 if ( original
== data
.result
)
4473 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4480 #endif // TEST_STRINGS
4482 // ----------------------------------------------------------------------------
4484 // ----------------------------------------------------------------------------
4486 int main(int argc
, char **argv
)
4488 if ( !wxInitialize() )
4490 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4495 #endif // TEST_CHARSET
4498 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4500 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4501 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4503 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4504 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4505 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
4506 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
4508 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4509 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4514 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4516 parser
.AddOption("project_name", "", "full path to project file",
4517 wxCMD_LINE_VAL_STRING
,
4518 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4520 switch ( parser
.Parse() )
4523 wxLogMessage("Help was given, terminating.");
4527 ShowCmdLine(parser
);
4531 wxLogMessage("Syntax error detected, aborting.");
4534 #endif // TEST_CMDLINE
4545 TestStringConstruction();
4548 TestStringTokenizer();
4549 TestStringReplace();
4551 #endif // TEST_STRINGS
4564 puts("*** Initially:");
4566 PrintArray("a1", a1
);
4568 wxArrayString
a2(a1
);
4569 PrintArray("a2", a2
);
4571 wxSortedArrayString
a3(a1
);
4572 PrintArray("a3", a3
);
4574 puts("*** After deleting a string from a1");
4577 PrintArray("a1", a1
);
4578 PrintArray("a2", a2
);
4579 PrintArray("a3", a3
);
4581 puts("*** After reassigning a1 to a2 and a3");
4583 PrintArray("a2", a2
);
4584 PrintArray("a3", a3
);
4586 puts("*** After sorting a1");
4588 PrintArray("a1", a1
);
4590 puts("*** After sorting a1 in reverse order");
4592 PrintArray("a1", a1
);
4594 puts("*** After sorting a1 by the string length");
4595 a1
.Sort(StringLenCompare
);
4596 PrintArray("a1", a1
);
4598 TestArrayOfObjects();
4601 #endif // TEST_ARRAYS
4607 #ifdef TEST_DLLLOADER
4609 #endif // TEST_DLLLOADER
4613 #endif // TEST_ENVIRON
4617 #endif // TEST_EXECUTE
4619 #ifdef TEST_FILECONF
4621 #endif // TEST_FILECONF
4629 #endif // TEST_LOCALE
4633 for ( size_t n
= 0; n
< 8000; n
++ )
4635 s
<< (char)('A' + (n
% 26));
4639 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4641 // this one shouldn't be truncated
4644 // but this one will because log functions use fixed size buffer
4645 // (note that it doesn't need '\n' at the end neither - will be added
4647 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4659 #ifdef TEST_FILENAME
4660 TestFileNameSplit();
4663 TestFileNameConstruction();
4665 TestFileNameComparison();
4666 TestFileNameOperations();
4668 #endif // TEST_FILENAME
4671 int nCPUs
= wxThread::GetCPUCount();
4672 printf("This system has %d CPUs\n", nCPUs
);
4674 wxThread::SetConcurrency(nCPUs
);
4676 if ( argc
> 1 && argv
[1][0] == 't' )
4677 wxLog::AddTraceMask("thread");
4680 TestDetachedThreads();
4682 TestJoinableThreads();
4684 TestThreadSuspend();
4688 #endif // TEST_THREADS
4690 #ifdef TEST_LONGLONG
4691 // seed pseudo random generator
4692 srand((unsigned)time(NULL
));
4700 TestMultiplication();
4703 TestLongLongConversion();
4704 TestBitOperations();
4706 TestLongLongComparison();
4707 #endif // TEST_LONGLONG
4714 wxLog::AddTraceMask(_T("mime"));
4722 TestMimeAssociate();
4725 #ifdef TEST_INFO_FUNCTIONS
4728 #endif // TEST_INFO_FUNCTIONS
4730 #ifdef TEST_PATHLIST
4732 #endif // TEST_PATHLIST
4736 #endif // TEST_REGCONF
4738 #ifdef TEST_REGISTRY
4741 TestRegistryAssociation();
4742 #endif // TEST_REGISTRY
4750 #endif // TEST_SOCKETS
4753 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4754 if ( TestFtpConnect() )
4765 TestFtpInteractive();
4767 //else: connecting to the FTP server failed
4777 #endif // TEST_STREAMS
4781 #endif // TEST_TIMER
4783 #ifdef TEST_DATETIME
4796 TestTimeArithmetics();
4803 TestTimeSpanFormat();
4805 TestDateTimeInteractive();
4806 #endif // TEST_DATETIME
4809 puts("Sleeping for 3 seconds... z-z-z-z-z...");
4811 #endif // TEST_USLEEP
4817 #endif // TEST_VCARD
4821 #endif // TEST_WCHAR
4825 TestZipStreamRead();
4826 TestZipFileSystem();
4831 TestZlibStreamWrite();
4832 TestZlibStreamRead();