1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWindows
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
22 #include <wx/string.h>
26 // without this pragma, the stupid compiler precompiles #defines below so that
27 // changing them doesn't "take place" later!
32 // ----------------------------------------------------------------------------
33 // conditional compilation
34 // ----------------------------------------------------------------------------
36 // what to test (in alphabetic order)?
39 //#define TEST_CMDLINE
40 //#define TEST_DATETIME
42 //#define TEST_DLLLOADER
43 //#define TEST_ENVIRON
44 //#define TEST_EXECUTE
46 //#define TEST_FILECONF
47 //#define TEST_FILENAME
50 //#define TEST_INFO_FUNCTIONS
54 //#define TEST_LONGLONG
56 //#define TEST_PATHLIST
57 //#define TEST_REGISTRY
58 //#define TEST_SOCKETS
59 //#define TEST_STREAMS
60 //#define TEST_STRINGS
61 //#define TEST_THREADS
63 //#define TEST_VCARD -- don't enable this (VZ)
74 // ----------------------------------------------------------------------------
75 // test class for container objects
76 // ----------------------------------------------------------------------------
78 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
80 class Bar
// Foo is already taken in the hash test
83 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
86 static size_t GetNumber() { return ms_bars
; }
88 const char *GetName() const { return m_name
; }
93 static size_t ms_bars
;
96 size_t Bar::ms_bars
= 0;
98 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
100 // ============================================================================
102 // ============================================================================
104 // ----------------------------------------------------------------------------
106 // ----------------------------------------------------------------------------
108 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
110 // replace TABs with \t and CRs with \n
111 static wxString
MakePrintable(const wxChar
*s
)
114 (void)str
.Replace(_T("\t"), _T("\\t"));
115 (void)str
.Replace(_T("\n"), _T("\\n"));
116 (void)str
.Replace(_T("\r"), _T("\\r"));
121 #endif // MakePrintable() is used
123 // ----------------------------------------------------------------------------
125 // ----------------------------------------------------------------------------
129 #include <wx/cmdline.h>
130 #include <wx/datetime.h>
132 static void ShowCmdLine(const wxCmdLineParser
& parser
)
134 wxString s
= "Input files: ";
136 size_t count
= parser
.GetParamCount();
137 for ( size_t param
= 0; param
< count
; param
++ )
139 s
<< parser
.GetParam(param
) << ' ';
143 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
144 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
149 if ( parser
.Found("o", &strVal
) )
150 s
<< "Output file:\t" << strVal
<< '\n';
151 if ( parser
.Found("i", &strVal
) )
152 s
<< "Input dir:\t" << strVal
<< '\n';
153 if ( parser
.Found("s", &lVal
) )
154 s
<< "Size:\t" << lVal
<< '\n';
155 if ( parser
.Found("d", &dt
) )
156 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
157 if ( parser
.Found("project_name", &strVal
) )
158 s
<< "Project:\t" << strVal
<< '\n';
163 #endif // TEST_CMDLINE
165 // ----------------------------------------------------------------------------
167 // ----------------------------------------------------------------------------
173 static void TestDirEnumHelper(wxDir
& dir
,
174 int flags
= wxDIR_DEFAULT
,
175 const wxString
& filespec
= wxEmptyString
)
179 if ( !dir
.IsOpened() )
182 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
185 printf("\t%s\n", filename
.c_str());
187 cont
= dir
.GetNext(&filename
);
193 static void TestDirEnum()
195 wxDir
dir(wxGetCwd());
197 puts("Enumerating everything in current directory:");
198 TestDirEnumHelper(dir
);
200 puts("Enumerating really everything in current directory:");
201 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
203 puts("Enumerating object files in current directory:");
204 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
206 puts("Enumerating directories in current directory:");
207 TestDirEnumHelper(dir
, wxDIR_DIRS
);
209 puts("Enumerating files in current directory:");
210 TestDirEnumHelper(dir
, wxDIR_FILES
);
212 puts("Enumerating files including hidden in current directory:");
213 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
217 #elif defined(__WXMSW__)
220 #error "don't know where the root directory is"
223 puts("Enumerating everything in root directory:");
224 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
226 puts("Enumerating directories in root directory:");
227 TestDirEnumHelper(dir
, wxDIR_DIRS
);
229 puts("Enumerating files in root directory:");
230 TestDirEnumHelper(dir
, wxDIR_FILES
);
232 puts("Enumerating files including hidden in root directory:");
233 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
235 puts("Enumerating files in non existing directory:");
236 wxDir
dirNo("nosuchdir");
237 TestDirEnumHelper(dirNo
);
242 // ----------------------------------------------------------------------------
244 // ----------------------------------------------------------------------------
246 #ifdef TEST_DLLLOADER
248 #include <wx/dynlib.h>
250 static void TestDllLoad()
252 #if defined(__WXMSW__)
253 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
254 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
255 #elif defined(__UNIX__)
256 // weird: using just libc.so does *not* work!
257 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
258 static const wxChar
*FUNC_NAME
= _T("strlen");
260 #error "don't know how to test wxDllLoader on this platform"
263 puts("*** testing wxDllLoader ***\n");
265 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
268 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
272 typedef int (*strlenType
)(char *);
273 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
276 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
277 FUNC_NAME
, LIB_NAME
);
281 if ( pfnStrlen("foo") != 3 )
283 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
291 wxDllLoader::UnloadLibrary(dllHandle
);
295 #endif // TEST_DLLLOADER
297 // ----------------------------------------------------------------------------
299 // ----------------------------------------------------------------------------
303 #include <wx/utils.h>
305 static wxString
MyGetEnv(const wxString
& var
)
308 if ( !wxGetEnv(var
, &val
) )
311 val
= wxString(_T('\'')) + val
+ _T('\'');
316 static void TestEnvironment()
318 const wxChar
*var
= _T("wxTestVar");
320 puts("*** testing environment access functions ***");
322 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
323 wxSetEnv(var
, _T("value for wxTestVar"));
324 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
325 wxSetEnv(var
, _T("another value"));
326 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
328 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
329 printf("PATH = %s\n", MyGetEnv(_T("PATH")));
332 #endif // TEST_ENVIRON
334 // ----------------------------------------------------------------------------
336 // ----------------------------------------------------------------------------
340 #include <wx/utils.h>
342 static void TestExecute()
344 puts("*** testing wxExecute ***");
347 #define COMMAND "cat -n ../../Makefile" // "echo hi"
348 #define SHELL_COMMAND "echo hi from shell"
349 #define REDIRECT_COMMAND COMMAND // "date"
350 #elif defined(__WXMSW__)
351 #define COMMAND "command.com -c 'echo hi'"
352 #define SHELL_COMMAND "echo hi"
353 #define REDIRECT_COMMAND COMMAND
355 #error "no command to exec"
358 printf("Testing wxShell: ");
360 if ( wxShell(SHELL_COMMAND
) )
365 printf("Testing wxExecute: ");
367 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
372 #if 0 // no, it doesn't work (yet?)
373 printf("Testing async wxExecute: ");
375 if ( wxExecute(COMMAND
) != 0 )
376 puts("Ok (command launched).");
381 printf("Testing wxExecute with redirection:\n");
382 wxArrayString output
;
383 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
389 size_t count
= output
.GetCount();
390 for ( size_t n
= 0; n
< count
; n
++ )
392 printf("\t%s\n", output
[n
].c_str());
399 #endif // TEST_EXECUTE
401 // ----------------------------------------------------------------------------
403 // ----------------------------------------------------------------------------
408 #include <wx/ffile.h>
409 #include <wx/textfile.h>
411 static void TestFileRead()
413 puts("*** wxFile read test ***");
415 wxFile
file(_T("testdata.fc"));
416 if ( file
.IsOpened() )
418 printf("File length: %lu\n", file
.Length());
420 puts("File dump:\n----------");
422 static const off_t len
= 1024;
426 off_t nRead
= file
.Read(buf
, len
);
427 if ( nRead
== wxInvalidOffset
)
429 printf("Failed to read the file.");
433 fwrite(buf
, nRead
, 1, stdout
);
443 printf("ERROR: can't open test file.\n");
449 static void TestTextFileRead()
451 puts("*** wxTextFile read test ***");
453 wxTextFile
file(_T("testdata.fc"));
456 printf("Number of lines: %u\n", file
.GetLineCount());
457 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
461 puts("\nDumping the entire file:");
462 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
464 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
466 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
468 puts("\nAnd now backwards:");
469 for ( s
= file
.GetLastLine();
470 file
.GetCurrentLine() != 0;
471 s
= file
.GetPrevLine() )
473 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
475 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
479 printf("ERROR: can't open '%s'\n", file
.GetName());
485 static void TestFileCopy()
487 puts("*** Testing wxCopyFile ***");
489 static const wxChar
*filename1
= _T("testdata.fc");
490 static const wxChar
*filename2
= _T("test2");
491 if ( !wxCopyFile(filename1
, filename2
) )
493 puts("ERROR: failed to copy file");
497 wxFFile
f1(filename1
, "rb"),
500 if ( !f1
.IsOpened() || !f2
.IsOpened() )
502 puts("ERROR: failed to open file(s)");
507 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
509 puts("ERROR: failed to read file(s)");
513 if ( (s1
.length() != s2
.length()) ||
514 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
516 puts("ERROR: copy error!");
520 puts("File was copied ok.");
526 if ( !wxRemoveFile(filename2
) )
528 puts("ERROR: failed to remove the file");
536 // ----------------------------------------------------------------------------
538 // ----------------------------------------------------------------------------
542 #include <wx/confbase.h>
543 #include <wx/fileconf.h>
545 static const struct FileConfTestData
547 const wxChar
*name
; // value name
548 const wxChar
*value
; // the value from the file
551 { _T("value1"), _T("one") },
552 { _T("value2"), _T("two") },
553 { _T("novalue"), _T("default") },
556 static void TestFileConfRead()
558 puts("*** testing wxFileConfig loading/reading ***");
560 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
561 _T("testdata.fc"), wxEmptyString
,
562 wxCONFIG_USE_RELATIVE_PATH
);
564 // test simple reading
565 puts("\nReading config file:");
566 wxString
defValue(_T("default")), value
;
567 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
569 const FileConfTestData
& data
= fcTestData
[n
];
570 value
= fileconf
.Read(data
.name
, defValue
);
571 printf("\t%s = %s ", data
.name
, value
.c_str());
572 if ( value
== data
.value
)
578 printf("(ERROR: should be %s)\n", data
.value
);
582 // test enumerating the entries
583 puts("\nEnumerating all root entries:");
586 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
589 printf("\t%s = %s\n",
591 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
593 cont
= fileconf
.GetNextEntry(name
, dummy
);
597 #endif // TEST_FILECONF
599 // ----------------------------------------------------------------------------
601 // ----------------------------------------------------------------------------
605 #include <wx/filename.h>
607 static struct FileNameInfo
609 const wxChar
*fullname
;
615 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
616 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
617 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
618 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
619 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
620 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
621 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
622 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
625 static void TestFileNameConstruction()
627 puts("*** testing wxFileName construction ***");
629 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
631 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
633 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
634 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
636 puts("ERROR (couldn't be normalized)");
640 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
647 static void TestFileNameSplit()
649 puts("*** testing wxFileName splitting ***");
651 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
653 const FileNameInfo
&fni
= filenames
[n
];
654 wxString path
, name
, ext
;
655 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
657 printf("%s -> path = '%s', name = '%s', ext = '%s'",
658 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
659 if ( path
!= fni
.path
)
660 printf(" (ERROR: path = '%s')", fni
.path
);
661 if ( name
!= fni
.name
)
662 printf(" (ERROR: name = '%s')", fni
.name
);
663 if ( ext
!= fni
.ext
)
664 printf(" (ERROR: ext = '%s')", fni
.ext
);
671 static void TestFileNameComparison()
676 static void TestFileNameOperations()
681 static void TestFileNameCwd()
686 #endif // TEST_FILENAME
688 // ----------------------------------------------------------------------------
690 // ----------------------------------------------------------------------------
698 Foo(int n_
) { n
= n_
; count
++; }
706 size_t Foo::count
= 0;
708 WX_DECLARE_LIST(Foo
, wxListFoos
);
709 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
711 #include <wx/listimpl.cpp>
713 WX_DEFINE_LIST(wxListFoos
);
715 static void TestHash()
717 puts("*** Testing wxHashTable ***\n");
721 hash
.DeleteContents(TRUE
);
723 printf("Hash created: %u foos in hash, %u foos totally\n",
724 hash
.GetCount(), Foo::count
);
726 static const int hashTestData
[] =
728 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
732 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
734 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
737 printf("Hash filled: %u foos in hash, %u foos totally\n",
738 hash
.GetCount(), Foo::count
);
740 puts("Hash access test:");
741 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
743 printf("\tGetting element with key %d, value %d: ",
745 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
748 printf("ERROR, not found.\n");
752 printf("%d (%s)\n", foo
->n
,
753 (size_t)foo
->n
== n
? "ok" : "ERROR");
757 printf("\nTrying to get an element not in hash: ");
759 if ( hash
.Get(1234) || hash
.Get(1, 0) )
761 puts("ERROR: found!");
765 puts("ok (not found)");
769 printf("Hash destroyed: %u foos left\n", Foo::count
);
774 // ----------------------------------------------------------------------------
776 // ----------------------------------------------------------------------------
782 WX_DECLARE_LIST(Bar
, wxListBars
);
783 #include <wx/listimpl.cpp>
784 WX_DEFINE_LIST(wxListBars
);
786 static void TestListCtor()
788 puts("*** Testing wxList construction ***\n");
792 list1
.Append(new Bar(_T("first")));
793 list1
.Append(new Bar(_T("second")));
795 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
796 list1
.GetCount(), Bar::GetNumber());
801 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
802 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
804 list1
.DeleteContents(TRUE
);
807 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
812 // ----------------------------------------------------------------------------
814 // ----------------------------------------------------------------------------
819 #include "wx/utils.h" // for wxSetEnv
821 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
823 // find the name of the language from its value
824 static const char *GetLangName(int lang
)
826 static const char *languageNames
[] =
847 "ARABIC_SAUDI_ARABIA",
872 "CHINESE_SIMPLIFIED",
873 "CHINESE_TRADITIONAL",
895 "ENGLISH_NEW_ZEALAND",
896 "ENGLISH_PHILIPPINES",
897 "ENGLISH_SOUTH_AFRICA",
918 "GERMAN_LIECHTENSTEIN",
960 "MALAY_BRUNEI_DARUSSALAM",
979 "PORTUGUESE_BRAZILIAN",
1004 "SPANISH_ARGENTINA",
1008 "SPANISH_COSTA_RICA",
1009 "SPANISH_DOMINICAN_REPUBLIC",
1011 "SPANISH_EL_SALVADOR",
1012 "SPANISH_GUATEMALA",
1016 "SPANISH_NICARAGUA",
1020 "SPANISH_PUERTO_RICO",
1023 "SPANISH_VENEZUELA",
1060 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1061 return languageNames
[lang
];
1066 static void TestDefaultLang()
1068 puts("*** Testing wxLocale::GetSystemLanguage ***");
1070 static const wxChar
*langStrings
[] =
1072 NULL
, // system default
1079 _T("de_DE.iso88591"),
1081 _T("?"), // invalid lang spec
1082 _T("klingonese"), // I bet on some systems it does exist...
1085 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1087 const char *langStr
= langStrings
[n
];
1089 wxSetEnv(_T("LC_ALL"), langStr
);
1091 int lang
= gs_localeDefault
.GetSystemLanguage();
1092 printf("Locale for '%s' is %s.\n",
1093 langStr
? langStr
: "system default", GetLangName(lang
));
1097 #endif // TEST_LOCALE
1099 // ----------------------------------------------------------------------------
1101 // ----------------------------------------------------------------------------
1105 #include <wx/mimetype.h>
1107 static void TestMimeEnum()
1109 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1111 wxArrayString mimetypes
;
1113 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1115 printf("*** All %u known filetypes: ***\n", count
);
1120 for ( size_t n
= 0; n
< count
; n
++ )
1122 wxFileType
*filetype
=
1123 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1126 printf("nothing known about the filetype '%s'!\n",
1127 mimetypes
[n
].c_str());
1131 filetype
->GetDescription(&desc
);
1132 filetype
->GetExtensions(exts
);
1134 filetype
->GetIcon(NULL
);
1137 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1140 extsAll
<< _T(", ");
1144 printf("\t%s: %s (%s)\n",
1145 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1151 static void TestMimeOverride()
1153 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1155 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1156 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1158 if ( wxFile::Exists(mailcap
) )
1159 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1161 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1163 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1166 if ( wxFile::Exists(mimetypes
) )
1167 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1169 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1171 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1177 static void TestMimeFilename()
1179 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1181 static const wxChar
*filenames
[] =
1188 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1190 const wxString fname
= filenames
[n
];
1191 wxString ext
= fname
.AfterLast(_T('.'));
1192 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1195 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1200 if ( !ft
->GetDescription(&desc
) )
1201 desc
= _T("<no description>");
1204 if ( !ft
->GetOpenCommand(&cmd
,
1205 wxFileType::MessageParameters(fname
, _T(""))) )
1206 cmd
= _T("<no command available>");
1208 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1209 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1218 static void TestMimeAssociate()
1220 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1222 wxFileTypeInfo
ftInfo(
1223 _T("application/x-xyz"),
1224 _T("xyzview '%s'"), // open cmd
1225 _T(""), // print cmd
1226 _T("XYZ File") // description
1227 _T(".xyz"), // extensions
1228 NULL
// end of extensions
1230 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1232 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1235 wxPuts(_T("ERROR: failed to create association!"));
1239 // TODO: read it back
1248 // ----------------------------------------------------------------------------
1249 // misc information functions
1250 // ----------------------------------------------------------------------------
1252 #ifdef TEST_INFO_FUNCTIONS
1254 #include <wx/utils.h>
1256 static void TestOsInfo()
1258 puts("*** Testing OS info functions ***\n");
1261 wxGetOsVersion(&major
, &minor
);
1262 printf("Running under: %s, version %d.%d\n",
1263 wxGetOsDescription().c_str(), major
, minor
);
1265 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1267 printf("Host name is %s (%s).\n",
1268 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1273 static void TestUserInfo()
1275 puts("*** Testing user info functions ***\n");
1277 printf("User id is:\t%s\n", wxGetUserId().c_str());
1278 printf("User name is:\t%s\n", wxGetUserName().c_str());
1279 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1280 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1285 #endif // TEST_INFO_FUNCTIONS
1287 // ----------------------------------------------------------------------------
1289 // ----------------------------------------------------------------------------
1291 #ifdef TEST_LONGLONG
1293 #include <wx/longlong.h>
1294 #include <wx/timer.h>
1296 // make a 64 bit number from 4 16 bit ones
1297 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1299 // get a random 64 bit number
1300 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1302 #if wxUSE_LONGLONG_WX
1303 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1304 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1305 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1306 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1307 #endif // wxUSE_LONGLONG_WX
1309 static void TestSpeed()
1311 static const long max
= 100000000;
1318 for ( n
= 0; n
< max
; n
++ )
1323 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1326 #if wxUSE_LONGLONG_NATIVE
1331 for ( n
= 0; n
< max
; n
++ )
1336 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1338 #endif // wxUSE_LONGLONG_NATIVE
1344 for ( n
= 0; n
< max
; n
++ )
1349 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1353 static void TestLongLongConversion()
1355 puts("*** Testing wxLongLong conversions ***\n");
1359 for ( size_t n
= 0; n
< 100000; n
++ )
1363 #if wxUSE_LONGLONG_NATIVE
1364 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1366 wxASSERT_MSG( a
== b
, "conversions failure" );
1368 puts("Can't do it without native long long type, test skipped.");
1371 #endif // wxUSE_LONGLONG_NATIVE
1373 if ( !(nTested
% 1000) )
1385 static void TestMultiplication()
1387 puts("*** Testing wxLongLong multiplication ***\n");
1391 for ( size_t n
= 0; n
< 100000; n
++ )
1396 #if wxUSE_LONGLONG_NATIVE
1397 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1398 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1400 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1401 #else // !wxUSE_LONGLONG_NATIVE
1402 puts("Can't do it without native long long type, test skipped.");
1405 #endif // wxUSE_LONGLONG_NATIVE
1407 if ( !(nTested
% 1000) )
1419 static void TestDivision()
1421 puts("*** Testing wxLongLong division ***\n");
1425 for ( size_t n
= 0; n
< 100000; n
++ )
1427 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1428 // multiplication will not overflow)
1429 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1431 // get a random long (not wxLongLong for now) to divide it with
1436 #if wxUSE_LONGLONG_NATIVE
1437 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1439 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1440 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1441 #else // !wxUSE_LONGLONG_NATIVE
1442 // verify the result
1443 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1444 #endif // wxUSE_LONGLONG_NATIVE
1446 if ( !(nTested
% 1000) )
1458 static void TestAddition()
1460 puts("*** Testing wxLongLong addition ***\n");
1464 for ( size_t n
= 0; n
< 100000; n
++ )
1470 #if wxUSE_LONGLONG_NATIVE
1471 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1472 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1473 "addition failure" );
1474 #else // !wxUSE_LONGLONG_NATIVE
1475 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1476 #endif // wxUSE_LONGLONG_NATIVE
1478 if ( !(nTested
% 1000) )
1490 static void TestBitOperations()
1492 puts("*** Testing wxLongLong bit operation ***\n");
1496 for ( size_t n
= 0; n
< 100000; n
++ )
1500 #if wxUSE_LONGLONG_NATIVE
1501 for ( size_t n
= 0; n
< 33; n
++ )
1504 #else // !wxUSE_LONGLONG_NATIVE
1505 puts("Can't do it without native long long type, test skipped.");
1508 #endif // wxUSE_LONGLONG_NATIVE
1510 if ( !(nTested
% 1000) )
1522 static void TestLongLongComparison()
1524 puts("*** Testing wxLongLong comparison ***\n");
1526 static const long testLongs
[] =
1537 static const long ls
[2] =
1543 wxLongLongWx lls
[2];
1547 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1551 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1553 res
= lls
[m
] > testLongs
[n
];
1554 printf("0x%lx > 0x%lx is %s (%s)\n",
1555 ls
[m
], testLongs
[n
], res
? "true" : "false",
1556 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1558 res
= lls
[m
] < testLongs
[n
];
1559 printf("0x%lx < 0x%lx is %s (%s)\n",
1560 ls
[m
], testLongs
[n
], res
? "true" : "false",
1561 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1563 res
= lls
[m
] == testLongs
[n
];
1564 printf("0x%lx == 0x%lx is %s (%s)\n",
1565 ls
[m
], testLongs
[n
], res
? "true" : "false",
1566 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1574 #endif // TEST_LONGLONG
1576 // ----------------------------------------------------------------------------
1578 // ----------------------------------------------------------------------------
1580 #ifdef TEST_PATHLIST
1582 static void TestPathList()
1584 puts("*** Testing wxPathList ***\n");
1586 wxPathList pathlist
;
1587 pathlist
.AddEnvList("PATH");
1588 wxString path
= pathlist
.FindValidPath("ls");
1591 printf("ERROR: command not found in the path.\n");
1595 printf("Command found in the path as '%s'.\n", path
.c_str());
1599 #endif // TEST_PATHLIST
1601 // ----------------------------------------------------------------------------
1603 // ----------------------------------------------------------------------------
1605 // this is for MSW only
1607 #undef TEST_REGISTRY
1610 #ifdef TEST_REGISTRY
1612 #include <wx/msw/registry.h>
1614 // I chose this one because I liked its name, but it probably only exists under
1616 static const wxChar
*TESTKEY
=
1617 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1619 static void TestRegistryRead()
1621 puts("*** testing registry reading ***");
1623 wxRegKey
key(TESTKEY
);
1624 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1627 puts("ERROR: test key can't be opened, aborting test.");
1632 size_t nSubKeys
, nValues
;
1633 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1635 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1638 printf("Enumerating values:\n");
1642 bool cont
= key
.GetFirstValue(value
, dummy
);
1645 printf("Value '%s': type ", value
.c_str());
1646 switch ( key
.GetValueType(value
) )
1648 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1649 case wxRegKey::Type_String
: printf("SZ"); break;
1650 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1651 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1652 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1653 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1654 default: printf("other (unknown)"); break;
1657 printf(", value = ");
1658 if ( key
.IsNumericValue(value
) )
1661 key
.QueryValue(value
, &val
);
1667 key
.QueryValue(value
, val
);
1668 printf("'%s'", val
.c_str());
1670 key
.QueryRawValue(value
, val
);
1671 printf(" (raw value '%s')", val
.c_str());
1676 cont
= key
.GetNextValue(value
, dummy
);
1680 static void TestRegistryAssociation()
1683 The second call to deleteself genertaes an error message, with a
1684 messagebox saying .flo is crucial to system operation, while the .ddf
1685 call also fails, but with no error message
1690 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1692 key
= "ddxf_auto_file" ;
1693 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1695 key
= "ddxf_auto_file" ;
1696 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1699 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1701 key
= "program \"%1\"" ;
1703 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1705 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1707 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1709 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1713 #endif // TEST_REGISTRY
1715 // ----------------------------------------------------------------------------
1717 // ----------------------------------------------------------------------------
1721 #include <wx/socket.h>
1722 #include <wx/protocol/protocol.h>
1723 #include <wx/protocol/http.h>
1725 static void TestSocketServer()
1727 puts("*** Testing wxSocketServer ***\n");
1729 static const int PORT
= 3000;
1734 wxSocketServer
*server
= new wxSocketServer(addr
);
1735 if ( !server
->Ok() )
1737 puts("ERROR: failed to bind");
1744 printf("Server: waiting for connection on port %d...\n", PORT
);
1746 wxSocketBase
*socket
= server
->Accept();
1749 puts("ERROR: wxSocketServer::Accept() failed.");
1753 puts("Server: got a client.");
1755 server
->SetTimeout(60); // 1 min
1757 while ( socket
->IsConnected() )
1763 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1765 // don't log error if the client just close the connection
1766 if ( socket
->IsConnected() )
1768 puts("ERROR: in wxSocket::Read.");
1788 printf("Server: got '%s'.\n", s
.c_str());
1789 if ( s
== _T("bye") )
1796 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1797 socket
->Write("\r\n", 2);
1798 printf("Server: wrote '%s'.\n", s
.c_str());
1801 puts("Server: lost a client.");
1806 // same as "delete server" but is consistent with GUI programs
1810 static void TestSocketClient()
1812 puts("*** Testing wxSocketClient ***\n");
1814 static const char *hostname
= "www.wxwindows.org";
1817 addr
.Hostname(hostname
);
1820 printf("--- Attempting to connect to %s:80...\n", hostname
);
1822 wxSocketClient client
;
1823 if ( !client
.Connect(addr
) )
1825 printf("ERROR: failed to connect to %s\n", hostname
);
1829 printf("--- Connected to %s:%u...\n",
1830 addr
.Hostname().c_str(), addr
.Service());
1834 // could use simply "GET" here I suppose
1836 wxString::Format("GET http://%s/\r\n", hostname
);
1837 client
.Write(cmdGet
, cmdGet
.length());
1838 printf("--- Sent command '%s' to the server\n",
1839 MakePrintable(cmdGet
).c_str());
1840 client
.Read(buf
, WXSIZEOF(buf
));
1841 printf("--- Server replied:\n%s", buf
);
1845 #endif // TEST_SOCKETS
1847 // ----------------------------------------------------------------------------
1849 // ----------------------------------------------------------------------------
1853 #include <wx/protocol/ftp.h>
1857 #define FTP_ANONYMOUS
1859 #ifdef FTP_ANONYMOUS
1860 static const char *directory
= "/pub";
1861 static const char *filename
= "welcome.msg";
1863 static const char *directory
= "/etc";
1864 static const char *filename
= "issue";
1867 static bool TestFtpConnect()
1869 puts("*** Testing FTP connect ***");
1871 #ifdef FTP_ANONYMOUS
1872 static const char *hostname
= "ftp.wxwindows.org";
1874 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1875 #else // !FTP_ANONYMOUS
1876 static const char *hostname
= "localhost";
1879 fgets(user
, WXSIZEOF(user
), stdin
);
1880 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
1884 printf("Password for %s: ", password
);
1885 fgets(password
, WXSIZEOF(password
), stdin
);
1886 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
1887 ftp
.SetPassword(password
);
1889 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
1890 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
1892 if ( !ftp
.Connect(hostname
) )
1894 printf("ERROR: failed to connect to %s\n", hostname
);
1900 printf("--- Connected to %s, current directory is '%s'\n",
1901 hostname
, ftp
.Pwd().c_str());
1907 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
1908 static void TestFtpWuFtpd()
1911 static const char *hostname
= "ftp.eudora.com";
1912 if ( !ftp
.Connect(hostname
) )
1914 printf("ERROR: failed to connect to %s\n", hostname
);
1918 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
1919 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1922 printf("ERROR: couldn't get input stream for %s\n", filename
);
1926 size_t size
= in
->StreamSize();
1927 printf("Reading file %s (%u bytes)...", filename
, size
);
1929 char *data
= new char[size
];
1930 if ( !in
->Read(data
, size
) )
1932 puts("ERROR: read error");
1936 printf("Successfully retrieved the file.\n");
1945 static void TestFtpList()
1947 puts("*** Testing wxFTP file listing ***\n");
1950 if ( !ftp
.ChDir(directory
) )
1952 printf("ERROR: failed to cd to %s\n", directory
);
1955 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
1957 // test NLIST and LIST
1958 wxArrayString files
;
1959 if ( !ftp
.GetFilesList(files
) )
1961 puts("ERROR: failed to get NLIST of files");
1965 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
1966 size_t count
= files
.GetCount();
1967 for ( size_t n
= 0; n
< count
; n
++ )
1969 printf("\t%s\n", files
[n
].c_str());
1971 puts("End of the file list");
1974 if ( !ftp
.GetDirList(files
) )
1976 puts("ERROR: failed to get LIST of files");
1980 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
1981 size_t count
= files
.GetCount();
1982 for ( size_t n
= 0; n
< count
; n
++ )
1984 printf("\t%s\n", files
[n
].c_str());
1986 puts("End of the file list");
1989 if ( !ftp
.ChDir(_T("..")) )
1991 puts("ERROR: failed to cd to ..");
1994 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
1997 static void TestFtpDownload()
1999 puts("*** Testing wxFTP download ***\n");
2002 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2005 printf("ERROR: couldn't get input stream for %s\n", filename
);
2009 size_t size
= in
->StreamSize();
2010 printf("Reading file %s (%u bytes)...", filename
, size
);
2013 char *data
= new char[size
];
2014 if ( !in
->Read(data
, size
) )
2016 puts("ERROR: read error");
2020 printf("\nContents of %s:\n%s\n", filename
, data
);
2028 static void TestFtpFileSize()
2030 puts("*** Testing FTP SIZE command ***");
2032 if ( !ftp
.ChDir(directory
) )
2034 printf("ERROR: failed to cd to %s\n", directory
);
2037 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2039 if ( ftp
.FileExists(filename
) )
2041 int size
= ftp
.GetFileSize(filename
);
2043 printf("ERROR: couldn't get size of '%s'\n", filename
);
2045 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2049 printf("ERROR: '%s' doesn't exist\n", filename
);
2053 static void TestFtpMisc()
2055 puts("*** Testing miscellaneous wxFTP functions ***");
2057 if ( ftp
.SendCommand("STAT") != '2' )
2059 puts("ERROR: STAT failed");
2063 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2066 if ( ftp
.SendCommand("HELP SITE") != '2' )
2068 puts("ERROR: HELP SITE failed");
2072 printf("The list of site-specific commands:\n\n%s\n",
2073 ftp
.GetLastResult().c_str());
2077 static void TestFtpInteractive()
2079 puts("\n*** Interactive wxFTP test ***");
2085 printf("Enter FTP command: ");
2086 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2089 // kill the last '\n'
2090 buf
[strlen(buf
) - 1] = 0;
2092 // special handling of LIST and NLST as they require data connection
2093 wxString
start(buf
, 4);
2095 if ( start
== "LIST" || start
== "NLST" )
2098 if ( strlen(buf
) > 4 )
2101 wxArrayString files
;
2102 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2104 printf("ERROR: failed to get %s of files\n", start
.c_str());
2108 printf("--- %s of '%s' under '%s':\n",
2109 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2110 size_t count
= files
.GetCount();
2111 for ( size_t n
= 0; n
< count
; n
++ )
2113 printf("\t%s\n", files
[n
].c_str());
2115 puts("--- End of the file list");
2120 char ch
= ftp
.SendCommand(buf
);
2121 printf("Command %s", ch
? "succeeded" : "failed");
2124 printf(" (return code %c)", ch
);
2127 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2131 puts("\n*** done ***");
2134 static void TestFtpUpload()
2136 puts("*** Testing wxFTP uploading ***\n");
2139 static const char *file1
= "test1";
2140 static const char *file2
= "test2";
2141 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2144 printf("--- Uploading to %s ---\n", file1
);
2145 out
->Write("First hello", 11);
2149 // send a command to check the remote file
2150 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2152 printf("ERROR: STAT %s failed\n", file1
);
2156 printf("STAT %s returned:\n\n%s\n",
2157 file1
, ftp
.GetLastResult().c_str());
2160 out
= ftp
.GetOutputStream(file2
);
2163 printf("--- Uploading to %s ---\n", file1
);
2164 out
->Write("Second hello", 12);
2171 // ----------------------------------------------------------------------------
2173 // ----------------------------------------------------------------------------
2177 #include <wx/wfstream.h>
2178 #include <wx/mstream.h>
2180 static void TestFileStream()
2182 puts("*** Testing wxFileInputStream ***");
2184 static const wxChar
*filename
= _T("testdata.fs");
2186 wxFileOutputStream
fsOut(filename
);
2187 fsOut
.Write("foo", 3);
2190 wxFileInputStream
fsIn(filename
);
2191 printf("File stream size: %u\n", fsIn
.GetSize());
2192 while ( !fsIn
.Eof() )
2194 putchar(fsIn
.GetC());
2197 if ( !wxRemoveFile(filename
) )
2199 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2202 puts("\n*** wxFileInputStream test done ***");
2205 static void TestMemoryStream()
2207 puts("*** Testing wxMemoryInputStream ***");
2210 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2212 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2213 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2214 while ( !memInpStream
.Eof() )
2216 putchar(memInpStream
.GetC());
2219 puts("\n*** wxMemoryInputStream test done ***");
2222 #endif // TEST_STREAMS
2224 // ----------------------------------------------------------------------------
2226 // ----------------------------------------------------------------------------
2230 #include <wx/timer.h>
2231 #include <wx/utils.h>
2233 static void TestStopWatch()
2235 puts("*** Testing wxStopWatch ***\n");
2238 printf("Sleeping 3 seconds...");
2240 printf("\telapsed time: %ldms\n", sw
.Time());
2243 printf("Sleeping 2 more seconds...");
2245 printf("\telapsed time: %ldms\n", sw
.Time());
2248 printf("And 3 more seconds...");
2250 printf("\telapsed time: %ldms\n", sw
.Time());
2253 puts("\nChecking for 'backwards clock' bug...");
2254 for ( size_t n
= 0; n
< 70; n
++ )
2258 for ( size_t m
= 0; m
< 100000; m
++ )
2260 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2262 puts("\ntime is negative - ERROR!");
2272 #endif // TEST_TIMER
2274 // ----------------------------------------------------------------------------
2276 // ----------------------------------------------------------------------------
2280 #include <wx/vcard.h>
2282 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2285 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2289 wxString(_T('\t'), level
).c_str(),
2290 vcObj
->GetName().c_str());
2293 switch ( vcObj
->GetType() )
2295 case wxVCardObject::String
:
2296 case wxVCardObject::UString
:
2299 vcObj
->GetValue(&val
);
2300 value
<< _T('"') << val
<< _T('"');
2304 case wxVCardObject::Int
:
2307 vcObj
->GetValue(&i
);
2308 value
.Printf(_T("%u"), i
);
2312 case wxVCardObject::Long
:
2315 vcObj
->GetValue(&l
);
2316 value
.Printf(_T("%lu"), l
);
2320 case wxVCardObject::None
:
2323 case wxVCardObject::Object
:
2324 value
= _T("<node>");
2328 value
= _T("<unknown value type>");
2332 printf(" = %s", value
.c_str());
2335 DumpVObject(level
+ 1, *vcObj
);
2338 vcObj
= vcard
.GetNextProp(&cookie
);
2342 static void DumpVCardAddresses(const wxVCard
& vcard
)
2344 puts("\nShowing all addresses from vCard:\n");
2348 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2352 int flags
= addr
->GetFlags();
2353 if ( flags
& wxVCardAddress::Domestic
)
2355 flagsStr
<< _T("domestic ");
2357 if ( flags
& wxVCardAddress::Intl
)
2359 flagsStr
<< _T("international ");
2361 if ( flags
& wxVCardAddress::Postal
)
2363 flagsStr
<< _T("postal ");
2365 if ( flags
& wxVCardAddress::Parcel
)
2367 flagsStr
<< _T("parcel ");
2369 if ( flags
& wxVCardAddress::Home
)
2371 flagsStr
<< _T("home ");
2373 if ( flags
& wxVCardAddress::Work
)
2375 flagsStr
<< _T("work ");
2378 printf("Address %u:\n"
2380 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2383 addr
->GetPostOffice().c_str(),
2384 addr
->GetExtAddress().c_str(),
2385 addr
->GetStreet().c_str(),
2386 addr
->GetLocality().c_str(),
2387 addr
->GetRegion().c_str(),
2388 addr
->GetPostalCode().c_str(),
2389 addr
->GetCountry().c_str()
2393 addr
= vcard
.GetNextAddress(&cookie
);
2397 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2399 puts("\nShowing all phone numbers from vCard:\n");
2403 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2407 int flags
= phone
->GetFlags();
2408 if ( flags
& wxVCardPhoneNumber::Voice
)
2410 flagsStr
<< _T("voice ");
2412 if ( flags
& wxVCardPhoneNumber::Fax
)
2414 flagsStr
<< _T("fax ");
2416 if ( flags
& wxVCardPhoneNumber::Cellular
)
2418 flagsStr
<< _T("cellular ");
2420 if ( flags
& wxVCardPhoneNumber::Modem
)
2422 flagsStr
<< _T("modem ");
2424 if ( flags
& wxVCardPhoneNumber::Home
)
2426 flagsStr
<< _T("home ");
2428 if ( flags
& wxVCardPhoneNumber::Work
)
2430 flagsStr
<< _T("work ");
2433 printf("Phone number %u:\n"
2438 phone
->GetNumber().c_str()
2442 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2446 static void TestVCardRead()
2448 puts("*** Testing wxVCard reading ***\n");
2450 wxVCard
vcard(_T("vcard.vcf"));
2451 if ( !vcard
.IsOk() )
2453 puts("ERROR: couldn't load vCard.");
2457 // read individual vCard properties
2458 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2462 vcObj
->GetValue(&value
);
2467 value
= _T("<none>");
2470 printf("Full name retrieved directly: %s\n", value
.c_str());
2473 if ( !vcard
.GetFullName(&value
) )
2475 value
= _T("<none>");
2478 printf("Full name from wxVCard API: %s\n", value
.c_str());
2480 // now show how to deal with multiply occuring properties
2481 DumpVCardAddresses(vcard
);
2482 DumpVCardPhoneNumbers(vcard
);
2484 // and finally show all
2485 puts("\nNow dumping the entire vCard:\n"
2486 "-----------------------------\n");
2488 DumpVObject(0, vcard
);
2492 static void TestVCardWrite()
2494 puts("*** Testing wxVCard writing ***\n");
2497 if ( !vcard
.IsOk() )
2499 puts("ERROR: couldn't create vCard.");
2504 vcard
.SetName("Zeitlin", "Vadim");
2505 vcard
.SetFullName("Vadim Zeitlin");
2506 vcard
.SetOrganization("wxWindows", "R&D");
2508 // just dump the vCard back
2509 puts("Entire vCard follows:\n");
2510 puts(vcard
.Write());
2514 #endif // TEST_VCARD
2516 // ----------------------------------------------------------------------------
2517 // wide char (Unicode) support
2518 // ----------------------------------------------------------------------------
2522 #include <wx/strconv.h>
2523 #include <wx/fontenc.h>
2524 #include <wx/encconv.h>
2525 #include <wx/buffer.h>
2527 static void TestUtf8()
2529 puts("*** Testing UTF8 support ***\n");
2531 static const char textInUtf8
[] =
2533 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2534 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2535 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2536 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2537 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2538 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2539 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2544 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2546 puts("ERROR: UTF-8 decoding failed.");
2550 // using wxEncodingConverter
2552 wxEncodingConverter ec
;
2553 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2554 ec
.Convert(wbuf
, buf
);
2555 #else // using wxCSConv
2556 wxCSConv
conv(_T("koi8-r"));
2557 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2559 puts("ERROR: conversion to KOI8-R failed.");
2564 printf("The resulting string (in koi8-r): %s\n", buf
);
2568 #endif // TEST_WCHAR
2570 // ----------------------------------------------------------------------------
2572 // ----------------------------------------------------------------------------
2576 #include "wx/filesys.h"
2577 #include "wx/fs_zip.h"
2578 #include "wx/zipstrm.h"
2580 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
2582 static void TestZipStreamRead()
2584 puts("*** Testing ZIP reading ***\n");
2586 static const wxChar
*filename
= _T("foo");
2587 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
2588 printf("Archive size: %u\n", istr
.GetSize());
2590 printf("Dumping the file '%s':\n", filename
);
2591 while ( !istr
.Eof() )
2593 putchar(istr
.GetC());
2597 puts("\n----- done ------");
2600 static void DumpZipDirectory(wxFileSystem
& fs
,
2601 const wxString
& dir
,
2602 const wxString
& indent
)
2604 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
2605 TESTFILE_ZIP
, dir
.c_str());
2606 wxString wildcard
= prefix
+ _T("/*");
2608 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
2609 while ( !dirname
.empty() )
2611 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
2613 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2618 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
2620 DumpZipDirectory(fs
, dirname
,
2621 indent
+ wxString(_T(' '), 4));
2623 dirname
= fs
.FindNext();
2626 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
2627 while ( !filename
.empty() )
2629 if ( !filename
.StartsWith(prefix
, &filename
) )
2631 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2636 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
2638 filename
= fs
.FindNext();
2642 static void TestZipFileSystem()
2644 puts("*** Testing ZIP file system ***\n");
2646 wxFileSystem::AddHandler(new wxZipFSHandler
);
2648 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
2650 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
2655 // ----------------------------------------------------------------------------
2657 // ----------------------------------------------------------------------------
2661 #include <wx/zstream.h>
2662 #include <wx/wfstream.h>
2664 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2665 static const char *TEST_DATA
= "hello and hello again";
2667 static void TestZlibStreamWrite()
2669 puts("*** Testing Zlib stream reading ***\n");
2671 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2672 wxZlibOutputStream
ostr(fileOutStream
, 0);
2673 printf("Compressing the test string... ");
2674 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2677 puts("(ERROR: failed)");
2684 puts("\n----- done ------");
2687 static void TestZlibStreamRead()
2689 puts("*** Testing Zlib stream reading ***\n");
2691 wxFileInputStream
fileInStream(FILENAME_GZ
);
2692 wxZlibInputStream
istr(fileInStream
);
2693 printf("Archive size: %u\n", istr
.GetSize());
2695 puts("Dumping the file:");
2696 while ( !istr
.Eof() )
2698 putchar(istr
.GetC());
2702 puts("\n----- done ------");
2707 // ----------------------------------------------------------------------------
2709 // ----------------------------------------------------------------------------
2711 #ifdef TEST_DATETIME
2713 #include <wx/date.h>
2715 #include <wx/datetime.h>
2720 wxDateTime::wxDateTime_t day
;
2721 wxDateTime::Month month
;
2723 wxDateTime::wxDateTime_t hour
, min
, sec
;
2725 wxDateTime::WeekDay wday
;
2726 time_t gmticks
, ticks
;
2728 void Init(const wxDateTime::Tm
& tm
)
2737 gmticks
= ticks
= -1;
2740 wxDateTime
DT() const
2741 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2743 bool SameDay(const wxDateTime::Tm
& tm
) const
2745 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2748 wxString
Format() const
2751 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2753 wxDateTime::GetMonthName(month
).c_str(),
2755 abs(wxDateTime::ConvertYearToBC(year
)),
2756 year
> 0 ? "AD" : "BC");
2760 wxString
FormatDate() const
2763 s
.Printf("%02d-%s-%4d%s",
2765 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2766 abs(wxDateTime::ConvertYearToBC(year
)),
2767 year
> 0 ? "AD" : "BC");
2772 static const Date testDates
[] =
2774 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2775 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2776 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2777 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2778 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2779 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2780 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2781 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2782 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2783 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2784 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2785 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2786 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2787 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2788 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2791 // this test miscellaneous static wxDateTime functions
2792 static void TestTimeStatic()
2794 puts("\n*** wxDateTime static methods test ***");
2796 // some info about the current date
2797 int year
= wxDateTime::GetCurrentYear();
2798 printf("Current year %d is %sa leap one and has %d days.\n",
2800 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2801 wxDateTime::GetNumberOfDays(year
));
2803 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2804 printf("Current month is '%s' ('%s') and it has %d days\n",
2805 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2806 wxDateTime::GetMonthName(month
).c_str(),
2807 wxDateTime::GetNumberOfDays(month
));
2810 static const size_t nYears
= 5;
2811 static const size_t years
[2][nYears
] =
2813 // first line: the years to test
2814 { 1990, 1976, 2000, 2030, 1984, },
2816 // second line: TRUE if leap, FALSE otherwise
2817 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2820 for ( size_t n
= 0; n
< nYears
; n
++ )
2822 int year
= years
[0][n
];
2823 bool should
= years
[1][n
] != 0,
2824 is
= wxDateTime::IsLeapYear(year
);
2826 printf("Year %d is %sa leap year (%s)\n",
2829 should
== is
? "ok" : "ERROR");
2831 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2835 // test constructing wxDateTime objects
2836 static void TestTimeSet()
2838 puts("\n*** wxDateTime construction test ***");
2840 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2842 const Date
& d1
= testDates
[n
];
2843 wxDateTime dt
= d1
.DT();
2846 d2
.Init(dt
.GetTm());
2848 wxString s1
= d1
.Format(),
2851 printf("Date: %s == %s (%s)\n",
2852 s1
.c_str(), s2
.c_str(),
2853 s1
== s2
? "ok" : "ERROR");
2857 // test time zones stuff
2858 static void TestTimeZones()
2860 puts("\n*** wxDateTime timezone test ***");
2862 wxDateTime now
= wxDateTime::Now();
2864 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2865 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2866 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2867 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2868 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2869 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2871 wxDateTime::Tm tm
= now
.GetTm();
2872 if ( wxDateTime(tm
) != now
)
2874 printf("ERROR: got %s instead of %s\n",
2875 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2879 // test some minimal support for the dates outside the standard range
2880 static void TestTimeRange()
2882 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2884 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
2886 printf("Unix epoch:\t%s\n",
2887 wxDateTime(2440587.5).Format(fmt
).c_str());
2888 printf("Feb 29, 0: \t%s\n",
2889 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
2890 printf("JDN 0: \t%s\n",
2891 wxDateTime(0.0).Format(fmt
).c_str());
2892 printf("Jan 1, 1AD:\t%s\n",
2893 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
2894 printf("May 29, 2099:\t%s\n",
2895 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
2898 static void TestTimeTicks()
2900 puts("\n*** wxDateTime ticks test ***");
2902 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2904 const Date
& d
= testDates
[n
];
2905 if ( d
.ticks
== -1 )
2908 wxDateTime dt
= d
.DT();
2909 long ticks
= (dt
.GetValue() / 1000).ToLong();
2910 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2911 if ( ticks
== d
.ticks
)
2917 printf(" (ERROR: should be %ld, delta = %ld)\n",
2918 d
.ticks
, ticks
- d
.ticks
);
2921 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
2922 ticks
= (dt
.GetValue() / 1000).ToLong();
2923 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2924 if ( ticks
== d
.gmticks
)
2930 printf(" (ERROR: should be %ld, delta = %ld)\n",
2931 d
.gmticks
, ticks
- d
.gmticks
);
2938 // test conversions to JDN &c
2939 static void TestTimeJDN()
2941 puts("\n*** wxDateTime to JDN test ***");
2943 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2945 const Date
& d
= testDates
[n
];
2946 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2947 double jdn
= dt
.GetJulianDayNumber();
2949 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
2956 printf(" (ERROR: should be %f, delta = %f)\n",
2957 d
.jdn
, jdn
- d
.jdn
);
2962 // test week days computation
2963 static void TestTimeWDays()
2965 puts("\n*** wxDateTime weekday test ***");
2967 // test GetWeekDay()
2969 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2971 const Date
& d
= testDates
[n
];
2972 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2974 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
2977 wxDateTime::GetWeekDayName(wday
).c_str());
2978 if ( wday
== d
.wday
)
2984 printf(" (ERROR: should be %s)\n",
2985 wxDateTime::GetWeekDayName(d
.wday
).c_str());
2991 // test SetToWeekDay()
2992 struct WeekDateTestData
2994 Date date
; // the real date (precomputed)
2995 int nWeek
; // its week index in the month
2996 wxDateTime::WeekDay wday
; // the weekday
2997 wxDateTime::Month month
; // the month
2998 int year
; // and the year
3000 wxString
Format() const
3003 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3005 case 1: which
= "first"; break;
3006 case 2: which
= "second"; break;
3007 case 3: which
= "third"; break;
3008 case 4: which
= "fourth"; break;
3009 case 5: which
= "fifth"; break;
3011 case -1: which
= "last"; break;
3016 which
+= " from end";
3019 s
.Printf("The %s %s of %s in %d",
3021 wxDateTime::GetWeekDayName(wday
).c_str(),
3022 wxDateTime::GetMonthName(month
).c_str(),
3029 // the array data was generated by the following python program
3031 from DateTime import *
3032 from whrandom import *
3033 from string import *
3035 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3036 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3038 week = DateTimeDelta(7)
3041 year = randint(1900, 2100)
3042 month = randint(1, 12)
3043 day = randint(1, 28)
3044 dt = DateTime(year, month, day)
3045 wday = dt.day_of_week
3047 countFromEnd = choice([-1, 1])
3050 while dt.month is month:
3051 dt = dt - countFromEnd * week
3052 weekNum = weekNum + countFromEnd
3054 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3056 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3057 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3060 static const WeekDateTestData weekDatesTestData
[] =
3062 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3063 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3064 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3065 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3066 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3067 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3068 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3069 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3070 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3071 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3072 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3073 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3074 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3075 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3076 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3077 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3078 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3079 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3080 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3081 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3084 static const char *fmt
= "%d-%b-%Y";
3087 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3089 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3091 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3093 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3095 const Date
& d
= wd
.date
;
3096 if ( d
.SameDay(dt
.GetTm()) )
3102 dt
.Set(d
.day
, d
.month
, d
.year
);
3104 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3109 // test the computation of (ISO) week numbers
3110 static void TestTimeWNumber()
3112 puts("\n*** wxDateTime week number test ***");
3114 struct WeekNumberTestData
3116 Date date
; // the date
3117 wxDateTime::wxDateTime_t week
; // the week number in the year
3118 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3119 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3120 wxDateTime::wxDateTime_t dnum
; // day number in the year
3123 // data generated with the following python script:
3125 from DateTime import *
3126 from whrandom import *
3127 from string import *
3129 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3130 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3132 def GetMonthWeek(dt):
3133 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3134 if weekNumMonth < 0:
3135 weekNumMonth = weekNumMonth + 53
3138 def GetLastSundayBefore(dt):
3139 if dt.iso_week[2] == 7:
3142 return dt - DateTimeDelta(dt.iso_week[2])
3145 year = randint(1900, 2100)
3146 month = randint(1, 12)
3147 day = randint(1, 28)
3148 dt = DateTime(year, month, day)
3149 dayNum = dt.day_of_year
3150 weekNum = dt.iso_week[1]
3151 weekNumMonth = GetMonthWeek(dt)
3154 dtSunday = GetLastSundayBefore(dt)
3156 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3157 weekNumMonth2 = weekNumMonth2 + 1
3158 dtSunday = dtSunday - DateTimeDelta(7)
3160 data = { 'day': rjust(`day`, 2), \
3161 'month': monthNames[month - 1], \
3163 'weekNum': rjust(`weekNum`, 2), \
3164 'weekNumMonth': weekNumMonth, \
3165 'weekNumMonth2': weekNumMonth2, \
3166 'dayNum': rjust(`dayNum`, 3) }
3168 print " { { %(day)s, "\
3169 "wxDateTime::%(month)s, "\
3172 "%(weekNumMonth)s, "\
3173 "%(weekNumMonth2)s, "\
3174 "%(dayNum)s }," % data
3177 static const WeekNumberTestData weekNumberTestDates
[] =
3179 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3180 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3181 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3182 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3183 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3184 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3185 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3186 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3187 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3188 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3189 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3190 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3191 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3192 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3193 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3194 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3195 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3196 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3197 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3198 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3201 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3203 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3204 const Date
& d
= wn
.date
;
3206 wxDateTime dt
= d
.DT();
3208 wxDateTime::wxDateTime_t
3209 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3210 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3211 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3212 dnum
= dt
.GetDayOfYear();
3214 printf("%s: the day number is %d",
3215 d
.FormatDate().c_str(), dnum
);
3216 if ( dnum
== wn
.dnum
)
3222 printf(" (ERROR: should be %d)", wn
.dnum
);
3225 printf(", week in month is %d", wmon
);
3226 if ( wmon
== wn
.wmon
)
3232 printf(" (ERROR: should be %d)", wn
.wmon
);
3235 printf(" or %d", wmon2
);
3236 if ( wmon2
== wn
.wmon2
)
3242 printf(" (ERROR: should be %d)", wn
.wmon2
);
3245 printf(", week in year is %d", week
);
3246 if ( week
== wn
.week
)
3252 printf(" (ERROR: should be %d)\n", wn
.week
);
3257 // test DST calculations
3258 static void TestTimeDST()
3260 puts("\n*** wxDateTime DST test ***");
3262 printf("DST is%s in effect now.\n\n",
3263 wxDateTime::Now().IsDST() ? "" : " not");
3265 // taken from http://www.energy.ca.gov/daylightsaving.html
3266 static const Date datesDST
[2][2004 - 1900 + 1] =
3269 { 1, wxDateTime::Apr
, 1990 },
3270 { 7, wxDateTime::Apr
, 1991 },
3271 { 5, wxDateTime::Apr
, 1992 },
3272 { 4, wxDateTime::Apr
, 1993 },
3273 { 3, wxDateTime::Apr
, 1994 },
3274 { 2, wxDateTime::Apr
, 1995 },
3275 { 7, wxDateTime::Apr
, 1996 },
3276 { 6, wxDateTime::Apr
, 1997 },
3277 { 5, wxDateTime::Apr
, 1998 },
3278 { 4, wxDateTime::Apr
, 1999 },
3279 { 2, wxDateTime::Apr
, 2000 },
3280 { 1, wxDateTime::Apr
, 2001 },
3281 { 7, wxDateTime::Apr
, 2002 },
3282 { 6, wxDateTime::Apr
, 2003 },
3283 { 4, wxDateTime::Apr
, 2004 },
3286 { 28, wxDateTime::Oct
, 1990 },
3287 { 27, wxDateTime::Oct
, 1991 },
3288 { 25, wxDateTime::Oct
, 1992 },
3289 { 31, wxDateTime::Oct
, 1993 },
3290 { 30, wxDateTime::Oct
, 1994 },
3291 { 29, wxDateTime::Oct
, 1995 },
3292 { 27, wxDateTime::Oct
, 1996 },
3293 { 26, wxDateTime::Oct
, 1997 },
3294 { 25, wxDateTime::Oct
, 1998 },
3295 { 31, wxDateTime::Oct
, 1999 },
3296 { 29, wxDateTime::Oct
, 2000 },
3297 { 28, wxDateTime::Oct
, 2001 },
3298 { 27, wxDateTime::Oct
, 2002 },
3299 { 26, wxDateTime::Oct
, 2003 },
3300 { 31, wxDateTime::Oct
, 2004 },
3305 for ( year
= 1990; year
< 2005; year
++ )
3307 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3308 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3310 printf("DST period in the US for year %d: from %s to %s",
3311 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3313 size_t n
= year
- 1990;
3314 const Date
& dBegin
= datesDST
[0][n
];
3315 const Date
& dEnd
= datesDST
[1][n
];
3317 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3323 printf(" (ERROR: should be %s %d to %s %d)\n",
3324 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3325 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3331 for ( year
= 1990; year
< 2005; year
++ )
3333 printf("DST period in Europe for year %d: from %s to %s\n",
3335 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3336 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3340 // test wxDateTime -> text conversion
3341 static void TestTimeFormat()
3343 puts("\n*** wxDateTime formatting test ***");
3345 // some information may be lost during conversion, so store what kind
3346 // of info should we recover after a round trip
3349 CompareNone
, // don't try comparing
3350 CompareBoth
, // dates and times should be identical
3351 CompareDate
, // dates only
3352 CompareTime
// time only
3357 CompareKind compareKind
;
3359 } formatTestFormats
[] =
3361 { CompareBoth
, "---> %c" },
3362 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3363 { CompareBoth
, "Date is %x, time is %X" },
3364 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3365 { CompareNone
, "The day of year: %j, the week of year: %W" },
3366 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3369 static const Date formatTestDates
[] =
3371 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3372 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3374 // this test can't work for other centuries because it uses two digit
3375 // years in formats, so don't even try it
3376 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3377 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3378 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3382 // an extra test (as it doesn't depend on date, don't do it in the loop)
3383 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3385 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3389 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3390 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3392 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3393 printf("%s", s
.c_str());
3395 // what can we recover?
3396 int kind
= formatTestFormats
[n
].compareKind
;
3400 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3403 // converion failed - should it have?
3404 if ( kind
== CompareNone
)
3407 puts(" (ERROR: conversion back failed)");
3411 // should have parsed the entire string
3412 puts(" (ERROR: conversion back stopped too soon)");
3416 bool equal
= FALSE
; // suppress compilaer warning
3424 equal
= dt
.IsSameDate(dt2
);
3428 equal
= dt
.IsSameTime(dt2
);
3434 printf(" (ERROR: got back '%s' instead of '%s')\n",
3435 dt2
.Format().c_str(), dt
.Format().c_str());
3446 // test text -> wxDateTime conversion
3447 static void TestTimeParse()
3449 puts("\n*** wxDateTime parse test ***");
3451 struct ParseTestData
3458 static const ParseTestData parseTestDates
[] =
3460 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3461 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3464 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3466 const char *format
= parseTestDates
[n
].format
;
3468 printf("%s => ", format
);
3471 if ( dt
.ParseRfc822Date(format
) )
3473 printf("%s ", dt
.Format().c_str());
3475 if ( parseTestDates
[n
].good
)
3477 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3484 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3489 puts("(ERROR: bad format)");
3494 printf("bad format (%s)\n",
3495 parseTestDates
[n
].good
? "ERROR" : "ok");
3500 static void TestDateTimeInteractive()
3502 puts("\n*** interactive wxDateTime tests ***");
3508 printf("Enter a date: ");
3509 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3512 // kill the last '\n'
3513 buf
[strlen(buf
) - 1] = 0;
3516 const char *p
= dt
.ParseDate(buf
);
3519 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3525 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3528 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3529 dt
.Format("%b %d, %Y").c_str(),
3531 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3532 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3533 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3536 puts("\n*** done ***");
3539 static void TestTimeMS()
3541 puts("*** testing millisecond-resolution support in wxDateTime ***");
3543 wxDateTime dt1
= wxDateTime::Now(),
3544 dt2
= wxDateTime::UNow();
3546 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3547 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3548 printf("Dummy loop: ");
3549 for ( int i
= 0; i
< 6000; i
++ )
3551 //for ( int j = 0; j < 10; j++ )
3554 s
.Printf("%g", sqrt(i
));
3563 dt2
= wxDateTime::UNow();
3564 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3566 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3568 puts("\n*** done ***");
3571 static void TestTimeArithmetics()
3573 puts("\n*** testing arithmetic operations on wxDateTime ***");
3575 static const struct ArithmData
3577 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3578 : span(sp
), name(nam
) { }
3582 } testArithmData
[] =
3584 ArithmData(wxDateSpan::Day(), "day"),
3585 ArithmData(wxDateSpan::Week(), "week"),
3586 ArithmData(wxDateSpan::Month(), "month"),
3587 ArithmData(wxDateSpan::Year(), "year"),
3588 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3591 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3593 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3595 wxDateSpan span
= testArithmData
[n
].span
;
3599 const char *name
= testArithmData
[n
].name
;
3600 printf("%s + %s = %s, %s - %s = %s\n",
3601 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3602 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3604 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3605 if ( dt1
- span
== dt
)
3611 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3614 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3615 if ( dt2
+ span
== dt
)
3621 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3624 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3625 if ( dt2
+ 2*span
== dt1
)
3631 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3638 static void TestTimeHolidays()
3640 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3642 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3643 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3644 dtEnd
= dtStart
.GetLastMonthDay();
3646 wxDateTimeArray hol
;
3647 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3649 const wxChar
*format
= "%d-%b-%Y (%a)";
3651 printf("All holidays between %s and %s:\n",
3652 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3654 size_t count
= hol
.GetCount();
3655 for ( size_t n
= 0; n
< count
; n
++ )
3657 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3663 static void TestTimeZoneBug()
3665 puts("\n*** testing for DST/timezone bug ***\n");
3667 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3668 for ( int i
= 0; i
< 31; i
++ )
3670 printf("Date %s: week day %s.\n",
3671 date
.Format(_T("%d-%m-%Y")).c_str(),
3672 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3674 date
+= wxDateSpan::Day();
3680 static void TestTimeSpanFormat()
3682 puts("\n*** wxTimeSpan tests ***");
3684 static const char *formats
[] =
3686 _T("(default) %H:%M:%S"),
3687 _T("%E weeks and %D days"),
3688 _T("%l milliseconds"),
3689 _T("(with ms) %H:%M:%S:%l"),
3690 _T("100%% of minutes is %M"), // test "%%"
3691 _T("%D days and %H hours"),
3694 wxTimeSpan
ts1(1, 2, 3, 4),
3696 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3698 printf("ts1 = %s\tts2 = %s\n",
3699 ts1
.Format(formats
[n
]).c_str(),
3700 ts2
.Format(formats
[n
]).c_str());
3708 // test compatibility with the old wxDate/wxTime classes
3709 static void TestTimeCompatibility()
3711 puts("\n*** wxDateTime compatibility test ***");
3713 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3714 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3716 double jdnNow
= wxDateTime::Now().GetJDN();
3717 long jdnMidnight
= (long)(jdnNow
- 0.5);
3718 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3720 jdnMidnight
= wxDate().Set().GetJulianDate();
3721 printf("wxDateTime for today: %s\n",
3722 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3724 int flags
= wxEUROPEAN
;//wxFULL;
3727 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3728 for ( int n
= 0; n
< 7; n
++ )
3730 printf("Previous %s is %s\n",
3731 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3732 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3738 #endif // TEST_DATETIME
3740 // ----------------------------------------------------------------------------
3742 // ----------------------------------------------------------------------------
3746 #include <wx/thread.h>
3748 static size_t gs_counter
= (size_t)-1;
3749 static wxCriticalSection gs_critsect
;
3750 static wxCondition gs_cond
;
3752 class MyJoinableThread
: public wxThread
3755 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3756 { m_n
= n
; Create(); }
3758 // thread execution starts here
3759 virtual ExitCode
Entry();
3765 wxThread::ExitCode
MyJoinableThread::Entry()
3767 unsigned long res
= 1;
3768 for ( size_t n
= 1; n
< m_n
; n
++ )
3772 // it's a loooong calculation :-)
3776 return (ExitCode
)res
;
3779 class MyDetachedThread
: public wxThread
3782 MyDetachedThread(size_t n
, char ch
)
3786 m_cancelled
= FALSE
;
3791 // thread execution starts here
3792 virtual ExitCode
Entry();
3795 virtual void OnExit();
3798 size_t m_n
; // number of characters to write
3799 char m_ch
; // character to write
3801 bool m_cancelled
; // FALSE if we exit normally
3804 wxThread::ExitCode
MyDetachedThread::Entry()
3807 wxCriticalSectionLocker
lock(gs_critsect
);
3808 if ( gs_counter
== (size_t)-1 )
3814 for ( size_t n
= 0; n
< m_n
; n
++ )
3816 if ( TestDestroy() )
3826 wxThread::Sleep(100);
3832 void MyDetachedThread::OnExit()
3834 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3836 wxCriticalSectionLocker
lock(gs_critsect
);
3837 if ( !--gs_counter
&& !m_cancelled
)
3841 void TestDetachedThreads()
3843 puts("\n*** Testing detached threads ***");
3845 static const size_t nThreads
= 3;
3846 MyDetachedThread
*threads
[nThreads
];
3848 for ( n
= 0; n
< nThreads
; n
++ )
3850 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3853 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3854 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3856 for ( n
= 0; n
< nThreads
; n
++ )
3861 // wait until all threads terminate
3867 void TestJoinableThreads()
3869 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3871 // calc 10! in the background
3872 MyJoinableThread
thread(10);
3875 printf("\nThread terminated with exit code %lu.\n",
3876 (unsigned long)thread
.Wait());
3879 void TestThreadSuspend()
3881 puts("\n*** Testing thread suspend/resume functions ***");
3883 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3887 // this is for this demo only, in a real life program we'd use another
3888 // condition variable which would be signaled from wxThread::Entry() to
3889 // tell us that the thread really started running - but here just wait a
3890 // bit and hope that it will be enough (the problem is, of course, that
3891 // the thread might still not run when we call Pause() which will result
3893 wxThread::Sleep(300);
3895 for ( size_t n
= 0; n
< 3; n
++ )
3899 puts("\nThread suspended");
3902 // don't sleep but resume immediately the first time
3903 wxThread::Sleep(300);
3905 puts("Going to resume the thread");
3910 puts("Waiting until it terminates now");
3912 // wait until the thread terminates
3918 void TestThreadDelete()
3920 // As above, using Sleep() is only for testing here - we must use some
3921 // synchronisation object instead to ensure that the thread is still
3922 // running when we delete it - deleting a detached thread which already
3923 // terminated will lead to a crash!
3925 puts("\n*** Testing thread delete function ***");
3927 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3931 puts("\nDeleted a thread which didn't start to run yet.");
3933 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3937 wxThread::Sleep(300);
3941 puts("\nDeleted a running thread.");
3943 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3947 wxThread::Sleep(300);
3953 puts("\nDeleted a sleeping thread.");
3955 MyJoinableThread
thread3(20);
3960 puts("\nDeleted a joinable thread.");
3962 MyJoinableThread
thread4(2);
3965 wxThread::Sleep(300);
3969 puts("\nDeleted a joinable thread which already terminated.");
3974 #endif // TEST_THREADS
3976 // ----------------------------------------------------------------------------
3978 // ----------------------------------------------------------------------------
3982 static void PrintArray(const char* name
, const wxArrayString
& array
)
3984 printf("Dump of the array '%s'\n", name
);
3986 size_t nCount
= array
.GetCount();
3987 for ( size_t n
= 0; n
< nCount
; n
++ )
3989 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
3993 static void PrintArray(const char* name
, const wxArrayInt
& array
)
3995 printf("Dump of the array '%s'\n", name
);
3997 size_t nCount
= array
.GetCount();
3998 for ( size_t n
= 0; n
< nCount
; n
++ )
4000 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4004 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4005 const wxString
& second
)
4007 return first
.length() - second
.length();
4010 int wxCMPFUNC_CONV
IntCompare(int *first
,
4013 return *first
- *second
;
4016 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4019 return *second
- *first
;
4022 static void TestArrayOfInts()
4024 puts("*** Testing wxArrayInt ***\n");
4035 puts("After sort:");
4039 puts("After reverse sort:");
4040 a
.Sort(IntRevCompare
);
4044 #include "wx/dynarray.h"
4046 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4047 #include "wx/arrimpl.cpp"
4048 WX_DEFINE_OBJARRAY(ArrayBars
);
4050 static void TestArrayOfObjects()
4052 puts("*** Testing wxObjArray ***\n");
4056 Bar
bar("second bar");
4058 printf("Initially: %u objects in the array, %u objects total.\n",
4059 bars
.GetCount(), Bar::GetNumber());
4061 bars
.Add(new Bar("first bar"));
4064 printf("Now: %u objects in the array, %u objects total.\n",
4065 bars
.GetCount(), Bar::GetNumber());
4069 printf("After Empty(): %u objects in the array, %u objects total.\n",
4070 bars
.GetCount(), Bar::GetNumber());
4073 printf("Finally: no more objects in the array, %u objects total.\n",
4077 #endif // TEST_ARRAYS
4079 // ----------------------------------------------------------------------------
4081 // ----------------------------------------------------------------------------
4085 #include "wx/timer.h"
4086 #include "wx/tokenzr.h"
4088 static void TestStringConstruction()
4090 puts("*** Testing wxString constructores ***");
4092 #define TEST_CTOR(args, res) \
4095 printf("wxString%s = %s ", #args, s.c_str()); \
4102 printf("(ERROR: should be %s)\n", res); \
4106 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4107 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4108 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4109 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4111 static const wxChar
*s
= _T("?really!");
4112 const wxChar
*start
= wxStrchr(s
, _T('r'));
4113 const wxChar
*end
= wxStrchr(s
, _T('!'));
4114 TEST_CTOR((start
, end
), _T("really"));
4119 static void TestString()
4129 for (int i
= 0; i
< 1000000; ++i
)
4133 c
= "! How'ya doin'?";
4136 c
= "Hello world! What's up?";
4141 printf ("TestString elapsed time: %ld\n", sw
.Time());
4144 static void TestPChar()
4152 for (int i
= 0; i
< 1000000; ++i
)
4154 strcpy (a
, "Hello");
4155 strcpy (b
, " world");
4156 strcpy (c
, "! How'ya doin'?");
4159 strcpy (c
, "Hello world! What's up?");
4160 if (strcmp (c
, a
) == 0)
4164 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4167 static void TestStringSub()
4169 wxString
s("Hello, world!");
4171 puts("*** Testing wxString substring extraction ***");
4173 printf("String = '%s'\n", s
.c_str());
4174 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4175 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4176 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4177 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4178 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4179 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4181 static const wxChar
*prefixes
[] =
4185 _T("Hello, world!"),
4186 _T("Hello, world!!!"),
4192 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4194 wxString prefix
= prefixes
[n
], rest
;
4195 bool rc
= s
.StartsWith(prefix
, &rest
);
4196 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4199 printf(" (the rest is '%s')\n", rest
.c_str());
4210 static void TestStringFormat()
4212 puts("*** Testing wxString formatting ***");
4215 s
.Printf("%03d", 18);
4217 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4218 printf("Number 18: %s\n", s
.c_str());
4223 // returns "not found" for npos, value for all others
4224 static wxString
PosToString(size_t res
)
4226 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4227 : wxString::Format(_T("%u"), res
);
4231 static void TestStringFind()
4233 puts("*** Testing wxString find() functions ***");
4235 static const wxChar
*strToFind
= _T("ell");
4236 static const struct StringFindTest
4240 result
; // of searching "ell" in str
4243 { _T("Well, hello world"), 0, 1 },
4244 { _T("Well, hello world"), 6, 7 },
4245 { _T("Well, hello world"), 9, wxString::npos
},
4248 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4250 const StringFindTest
& ft
= findTestData
[n
];
4251 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4253 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4254 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4256 size_t resTrue
= ft
.result
;
4257 if ( res
== resTrue
)
4263 printf(_T("(ERROR: should be %s)\n"),
4264 PosToString(resTrue
).c_str());
4271 static void TestStringTokenizer()
4273 puts("*** Testing wxStringTokenizer ***");
4275 static const wxChar
*modeNames
[] =
4279 _T("return all empty"),
4284 static const struct StringTokenizerTest
4286 const wxChar
*str
; // string to tokenize
4287 const wxChar
*delims
; // delimiters to use
4288 size_t count
; // count of token
4289 wxStringTokenizerMode mode
; // how should we tokenize it
4290 } tokenizerTestData
[] =
4292 { _T(""), _T(" "), 0 },
4293 { _T("Hello, world"), _T(" "), 2 },
4294 { _T("Hello, world "), _T(" "), 2 },
4295 { _T("Hello, world"), _T(","), 2 },
4296 { _T("Hello, world!"), _T(",!"), 2 },
4297 { _T("Hello,, world!"), _T(",!"), 3 },
4298 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4299 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4300 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4301 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4302 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4303 { _T("01/02/99"), _T("/-"), 3 },
4304 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4307 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4309 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4310 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4312 size_t count
= tkz
.CountTokens();
4313 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4314 MakePrintable(tt
.str
).c_str(),
4316 MakePrintable(tt
.delims
).c_str(),
4317 modeNames
[tkz
.GetMode()]);
4318 if ( count
== tt
.count
)
4324 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4329 // if we emulate strtok(), check that we do it correctly
4330 wxChar
*buf
, *s
= NULL
, *last
;
4332 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4334 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4335 wxStrcpy(buf
, tt
.str
);
4337 s
= wxStrtok(buf
, tt
.delims
, &last
);
4344 // now show the tokens themselves
4346 while ( tkz
.HasMoreTokens() )
4348 wxString token
= tkz
.GetNextToken();
4350 printf(_T("\ttoken %u: '%s'"),
4352 MakePrintable(token
).c_str());
4362 printf(" (ERROR: should be %s)\n", s
);
4365 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4369 // nothing to compare with
4374 if ( count2
!= count
)
4376 puts(_T("\tERROR: token count mismatch"));
4385 static void TestStringReplace()
4387 puts("*** Testing wxString::replace ***");
4389 static const struct StringReplaceTestData
4391 const wxChar
*original
; // original test string
4392 size_t start
, len
; // the part to replace
4393 const wxChar
*replacement
; // the replacement string
4394 const wxChar
*result
; // and the expected result
4395 } stringReplaceTestData
[] =
4397 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4398 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4399 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4400 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4401 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4404 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4406 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4408 wxString original
= data
.original
;
4409 original
.replace(data
.start
, data
.len
, data
.replacement
);
4411 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4412 data
.original
, data
.start
, data
.len
, data
.replacement
,
4415 if ( original
== data
.result
)
4421 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4428 #endif // TEST_STRINGS
4430 // ----------------------------------------------------------------------------
4432 // ----------------------------------------------------------------------------
4434 int main(int argc
, char **argv
)
4436 if ( !wxInitialize() )
4438 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4442 puts("Sleeping for 3 seconds... z-z-z-z-z...");
4444 #endif // TEST_USLEEP
4447 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4449 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4450 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4452 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4453 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4454 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
4455 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
4457 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4458 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4463 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4465 parser
.AddOption("project_name", "", "full path to project file",
4466 wxCMD_LINE_VAL_STRING
,
4467 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4469 switch ( parser
.Parse() )
4472 wxLogMessage("Help was given, terminating.");
4476 ShowCmdLine(parser
);
4480 wxLogMessage("Syntax error detected, aborting.");
4483 #endif // TEST_CMDLINE
4494 TestStringConstruction();
4497 TestStringTokenizer();
4498 TestStringReplace();
4500 #endif // TEST_STRINGS
4513 puts("*** Initially:");
4515 PrintArray("a1", a1
);
4517 wxArrayString
a2(a1
);
4518 PrintArray("a2", a2
);
4520 wxSortedArrayString
a3(a1
);
4521 PrintArray("a3", a3
);
4523 puts("*** After deleting a string from a1");
4526 PrintArray("a1", a1
);
4527 PrintArray("a2", a2
);
4528 PrintArray("a3", a3
);
4530 puts("*** After reassigning a1 to a2 and a3");
4532 PrintArray("a2", a2
);
4533 PrintArray("a3", a3
);
4535 puts("*** After sorting a1");
4537 PrintArray("a1", a1
);
4539 puts("*** After sorting a1 in reverse order");
4541 PrintArray("a1", a1
);
4543 puts("*** After sorting a1 by the string length");
4544 a1
.Sort(StringLenCompare
);
4545 PrintArray("a1", a1
);
4547 TestArrayOfObjects();
4550 #endif // TEST_ARRAYS
4556 #ifdef TEST_DLLLOADER
4558 #endif // TEST_DLLLOADER
4562 #endif // TEST_ENVIRON
4566 #endif // TEST_EXECUTE
4568 #ifdef TEST_FILECONF
4570 #endif // TEST_FILECONF
4578 #endif // TEST_LOCALE
4582 for ( size_t n
= 0; n
< 8000; n
++ )
4584 s
<< (char)('A' + (n
% 26));
4588 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4590 // this one shouldn't be truncated
4593 // but this one will because log functions use fixed size buffer
4594 // (note that it doesn't need '\n' at the end neither - will be added
4596 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4608 #ifdef TEST_FILENAME
4609 TestFileNameSplit();
4612 TestFileNameConstruction();
4614 TestFileNameComparison();
4615 TestFileNameOperations();
4617 #endif // TEST_FILENAME
4620 int nCPUs
= wxThread::GetCPUCount();
4621 printf("This system has %d CPUs\n", nCPUs
);
4623 wxThread::SetConcurrency(nCPUs
);
4625 if ( argc
> 1 && argv
[1][0] == 't' )
4626 wxLog::AddTraceMask("thread");
4629 TestDetachedThreads();
4631 TestJoinableThreads();
4633 TestThreadSuspend();
4637 #endif // TEST_THREADS
4639 #ifdef TEST_LONGLONG
4640 // seed pseudo random generator
4641 srand((unsigned)time(NULL
));
4649 TestMultiplication();
4652 TestLongLongConversion();
4653 TestBitOperations();
4655 TestLongLongComparison();
4656 #endif // TEST_LONGLONG
4663 wxLog::AddTraceMask(_T("mime"));
4671 TestMimeAssociate();
4674 #ifdef TEST_INFO_FUNCTIONS
4677 #endif // TEST_INFO_FUNCTIONS
4679 #ifdef TEST_PATHLIST
4681 #endif // TEST_PATHLIST
4683 #ifdef TEST_REGISTRY
4686 TestRegistryAssociation();
4687 #endif // TEST_REGISTRY
4695 #endif // TEST_SOCKETS
4698 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4699 if ( TestFtpConnect() )
4710 TestFtpInteractive();
4712 //else: connecting to the FTP server failed
4722 #endif // TEST_STREAMS
4726 #endif // TEST_TIMER
4728 #ifdef TEST_DATETIME
4741 TestTimeArithmetics();
4748 TestTimeSpanFormat();
4750 TestDateTimeInteractive();
4751 #endif // TEST_DATETIME
4757 #endif // TEST_VCARD
4761 #endif // TEST_WCHAR
4765 TestZipStreamRead();
4766 TestZipFileSystem();
4771 TestZlibStreamWrite();
4772 TestZlibStreamRead();