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
53 //#define TEST_LONGLONG
55 //#define TEST_PATHLIST
56 //#define TEST_REGISTRY
57 //#define TEST_SOCKETS
58 //#define TEST_STREAMS
59 //#define TEST_STRINGS
60 //#define TEST_THREADS
62 //#define TEST_VCARD -- don't enable this (VZ)
67 // ----------------------------------------------------------------------------
68 // test class for container objects
69 // ----------------------------------------------------------------------------
71 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
73 class Bar
// Foo is already taken in the hash test
76 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
79 static size_t GetNumber() { return ms_bars
; }
81 const char *GetName() const { return m_name
; }
86 static size_t ms_bars
;
89 size_t Bar::ms_bars
= 0;
91 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
93 // ============================================================================
95 // ============================================================================
97 // ----------------------------------------------------------------------------
99 // ----------------------------------------------------------------------------
101 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
103 // replace TABs with \t and CRs with \n
104 static wxString
MakePrintable(const wxChar
*s
)
107 (void)str
.Replace(_T("\t"), _T("\\t"));
108 (void)str
.Replace(_T("\n"), _T("\\n"));
109 (void)str
.Replace(_T("\r"), _T("\\r"));
114 #endif // MakePrintable() is used
116 // ----------------------------------------------------------------------------
118 // ----------------------------------------------------------------------------
122 #include <wx/cmdline.h>
123 #include <wx/datetime.h>
125 static void ShowCmdLine(const wxCmdLineParser
& parser
)
127 wxString s
= "Input files: ";
129 size_t count
= parser
.GetParamCount();
130 for ( size_t param
= 0; param
< count
; param
++ )
132 s
<< parser
.GetParam(param
) << ' ';
136 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
137 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
142 if ( parser
.Found("o", &strVal
) )
143 s
<< "Output file:\t" << strVal
<< '\n';
144 if ( parser
.Found("i", &strVal
) )
145 s
<< "Input dir:\t" << strVal
<< '\n';
146 if ( parser
.Found("s", &lVal
) )
147 s
<< "Size:\t" << lVal
<< '\n';
148 if ( parser
.Found("d", &dt
) )
149 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
150 if ( parser
.Found("project_name", &strVal
) )
151 s
<< "Project:\t" << strVal
<< '\n';
156 #endif // TEST_CMDLINE
158 // ----------------------------------------------------------------------------
160 // ----------------------------------------------------------------------------
166 static void TestDirEnumHelper(wxDir
& dir
,
167 int flags
= wxDIR_DEFAULT
,
168 const wxString
& filespec
= wxEmptyString
)
172 if ( !dir
.IsOpened() )
175 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
178 printf("\t%s\n", filename
.c_str());
180 cont
= dir
.GetNext(&filename
);
186 static void TestDirEnum()
188 wxDir
dir(wxGetCwd());
190 puts("Enumerating everything in current directory:");
191 TestDirEnumHelper(dir
);
193 puts("Enumerating really everything in current directory:");
194 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
196 puts("Enumerating object files in current directory:");
197 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
199 puts("Enumerating directories in current directory:");
200 TestDirEnumHelper(dir
, wxDIR_DIRS
);
202 puts("Enumerating files in current directory:");
203 TestDirEnumHelper(dir
, wxDIR_FILES
);
205 puts("Enumerating files including hidden in current directory:");
206 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
210 #elif defined(__WXMSW__)
213 #error "don't know where the root directory is"
216 puts("Enumerating everything in root directory:");
217 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
219 puts("Enumerating directories in root directory:");
220 TestDirEnumHelper(dir
, wxDIR_DIRS
);
222 puts("Enumerating files in root directory:");
223 TestDirEnumHelper(dir
, wxDIR_FILES
);
225 puts("Enumerating files including hidden in root directory:");
226 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
228 puts("Enumerating files in non existing directory:");
229 wxDir
dirNo("nosuchdir");
230 TestDirEnumHelper(dirNo
);
235 // ----------------------------------------------------------------------------
237 // ----------------------------------------------------------------------------
239 #ifdef TEST_DLLLOADER
241 #include <wx/dynlib.h>
243 static void TestDllLoad()
245 #if defined(__WXMSW__)
246 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
247 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
248 #elif defined(__UNIX__)
249 // weird: using just libc.so does *not* work!
250 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
251 static const wxChar
*FUNC_NAME
= _T("strlen");
253 #error "don't know how to test wxDllLoader on this platform"
256 puts("*** testing wxDllLoader ***\n");
258 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
261 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
265 typedef int (*strlenType
)(char *);
266 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
269 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
270 FUNC_NAME
, LIB_NAME
);
274 if ( pfnStrlen("foo") != 3 )
276 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
284 wxDllLoader::UnloadLibrary(dllHandle
);
288 #endif // TEST_DLLLOADER
290 // ----------------------------------------------------------------------------
292 // ----------------------------------------------------------------------------
296 #include <wx/utils.h>
298 static wxString
MyGetEnv(const wxString
& var
)
301 if ( !wxGetEnv(var
, &val
) )
304 val
= wxString(_T('\'')) + val
+ _T('\'');
309 static void TestEnvironment()
311 const wxChar
*var
= _T("wxTestVar");
313 puts("*** testing environment access functions ***");
315 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
316 wxSetEnv(var
, _T("value for wxTestVar"));
317 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
318 wxSetEnv(var
, _T("another value"));
319 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
321 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
322 printf("PATH = %s\n", MyGetEnv(_T("PATH")));
325 #endif // TEST_ENVIRON
327 // ----------------------------------------------------------------------------
329 // ----------------------------------------------------------------------------
333 #include <wx/utils.h>
335 static void TestExecute()
337 puts("*** testing wxExecute ***");
340 #define COMMAND "cat -n ../../Makefile" // "echo hi"
341 #define SHELL_COMMAND "echo hi from shell"
342 #define REDIRECT_COMMAND COMMAND // "date"
343 #elif defined(__WXMSW__)
344 #define COMMAND "command.com -c 'echo hi'"
345 #define SHELL_COMMAND "echo hi"
346 #define REDIRECT_COMMAND COMMAND
348 #error "no command to exec"
351 printf("Testing wxShell: ");
353 if ( wxShell(SHELL_COMMAND
) )
358 printf("Testing wxExecute: ");
360 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
365 #if 0 // no, it doesn't work (yet?)
366 printf("Testing async wxExecute: ");
368 if ( wxExecute(COMMAND
) != 0 )
369 puts("Ok (command launched).");
374 printf("Testing wxExecute with redirection:\n");
375 wxArrayString output
;
376 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
382 size_t count
= output
.GetCount();
383 for ( size_t n
= 0; n
< count
; n
++ )
385 printf("\t%s\n", output
[n
].c_str());
392 #endif // TEST_EXECUTE
394 // ----------------------------------------------------------------------------
396 // ----------------------------------------------------------------------------
401 #include <wx/ffile.h>
402 #include <wx/textfile.h>
404 static void TestFileRead()
406 puts("*** wxFile read test ***");
408 wxFile
file(_T("testdata.fc"));
409 if ( file
.IsOpened() )
411 printf("File length: %lu\n", file
.Length());
413 puts("File dump:\n----------");
415 static const off_t len
= 1024;
419 off_t nRead
= file
.Read(buf
, len
);
420 if ( nRead
== wxInvalidOffset
)
422 printf("Failed to read the file.");
426 fwrite(buf
, nRead
, 1, stdout
);
436 printf("ERROR: can't open test file.\n");
442 static void TestTextFileRead()
444 puts("*** wxTextFile read test ***");
446 wxTextFile
file(_T("testdata.fc"));
449 printf("Number of lines: %u\n", file
.GetLineCount());
450 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
454 puts("\nDumping the entire file:");
455 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
457 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
459 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
461 puts("\nAnd now backwards:");
462 for ( s
= file
.GetLastLine();
463 file
.GetCurrentLine() != 0;
464 s
= file
.GetPrevLine() )
466 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
468 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
472 printf("ERROR: can't open '%s'\n", file
.GetName());
478 static void TestFileCopy()
480 puts("*** Testing wxCopyFile ***");
482 static const wxChar
*filename1
= _T("testdata.fc");
483 static const wxChar
*filename2
= _T("test2");
484 if ( !wxCopyFile(filename1
, filename2
) )
486 puts("ERROR: failed to copy file");
490 wxFFile
f1(filename1
, "rb"),
493 if ( !f1
.IsOpened() || !f2
.IsOpened() )
495 puts("ERROR: failed to open file(s)");
500 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
502 puts("ERROR: failed to read file(s)");
506 if ( (s1
.length() != s2
.length()) ||
507 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
509 puts("ERROR: copy error!");
513 puts("File was copied ok.");
519 if ( !wxRemoveFile(filename2
) )
521 puts("ERROR: failed to remove the file");
529 // ----------------------------------------------------------------------------
531 // ----------------------------------------------------------------------------
535 #include <wx/confbase.h>
536 #include <wx/fileconf.h>
538 static const struct FileConfTestData
540 const wxChar
*name
; // value name
541 const wxChar
*value
; // the value from the file
544 { _T("value1"), _T("one") },
545 { _T("value2"), _T("two") },
546 { _T("novalue"), _T("default") },
549 static void TestFileConfRead()
551 puts("*** testing wxFileConfig loading/reading ***");
553 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
554 _T("testdata.fc"), wxEmptyString
,
555 wxCONFIG_USE_RELATIVE_PATH
);
557 // test simple reading
558 puts("\nReading config file:");
559 wxString
defValue(_T("default")), value
;
560 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
562 const FileConfTestData
& data
= fcTestData
[n
];
563 value
= fileconf
.Read(data
.name
, defValue
);
564 printf("\t%s = %s ", data
.name
, value
.c_str());
565 if ( value
== data
.value
)
571 printf("(ERROR: should be %s)\n", data
.value
);
575 // test enumerating the entries
576 puts("\nEnumerating all root entries:");
579 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
582 printf("\t%s = %s\n",
584 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
586 cont
= fileconf
.GetNextEntry(name
, dummy
);
590 #endif // TEST_FILECONF
592 // ----------------------------------------------------------------------------
594 // ----------------------------------------------------------------------------
598 #include <wx/filename.h>
600 static struct FileNameInfo
602 const wxChar
*fullname
;
608 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
609 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
610 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
611 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
612 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
613 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
614 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
615 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
618 static void TestFileNameConstruction()
620 puts("*** testing wxFileName construction ***");
622 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
624 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
626 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
627 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
629 puts("ERROR (couldn't be normalized)");
633 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
640 static void TestFileNameSplit()
642 puts("*** testing wxFileName splitting ***");
644 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
646 const FileNameInfo
&fni
= filenames
[n
];
647 wxString path
, name
, ext
;
648 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
650 printf("%s -> path = '%s', name = '%s', ext = '%s'",
651 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
652 if ( path
!= fni
.path
)
653 printf(" (ERROR: path = '%s')", fni
.path
);
654 if ( name
!= fni
.name
)
655 printf(" (ERROR: name = '%s')", fni
.name
);
656 if ( ext
!= fni
.ext
)
657 printf(" (ERROR: ext = '%s')", fni
.ext
);
664 static void TestFileNameComparison()
669 static void TestFileNameOperations()
674 static void TestFileNameCwd()
679 #endif // TEST_FILENAME
681 // ----------------------------------------------------------------------------
683 // ----------------------------------------------------------------------------
691 Foo(int n_
) { n
= n_
; count
++; }
699 size_t Foo::count
= 0;
701 WX_DECLARE_LIST(Foo
, wxListFoos
);
702 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
704 #include <wx/listimpl.cpp>
706 WX_DEFINE_LIST(wxListFoos
);
708 static void TestHash()
710 puts("*** Testing wxHashTable ***\n");
714 hash
.DeleteContents(TRUE
);
716 printf("Hash created: %u foos in hash, %u foos totally\n",
717 hash
.GetCount(), Foo::count
);
719 static const int hashTestData
[] =
721 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
725 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
727 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
730 printf("Hash filled: %u foos in hash, %u foos totally\n",
731 hash
.GetCount(), Foo::count
);
733 puts("Hash access test:");
734 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
736 printf("\tGetting element with key %d, value %d: ",
738 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
741 printf("ERROR, not found.\n");
745 printf("%d (%s)\n", foo
->n
,
746 (size_t)foo
->n
== n
? "ok" : "ERROR");
750 printf("\nTrying to get an element not in hash: ");
752 if ( hash
.Get(1234) || hash
.Get(1, 0) )
754 puts("ERROR: found!");
758 puts("ok (not found)");
762 printf("Hash destroyed: %u foos left\n", Foo::count
);
767 // ----------------------------------------------------------------------------
769 // ----------------------------------------------------------------------------
775 WX_DECLARE_LIST(Bar
, wxListBars
);
776 #include <wx/listimpl.cpp>
777 WX_DEFINE_LIST(wxListBars
);
779 static void TestListCtor()
781 puts("*** Testing wxList construction ***\n");
785 list1
.Append(new Bar(_T("first")));
786 list1
.Append(new Bar(_T("second")));
788 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
789 list1
.GetCount(), Bar::GetNumber());
794 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
795 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
797 list1
.DeleteContents(TRUE
);
800 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
805 // ----------------------------------------------------------------------------
807 // ----------------------------------------------------------------------------
811 #include <wx/mimetype.h>
813 static void TestMimeEnum()
815 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
817 wxArrayString mimetypes
;
819 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
821 printf("*** All %u known filetypes: ***\n", count
);
826 for ( size_t n
= 0; n
< count
; n
++ )
828 wxFileType
*filetype
=
829 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
832 printf("nothing known about the filetype '%s'!\n",
833 mimetypes
[n
].c_str());
837 filetype
->GetDescription(&desc
);
838 filetype
->GetExtensions(exts
);
840 filetype
->GetIcon(NULL
);
843 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
850 printf("\t%s: %s (%s)\n",
851 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
857 static void TestMimeOverride()
859 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
861 static const wxChar
*mailcap
= _T("/tmp/mailcap");
862 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
864 if ( wxFile::Exists(mailcap
) )
865 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
867 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
869 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
872 if ( wxFile::Exists(mimetypes
) )
873 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
875 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
877 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
883 static void TestMimeFilename()
885 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
887 static const wxChar
*filenames
[] =
894 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
896 const wxString fname
= filenames
[n
];
897 wxString ext
= fname
.AfterLast(_T('.'));
898 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
901 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
906 if ( !ft
->GetDescription(&desc
) )
907 desc
= _T("<no description>");
910 if ( !ft
->GetOpenCommand(&cmd
,
911 wxFileType::MessageParameters(fname
, _T(""))) )
912 cmd
= _T("<no command available>");
914 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
915 fname
.c_str(), desc
.c_str(), cmd
.c_str());
924 static void TestMimeAssociate()
926 wxPuts(_T("*** Testing creation of filetype association ***\n"));
928 wxFileTypeInfo
ftInfo(
929 _T("application/x-xyz"),
930 _T("xyzview '%s'"), // open cmd
932 _T("XYZ File") // description
933 _T(".xyz"), // extensions
934 NULL
// end of extensions
936 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
938 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
941 wxPuts(_T("ERROR: failed to create association!"));
945 // TODO: read it back
954 // ----------------------------------------------------------------------------
955 // misc information functions
956 // ----------------------------------------------------------------------------
958 #ifdef TEST_INFO_FUNCTIONS
960 #include <wx/utils.h>
962 static void TestOsInfo()
964 puts("*** Testing OS info functions ***\n");
967 wxGetOsVersion(&major
, &minor
);
968 printf("Running under: %s, version %d.%d\n",
969 wxGetOsDescription().c_str(), major
, minor
);
971 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
973 printf("Host name is %s (%s).\n",
974 wxGetHostName().c_str(), wxGetFullHostName().c_str());
979 static void TestUserInfo()
981 puts("*** Testing user info functions ***\n");
983 printf("User id is:\t%s\n", wxGetUserId().c_str());
984 printf("User name is:\t%s\n", wxGetUserName().c_str());
985 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
986 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
991 #endif // TEST_INFO_FUNCTIONS
993 // ----------------------------------------------------------------------------
995 // ----------------------------------------------------------------------------
999 #include <wx/longlong.h>
1000 #include <wx/timer.h>
1002 // make a 64 bit number from 4 16 bit ones
1003 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1005 // get a random 64 bit number
1006 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1008 #if wxUSE_LONGLONG_WX
1009 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1010 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1011 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1012 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1013 #endif // wxUSE_LONGLONG_WX
1015 static void TestSpeed()
1017 static const long max
= 100000000;
1024 for ( n
= 0; n
< max
; n
++ )
1029 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1032 #if wxUSE_LONGLONG_NATIVE
1037 for ( n
= 0; n
< max
; n
++ )
1042 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1044 #endif // wxUSE_LONGLONG_NATIVE
1050 for ( n
= 0; n
< max
; n
++ )
1055 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1059 static void TestLongLongConversion()
1061 puts("*** Testing wxLongLong conversions ***\n");
1065 for ( size_t n
= 0; n
< 100000; n
++ )
1069 #if wxUSE_LONGLONG_NATIVE
1070 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1072 wxASSERT_MSG( a
== b
, "conversions failure" );
1074 puts("Can't do it without native long long type, test skipped.");
1077 #endif // wxUSE_LONGLONG_NATIVE
1079 if ( !(nTested
% 1000) )
1091 static void TestMultiplication()
1093 puts("*** Testing wxLongLong multiplication ***\n");
1097 for ( size_t n
= 0; n
< 100000; n
++ )
1102 #if wxUSE_LONGLONG_NATIVE
1103 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1104 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1106 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1107 #else // !wxUSE_LONGLONG_NATIVE
1108 puts("Can't do it without native long long type, test skipped.");
1111 #endif // wxUSE_LONGLONG_NATIVE
1113 if ( !(nTested
% 1000) )
1125 static void TestDivision()
1127 puts("*** Testing wxLongLong division ***\n");
1131 for ( size_t n
= 0; n
< 100000; n
++ )
1133 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1134 // multiplication will not overflow)
1135 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1137 // get a random long (not wxLongLong for now) to divide it with
1142 #if wxUSE_LONGLONG_NATIVE
1143 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1145 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1146 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1147 #else // !wxUSE_LONGLONG_NATIVE
1148 // verify the result
1149 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1150 #endif // wxUSE_LONGLONG_NATIVE
1152 if ( !(nTested
% 1000) )
1164 static void TestAddition()
1166 puts("*** Testing wxLongLong addition ***\n");
1170 for ( size_t n
= 0; n
< 100000; n
++ )
1176 #if wxUSE_LONGLONG_NATIVE
1177 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1178 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1179 "addition failure" );
1180 #else // !wxUSE_LONGLONG_NATIVE
1181 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1182 #endif // wxUSE_LONGLONG_NATIVE
1184 if ( !(nTested
% 1000) )
1196 static void TestBitOperations()
1198 puts("*** Testing wxLongLong bit operation ***\n");
1202 for ( size_t n
= 0; n
< 100000; n
++ )
1206 #if wxUSE_LONGLONG_NATIVE
1207 for ( size_t n
= 0; n
< 33; n
++ )
1210 #else // !wxUSE_LONGLONG_NATIVE
1211 puts("Can't do it without native long long type, test skipped.");
1214 #endif // wxUSE_LONGLONG_NATIVE
1216 if ( !(nTested
% 1000) )
1228 static void TestLongLongComparison()
1230 puts("*** Testing wxLongLong comparison ***\n");
1232 static const long testLongs
[] =
1243 static const long ls
[2] =
1249 wxLongLongWx lls
[2];
1253 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1257 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1259 res
= lls
[m
] > testLongs
[n
];
1260 printf("0x%lx > 0x%lx is %s (%s)\n",
1261 ls
[m
], testLongs
[n
], res
? "true" : "false",
1262 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1264 res
= lls
[m
] < testLongs
[n
];
1265 printf("0x%lx < 0x%lx is %s (%s)\n",
1266 ls
[m
], testLongs
[n
], res
? "true" : "false",
1267 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1269 res
= lls
[m
] == testLongs
[n
];
1270 printf("0x%lx == 0x%lx is %s (%s)\n",
1271 ls
[m
], testLongs
[n
], res
? "true" : "false",
1272 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1280 #endif // TEST_LONGLONG
1282 // ----------------------------------------------------------------------------
1284 // ----------------------------------------------------------------------------
1286 #ifdef TEST_PATHLIST
1288 static void TestPathList()
1290 puts("*** Testing wxPathList ***\n");
1292 wxPathList pathlist
;
1293 pathlist
.AddEnvList("PATH");
1294 wxString path
= pathlist
.FindValidPath("ls");
1297 printf("ERROR: command not found in the path.\n");
1301 printf("Command found in the path as '%s'.\n", path
.c_str());
1305 #endif // TEST_PATHLIST
1307 // ----------------------------------------------------------------------------
1309 // ----------------------------------------------------------------------------
1311 // this is for MSW only
1313 #undef TEST_REGISTRY
1316 #ifdef TEST_REGISTRY
1318 #include <wx/msw/registry.h>
1320 // I chose this one because I liked its name, but it probably only exists under
1322 static const wxChar
*TESTKEY
=
1323 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1325 static void TestRegistryRead()
1327 puts("*** testing registry reading ***");
1329 wxRegKey
key(TESTKEY
);
1330 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1333 puts("ERROR: test key can't be opened, aborting test.");
1338 size_t nSubKeys
, nValues
;
1339 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1341 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1344 printf("Enumerating values:\n");
1348 bool cont
= key
.GetFirstValue(value
, dummy
);
1351 printf("Value '%s': type ", value
.c_str());
1352 switch ( key
.GetValueType(value
) )
1354 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1355 case wxRegKey::Type_String
: printf("SZ"); break;
1356 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1357 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1358 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1359 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1360 default: printf("other (unknown)"); break;
1363 printf(", value = ");
1364 if ( key
.IsNumericValue(value
) )
1367 key
.QueryValue(value
, &val
);
1373 key
.QueryValue(value
, val
);
1374 printf("'%s'", val
.c_str());
1376 key
.QueryRawValue(value
, val
);
1377 printf(" (raw value '%s')", val
.c_str());
1382 cont
= key
.GetNextValue(value
, dummy
);
1386 static void TestRegistryAssociation()
1389 The second call to deleteself genertaes an error message, with a
1390 messagebox saying .flo is crucial to system operation, while the .ddf
1391 call also fails, but with no error message
1396 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1398 key
= "ddxf_auto_file" ;
1399 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1401 key
= "ddxf_auto_file" ;
1402 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1405 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1407 key
= "program \"%1\"" ;
1409 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1411 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1413 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1415 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1419 #endif // TEST_REGISTRY
1421 // ----------------------------------------------------------------------------
1423 // ----------------------------------------------------------------------------
1427 #include <wx/socket.h>
1428 #include <wx/protocol/protocol.h>
1429 #include <wx/protocol/http.h>
1431 static void TestSocketServer()
1433 puts("*** Testing wxSocketServer ***\n");
1435 static const int PORT
= 3000;
1440 wxSocketServer
*server
= new wxSocketServer(addr
);
1441 if ( !server
->Ok() )
1443 puts("ERROR: failed to bind");
1450 printf("Server: waiting for connection on port %d...\n", PORT
);
1452 wxSocketBase
*socket
= server
->Accept();
1455 puts("ERROR: wxSocketServer::Accept() failed.");
1459 puts("Server: got a client.");
1461 server
->SetTimeout(60); // 1 min
1463 while ( socket
->IsConnected() )
1469 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1471 // don't log error if the client just close the connection
1472 if ( socket
->IsConnected() )
1474 puts("ERROR: in wxSocket::Read.");
1494 printf("Server: got '%s'.\n", s
.c_str());
1495 if ( s
== _T("bye") )
1502 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1503 socket
->Write("\r\n", 2);
1504 printf("Server: wrote '%s'.\n", s
.c_str());
1507 puts("Server: lost a client.");
1512 // same as "delete server" but is consistent with GUI programs
1516 static void TestSocketClient()
1518 puts("*** Testing wxSocketClient ***\n");
1520 static const char *hostname
= "www.wxwindows.org";
1523 addr
.Hostname(hostname
);
1526 printf("--- Attempting to connect to %s:80...\n", hostname
);
1528 wxSocketClient client
;
1529 if ( !client
.Connect(addr
) )
1531 printf("ERROR: failed to connect to %s\n", hostname
);
1535 printf("--- Connected to %s:%u...\n",
1536 addr
.Hostname().c_str(), addr
.Service());
1540 // could use simply "GET" here I suppose
1542 wxString::Format("GET http://%s/\r\n", hostname
);
1543 client
.Write(cmdGet
, cmdGet
.length());
1544 printf("--- Sent command '%s' to the server\n",
1545 MakePrintable(cmdGet
).c_str());
1546 client
.Read(buf
, WXSIZEOF(buf
));
1547 printf("--- Server replied:\n%s", buf
);
1551 #endif // TEST_SOCKETS
1553 // ----------------------------------------------------------------------------
1555 // ----------------------------------------------------------------------------
1559 #include <wx/protocol/ftp.h>
1563 #define FTP_ANONYMOUS
1565 #ifdef FTP_ANONYMOUS
1566 static const char *directory
= "/pub";
1567 static const char *filename
= "welcome.msg";
1569 static const char *directory
= "/etc";
1570 static const char *filename
= "issue";
1573 static bool TestFtpConnect()
1575 puts("*** Testing FTP connect ***");
1577 #ifdef FTP_ANONYMOUS
1578 static const char *hostname
= "ftp.wxwindows.org";
1580 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1581 #else // !FTP_ANONYMOUS
1582 static const char *hostname
= "localhost";
1585 fgets(user
, WXSIZEOF(user
), stdin
);
1586 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
1590 printf("Password for %s: ", password
);
1591 fgets(password
, WXSIZEOF(password
), stdin
);
1592 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
1593 ftp
.SetPassword(password
);
1595 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
1596 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
1598 if ( !ftp
.Connect(hostname
) )
1600 printf("ERROR: failed to connect to %s\n", hostname
);
1606 printf("--- Connected to %s, current directory is '%s'\n",
1607 hostname
, ftp
.Pwd().c_str());
1613 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
1614 static void TestFtpWuFtpd()
1617 static const char *hostname
= "ftp.eudora.com";
1618 if ( !ftp
.Connect(hostname
) )
1620 printf("ERROR: failed to connect to %s\n", hostname
);
1624 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
1625 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1628 printf("ERROR: couldn't get input stream for %s\n", filename
);
1632 size_t size
= in
->StreamSize();
1633 printf("Reading file %s (%u bytes)...", filename
, size
);
1635 char *data
= new char[size
];
1636 if ( !in
->Read(data
, size
) )
1638 puts("ERROR: read error");
1642 printf("Successfully retrieved the file.\n");
1651 static void TestFtpList()
1653 puts("*** Testing wxFTP file listing ***\n");
1656 if ( !ftp
.ChDir(directory
) )
1658 printf("ERROR: failed to cd to %s\n", directory
);
1661 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
1663 // test NLIST and LIST
1664 wxArrayString files
;
1665 if ( !ftp
.GetFilesList(files
) )
1667 puts("ERROR: failed to get NLIST of files");
1671 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
1672 size_t count
= files
.GetCount();
1673 for ( size_t n
= 0; n
< count
; n
++ )
1675 printf("\t%s\n", files
[n
].c_str());
1677 puts("End of the file list");
1680 if ( !ftp
.GetDirList(files
) )
1682 puts("ERROR: failed to get LIST of files");
1686 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
1687 size_t count
= files
.GetCount();
1688 for ( size_t n
= 0; n
< count
; n
++ )
1690 printf("\t%s\n", files
[n
].c_str());
1692 puts("End of the file list");
1695 if ( !ftp
.ChDir(_T("..")) )
1697 puts("ERROR: failed to cd to ..");
1700 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
1703 static void TestFtpDownload()
1705 puts("*** Testing wxFTP download ***\n");
1708 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1711 printf("ERROR: couldn't get input stream for %s\n", filename
);
1715 size_t size
= in
->StreamSize();
1716 printf("Reading file %s (%u bytes)...", filename
, size
);
1719 char *data
= new char[size
];
1720 if ( !in
->Read(data
, size
) )
1722 puts("ERROR: read error");
1726 printf("\nContents of %s:\n%s\n", filename
, data
);
1734 static void TestFtpFileSize()
1736 puts("*** Testing FTP SIZE command ***");
1738 if ( !ftp
.ChDir(directory
) )
1740 printf("ERROR: failed to cd to %s\n", directory
);
1743 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
1745 if ( ftp
.FileExists(filename
) )
1747 int size
= ftp
.GetFileSize(filename
);
1749 printf("ERROR: couldn't get size of '%s'\n", filename
);
1751 printf("Size of '%s' is %d bytes.\n", filename
, size
);
1755 printf("ERROR: '%s' doesn't exist\n", filename
);
1759 static void TestFtpMisc()
1761 puts("*** Testing miscellaneous wxFTP functions ***");
1763 if ( ftp
.SendCommand("STAT") != '2' )
1765 puts("ERROR: STAT failed");
1769 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
1772 if ( ftp
.SendCommand("HELP SITE") != '2' )
1774 puts("ERROR: HELP SITE failed");
1778 printf("The list of site-specific commands:\n\n%s\n",
1779 ftp
.GetLastResult().c_str());
1783 static void TestFtpInteractive()
1785 puts("\n*** Interactive wxFTP test ***");
1791 printf("Enter FTP command: ");
1792 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
1795 // kill the last '\n'
1796 buf
[strlen(buf
) - 1] = 0;
1798 // special handling of LIST and NLST as they require data connection
1799 wxString
start(buf
, 4);
1801 if ( start
== "LIST" || start
== "NLST" )
1804 if ( strlen(buf
) > 4 )
1807 wxArrayString files
;
1808 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
1810 printf("ERROR: failed to get %s of files\n", start
.c_str());
1814 printf("--- %s of '%s' under '%s':\n",
1815 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
1816 size_t count
= files
.GetCount();
1817 for ( size_t n
= 0; n
< count
; n
++ )
1819 printf("\t%s\n", files
[n
].c_str());
1821 puts("--- End of the file list");
1826 char ch
= ftp
.SendCommand(buf
);
1827 printf("Command %s", ch
? "succeeded" : "failed");
1830 printf(" (return code %c)", ch
);
1833 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
1837 puts("\n*** done ***");
1840 static void TestFtpUpload()
1842 puts("*** Testing wxFTP uploading ***\n");
1845 static const char *file1
= "test1";
1846 static const char *file2
= "test2";
1847 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
1850 printf("--- Uploading to %s ---\n", file1
);
1851 out
->Write("First hello", 11);
1855 // send a command to check the remote file
1856 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
1858 printf("ERROR: STAT %s failed\n", file1
);
1862 printf("STAT %s returned:\n\n%s\n",
1863 file1
, ftp
.GetLastResult().c_str());
1866 out
= ftp
.GetOutputStream(file2
);
1869 printf("--- Uploading to %s ---\n", file1
);
1870 out
->Write("Second hello", 12);
1877 // ----------------------------------------------------------------------------
1879 // ----------------------------------------------------------------------------
1883 #include <wx/wfstream.h>
1884 #include <wx/mstream.h>
1886 static void TestFileStream()
1888 puts("*** Testing wxFileInputStream ***");
1890 static const wxChar
*filename
= _T("testdata.fs");
1892 wxFileOutputStream
fsOut(filename
);
1893 fsOut
.Write("foo", 3);
1896 wxFileInputStream
fsIn(filename
);
1897 printf("File stream size: %u\n", fsIn
.GetSize());
1898 while ( !fsIn
.Eof() )
1900 putchar(fsIn
.GetC());
1903 if ( !wxRemoveFile(filename
) )
1905 printf("ERROR: failed to remove the file '%s'.\n", filename
);
1908 puts("\n*** wxFileInputStream test done ***");
1911 static void TestMemoryStream()
1913 puts("*** Testing wxMemoryInputStream ***");
1916 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
1918 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
1919 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
1920 while ( !memInpStream
.Eof() )
1922 putchar(memInpStream
.GetC());
1925 puts("\n*** wxMemoryInputStream test done ***");
1928 #endif // TEST_STREAMS
1930 // ----------------------------------------------------------------------------
1932 // ----------------------------------------------------------------------------
1936 #include <wx/timer.h>
1937 #include <wx/utils.h>
1939 static void TestStopWatch()
1941 puts("*** Testing wxStopWatch ***\n");
1944 printf("Sleeping 3 seconds...");
1946 printf("\telapsed time: %ldms\n", sw
.Time());
1949 printf("Sleeping 2 more seconds...");
1951 printf("\telapsed time: %ldms\n", sw
.Time());
1954 printf("And 3 more seconds...");
1956 printf("\telapsed time: %ldms\n", sw
.Time());
1959 puts("\nChecking for 'backwards clock' bug...");
1960 for ( size_t n
= 0; n
< 70; n
++ )
1964 for ( size_t m
= 0; m
< 100000; m
++ )
1966 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
1968 puts("\ntime is negative - ERROR!");
1978 #endif // TEST_TIMER
1980 // ----------------------------------------------------------------------------
1982 // ----------------------------------------------------------------------------
1986 #include <wx/vcard.h>
1988 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
1991 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
1995 wxString(_T('\t'), level
).c_str(),
1996 vcObj
->GetName().c_str());
1999 switch ( vcObj
->GetType() )
2001 case wxVCardObject::String
:
2002 case wxVCardObject::UString
:
2005 vcObj
->GetValue(&val
);
2006 value
<< _T('"') << val
<< _T('"');
2010 case wxVCardObject::Int
:
2013 vcObj
->GetValue(&i
);
2014 value
.Printf(_T("%u"), i
);
2018 case wxVCardObject::Long
:
2021 vcObj
->GetValue(&l
);
2022 value
.Printf(_T("%lu"), l
);
2026 case wxVCardObject::None
:
2029 case wxVCardObject::Object
:
2030 value
= _T("<node>");
2034 value
= _T("<unknown value type>");
2038 printf(" = %s", value
.c_str());
2041 DumpVObject(level
+ 1, *vcObj
);
2044 vcObj
= vcard
.GetNextProp(&cookie
);
2048 static void DumpVCardAddresses(const wxVCard
& vcard
)
2050 puts("\nShowing all addresses from vCard:\n");
2054 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2058 int flags
= addr
->GetFlags();
2059 if ( flags
& wxVCardAddress::Domestic
)
2061 flagsStr
<< _T("domestic ");
2063 if ( flags
& wxVCardAddress::Intl
)
2065 flagsStr
<< _T("international ");
2067 if ( flags
& wxVCardAddress::Postal
)
2069 flagsStr
<< _T("postal ");
2071 if ( flags
& wxVCardAddress::Parcel
)
2073 flagsStr
<< _T("parcel ");
2075 if ( flags
& wxVCardAddress::Home
)
2077 flagsStr
<< _T("home ");
2079 if ( flags
& wxVCardAddress::Work
)
2081 flagsStr
<< _T("work ");
2084 printf("Address %u:\n"
2086 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2089 addr
->GetPostOffice().c_str(),
2090 addr
->GetExtAddress().c_str(),
2091 addr
->GetStreet().c_str(),
2092 addr
->GetLocality().c_str(),
2093 addr
->GetRegion().c_str(),
2094 addr
->GetPostalCode().c_str(),
2095 addr
->GetCountry().c_str()
2099 addr
= vcard
.GetNextAddress(&cookie
);
2103 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2105 puts("\nShowing all phone numbers from vCard:\n");
2109 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2113 int flags
= phone
->GetFlags();
2114 if ( flags
& wxVCardPhoneNumber::Voice
)
2116 flagsStr
<< _T("voice ");
2118 if ( flags
& wxVCardPhoneNumber::Fax
)
2120 flagsStr
<< _T("fax ");
2122 if ( flags
& wxVCardPhoneNumber::Cellular
)
2124 flagsStr
<< _T("cellular ");
2126 if ( flags
& wxVCardPhoneNumber::Modem
)
2128 flagsStr
<< _T("modem ");
2130 if ( flags
& wxVCardPhoneNumber::Home
)
2132 flagsStr
<< _T("home ");
2134 if ( flags
& wxVCardPhoneNumber::Work
)
2136 flagsStr
<< _T("work ");
2139 printf("Phone number %u:\n"
2144 phone
->GetNumber().c_str()
2148 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2152 static void TestVCardRead()
2154 puts("*** Testing wxVCard reading ***\n");
2156 wxVCard
vcard(_T("vcard.vcf"));
2157 if ( !vcard
.IsOk() )
2159 puts("ERROR: couldn't load vCard.");
2163 // read individual vCard properties
2164 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2168 vcObj
->GetValue(&value
);
2173 value
= _T("<none>");
2176 printf("Full name retrieved directly: %s\n", value
.c_str());
2179 if ( !vcard
.GetFullName(&value
) )
2181 value
= _T("<none>");
2184 printf("Full name from wxVCard API: %s\n", value
.c_str());
2186 // now show how to deal with multiply occuring properties
2187 DumpVCardAddresses(vcard
);
2188 DumpVCardPhoneNumbers(vcard
);
2190 // and finally show all
2191 puts("\nNow dumping the entire vCard:\n"
2192 "-----------------------------\n");
2194 DumpVObject(0, vcard
);
2198 static void TestVCardWrite()
2200 puts("*** Testing wxVCard writing ***\n");
2203 if ( !vcard
.IsOk() )
2205 puts("ERROR: couldn't create vCard.");
2210 vcard
.SetName("Zeitlin", "Vadim");
2211 vcard
.SetFullName("Vadim Zeitlin");
2212 vcard
.SetOrganization("wxWindows", "R&D");
2214 // just dump the vCard back
2215 puts("Entire vCard follows:\n");
2216 puts(vcard
.Write());
2220 #endif // TEST_VCARD
2222 // ----------------------------------------------------------------------------
2223 // wide char (Unicode) support
2224 // ----------------------------------------------------------------------------
2228 #include <wx/strconv.h>
2229 #include <wx/fontenc.h>
2230 #include <wx/encconv.h>
2231 #include <wx/buffer.h>
2233 static void TestUtf8()
2235 puts("*** Testing UTF8 support ***\n");
2237 static const char textInUtf8
[] =
2239 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2240 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2241 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2242 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2243 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2244 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2245 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2250 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2252 puts("ERROR: UTF-8 decoding failed.");
2256 // using wxEncodingConverter
2258 wxEncodingConverter ec
;
2259 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2260 ec
.Convert(wbuf
, buf
);
2261 #else // using wxCSConv
2262 wxCSConv
conv(_T("koi8-r"));
2263 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2265 puts("ERROR: conversion to KOI8-R failed.");
2270 printf("The resulting string (in koi8-r): %s\n", buf
);
2274 #endif // TEST_WCHAR
2276 // ----------------------------------------------------------------------------
2278 // ----------------------------------------------------------------------------
2282 #include "wx/filesys.h"
2283 #include "wx/fs_zip.h"
2284 #include "wx/zipstrm.h"
2286 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
2288 static void TestZipStreamRead()
2290 puts("*** Testing ZIP reading ***\n");
2292 static const wxChar
*filename
= _T("foo");
2293 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
2294 printf("Archive size: %u\n", istr
.GetSize());
2296 printf("Dumping the file '%s':\n", filename
);
2297 while ( !istr
.Eof() )
2299 putchar(istr
.GetC());
2303 puts("\n----- done ------");
2306 static void DumpZipDirectory(wxFileSystem
& fs
,
2307 const wxString
& dir
,
2308 const wxString
& indent
)
2310 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
2311 TESTFILE_ZIP
, dir
.c_str());
2312 wxString wildcard
= prefix
+ _T("/*");
2314 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
2315 while ( !dirname
.empty() )
2317 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
2319 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2324 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
2326 DumpZipDirectory(fs
, dirname
,
2327 indent
+ wxString(_T(' '), 4));
2329 dirname
= fs
.FindNext();
2332 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
2333 while ( !filename
.empty() )
2335 if ( !filename
.StartsWith(prefix
, &filename
) )
2337 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2342 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
2344 filename
= fs
.FindNext();
2348 static void TestZipFileSystem()
2350 puts("*** Testing ZIP file system ***\n");
2352 wxFileSystem::AddHandler(new wxZipFSHandler
);
2354 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
2356 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
2361 // ----------------------------------------------------------------------------
2363 // ----------------------------------------------------------------------------
2367 #include <wx/zstream.h>
2368 #include <wx/wfstream.h>
2370 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2371 static const char *TEST_DATA
= "hello and hello again";
2373 static void TestZlibStreamWrite()
2375 puts("*** Testing Zlib stream reading ***\n");
2377 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2378 wxZlibOutputStream
ostr(fileOutStream
, 0);
2379 printf("Compressing the test string... ");
2380 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2383 puts("(ERROR: failed)");
2390 puts("\n----- done ------");
2393 static void TestZlibStreamRead()
2395 puts("*** Testing Zlib stream reading ***\n");
2397 wxFileInputStream
fileInStream(FILENAME_GZ
);
2398 wxZlibInputStream
istr(fileInStream
);
2399 printf("Archive size: %u\n", istr
.GetSize());
2401 puts("Dumping the file:");
2402 while ( !istr
.Eof() )
2404 putchar(istr
.GetC());
2408 puts("\n----- done ------");
2413 // ----------------------------------------------------------------------------
2415 // ----------------------------------------------------------------------------
2417 #ifdef TEST_DATETIME
2419 #include <wx/date.h>
2421 #include <wx/datetime.h>
2426 wxDateTime::wxDateTime_t day
;
2427 wxDateTime::Month month
;
2429 wxDateTime::wxDateTime_t hour
, min
, sec
;
2431 wxDateTime::WeekDay wday
;
2432 time_t gmticks
, ticks
;
2434 void Init(const wxDateTime::Tm
& tm
)
2443 gmticks
= ticks
= -1;
2446 wxDateTime
DT() const
2447 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2449 bool SameDay(const wxDateTime::Tm
& tm
) const
2451 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2454 wxString
Format() const
2457 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2459 wxDateTime::GetMonthName(month
).c_str(),
2461 abs(wxDateTime::ConvertYearToBC(year
)),
2462 year
> 0 ? "AD" : "BC");
2466 wxString
FormatDate() const
2469 s
.Printf("%02d-%s-%4d%s",
2471 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2472 abs(wxDateTime::ConvertYearToBC(year
)),
2473 year
> 0 ? "AD" : "BC");
2478 static const Date testDates
[] =
2480 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2481 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2482 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2483 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2484 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2485 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2486 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2487 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2488 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2489 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2490 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2491 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2492 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2493 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2494 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2497 // this test miscellaneous static wxDateTime functions
2498 static void TestTimeStatic()
2500 puts("\n*** wxDateTime static methods test ***");
2502 // some info about the current date
2503 int year
= wxDateTime::GetCurrentYear();
2504 printf("Current year %d is %sa leap one and has %d days.\n",
2506 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2507 wxDateTime::GetNumberOfDays(year
));
2509 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2510 printf("Current month is '%s' ('%s') and it has %d days\n",
2511 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2512 wxDateTime::GetMonthName(month
).c_str(),
2513 wxDateTime::GetNumberOfDays(month
));
2516 static const size_t nYears
= 5;
2517 static const size_t years
[2][nYears
] =
2519 // first line: the years to test
2520 { 1990, 1976, 2000, 2030, 1984, },
2522 // second line: TRUE if leap, FALSE otherwise
2523 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2526 for ( size_t n
= 0; n
< nYears
; n
++ )
2528 int year
= years
[0][n
];
2529 bool should
= years
[1][n
] != 0,
2530 is
= wxDateTime::IsLeapYear(year
);
2532 printf("Year %d is %sa leap year (%s)\n",
2535 should
== is
? "ok" : "ERROR");
2537 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2541 // test constructing wxDateTime objects
2542 static void TestTimeSet()
2544 puts("\n*** wxDateTime construction test ***");
2546 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2548 const Date
& d1
= testDates
[n
];
2549 wxDateTime dt
= d1
.DT();
2552 d2
.Init(dt
.GetTm());
2554 wxString s1
= d1
.Format(),
2557 printf("Date: %s == %s (%s)\n",
2558 s1
.c_str(), s2
.c_str(),
2559 s1
== s2
? "ok" : "ERROR");
2563 // test time zones stuff
2564 static void TestTimeZones()
2566 puts("\n*** wxDateTime timezone test ***");
2568 wxDateTime now
= wxDateTime::Now();
2570 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2571 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2572 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2573 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2574 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2575 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2577 wxDateTime::Tm tm
= now
.GetTm();
2578 if ( wxDateTime(tm
) != now
)
2580 printf("ERROR: got %s instead of %s\n",
2581 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2585 // test some minimal support for the dates outside the standard range
2586 static void TestTimeRange()
2588 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2590 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
2592 printf("Unix epoch:\t%s\n",
2593 wxDateTime(2440587.5).Format(fmt
).c_str());
2594 printf("Feb 29, 0: \t%s\n",
2595 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
2596 printf("JDN 0: \t%s\n",
2597 wxDateTime(0.0).Format(fmt
).c_str());
2598 printf("Jan 1, 1AD:\t%s\n",
2599 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
2600 printf("May 29, 2099:\t%s\n",
2601 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
2604 static void TestTimeTicks()
2606 puts("\n*** wxDateTime ticks test ***");
2608 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2610 const Date
& d
= testDates
[n
];
2611 if ( d
.ticks
== -1 )
2614 wxDateTime dt
= d
.DT();
2615 long ticks
= (dt
.GetValue() / 1000).ToLong();
2616 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2617 if ( ticks
== d
.ticks
)
2623 printf(" (ERROR: should be %ld, delta = %ld)\n",
2624 d
.ticks
, ticks
- d
.ticks
);
2627 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
2628 ticks
= (dt
.GetValue() / 1000).ToLong();
2629 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2630 if ( ticks
== d
.gmticks
)
2636 printf(" (ERROR: should be %ld, delta = %ld)\n",
2637 d
.gmticks
, ticks
- d
.gmticks
);
2644 // test conversions to JDN &c
2645 static void TestTimeJDN()
2647 puts("\n*** wxDateTime to JDN test ***");
2649 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2651 const Date
& d
= testDates
[n
];
2652 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2653 double jdn
= dt
.GetJulianDayNumber();
2655 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
2662 printf(" (ERROR: should be %f, delta = %f)\n",
2663 d
.jdn
, jdn
- d
.jdn
);
2668 // test week days computation
2669 static void TestTimeWDays()
2671 puts("\n*** wxDateTime weekday test ***");
2673 // test GetWeekDay()
2675 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2677 const Date
& d
= testDates
[n
];
2678 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2680 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
2683 wxDateTime::GetWeekDayName(wday
).c_str());
2684 if ( wday
== d
.wday
)
2690 printf(" (ERROR: should be %s)\n",
2691 wxDateTime::GetWeekDayName(d
.wday
).c_str());
2697 // test SetToWeekDay()
2698 struct WeekDateTestData
2700 Date date
; // the real date (precomputed)
2701 int nWeek
; // its week index in the month
2702 wxDateTime::WeekDay wday
; // the weekday
2703 wxDateTime::Month month
; // the month
2704 int year
; // and the year
2706 wxString
Format() const
2709 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
2711 case 1: which
= "first"; break;
2712 case 2: which
= "second"; break;
2713 case 3: which
= "third"; break;
2714 case 4: which
= "fourth"; break;
2715 case 5: which
= "fifth"; break;
2717 case -1: which
= "last"; break;
2722 which
+= " from end";
2725 s
.Printf("The %s %s of %s in %d",
2727 wxDateTime::GetWeekDayName(wday
).c_str(),
2728 wxDateTime::GetMonthName(month
).c_str(),
2735 // the array data was generated by the following python program
2737 from DateTime import *
2738 from whrandom import *
2739 from string import *
2741 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2742 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2744 week = DateTimeDelta(7)
2747 year = randint(1900, 2100)
2748 month = randint(1, 12)
2749 day = randint(1, 28)
2750 dt = DateTime(year, month, day)
2751 wday = dt.day_of_week
2753 countFromEnd = choice([-1, 1])
2756 while dt.month is month:
2757 dt = dt - countFromEnd * week
2758 weekNum = weekNum + countFromEnd
2760 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
2762 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
2763 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
2766 static const WeekDateTestData weekDatesTestData
[] =
2768 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
2769 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
2770 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
2771 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
2772 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
2773 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
2774 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
2775 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
2776 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
2777 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
2778 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
2779 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
2780 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
2781 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
2782 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
2783 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
2784 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
2785 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
2786 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
2787 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
2790 static const char *fmt
= "%d-%b-%Y";
2793 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
2795 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
2797 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
2799 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
2801 const Date
& d
= wd
.date
;
2802 if ( d
.SameDay(dt
.GetTm()) )
2808 dt
.Set(d
.day
, d
.month
, d
.year
);
2810 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
2815 // test the computation of (ISO) week numbers
2816 static void TestTimeWNumber()
2818 puts("\n*** wxDateTime week number test ***");
2820 struct WeekNumberTestData
2822 Date date
; // the date
2823 wxDateTime::wxDateTime_t week
; // the week number in the year
2824 wxDateTime::wxDateTime_t wmon
; // the week number in the month
2825 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
2826 wxDateTime::wxDateTime_t dnum
; // day number in the year
2829 // data generated with the following python script:
2831 from DateTime import *
2832 from whrandom import *
2833 from string import *
2835 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2836 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2838 def GetMonthWeek(dt):
2839 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
2840 if weekNumMonth < 0:
2841 weekNumMonth = weekNumMonth + 53
2844 def GetLastSundayBefore(dt):
2845 if dt.iso_week[2] == 7:
2848 return dt - DateTimeDelta(dt.iso_week[2])
2851 year = randint(1900, 2100)
2852 month = randint(1, 12)
2853 day = randint(1, 28)
2854 dt = DateTime(year, month, day)
2855 dayNum = dt.day_of_year
2856 weekNum = dt.iso_week[1]
2857 weekNumMonth = GetMonthWeek(dt)
2860 dtSunday = GetLastSundayBefore(dt)
2862 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
2863 weekNumMonth2 = weekNumMonth2 + 1
2864 dtSunday = dtSunday - DateTimeDelta(7)
2866 data = { 'day': rjust(`day`, 2), \
2867 'month': monthNames[month - 1], \
2869 'weekNum': rjust(`weekNum`, 2), \
2870 'weekNumMonth': weekNumMonth, \
2871 'weekNumMonth2': weekNumMonth2, \
2872 'dayNum': rjust(`dayNum`, 3) }
2874 print " { { %(day)s, "\
2875 "wxDateTime::%(month)s, "\
2878 "%(weekNumMonth)s, "\
2879 "%(weekNumMonth2)s, "\
2880 "%(dayNum)s }," % data
2883 static const WeekNumberTestData weekNumberTestDates
[] =
2885 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
2886 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
2887 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
2888 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
2889 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
2890 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
2891 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
2892 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
2893 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
2894 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
2895 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
2896 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
2897 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
2898 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
2899 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
2900 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
2901 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
2902 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
2903 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
2904 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
2907 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
2909 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
2910 const Date
& d
= wn
.date
;
2912 wxDateTime dt
= d
.DT();
2914 wxDateTime::wxDateTime_t
2915 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
2916 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2917 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2918 dnum
= dt
.GetDayOfYear();
2920 printf("%s: the day number is %d",
2921 d
.FormatDate().c_str(), dnum
);
2922 if ( dnum
== wn
.dnum
)
2928 printf(" (ERROR: should be %d)", wn
.dnum
);
2931 printf(", week in month is %d", wmon
);
2932 if ( wmon
== wn
.wmon
)
2938 printf(" (ERROR: should be %d)", wn
.wmon
);
2941 printf(" or %d", wmon2
);
2942 if ( wmon2
== wn
.wmon2
)
2948 printf(" (ERROR: should be %d)", wn
.wmon2
);
2951 printf(", week in year is %d", week
);
2952 if ( week
== wn
.week
)
2958 printf(" (ERROR: should be %d)\n", wn
.week
);
2963 // test DST calculations
2964 static void TestTimeDST()
2966 puts("\n*** wxDateTime DST test ***");
2968 printf("DST is%s in effect now.\n\n",
2969 wxDateTime::Now().IsDST() ? "" : " not");
2971 // taken from http://www.energy.ca.gov/daylightsaving.html
2972 static const Date datesDST
[2][2004 - 1900 + 1] =
2975 { 1, wxDateTime::Apr
, 1990 },
2976 { 7, wxDateTime::Apr
, 1991 },
2977 { 5, wxDateTime::Apr
, 1992 },
2978 { 4, wxDateTime::Apr
, 1993 },
2979 { 3, wxDateTime::Apr
, 1994 },
2980 { 2, wxDateTime::Apr
, 1995 },
2981 { 7, wxDateTime::Apr
, 1996 },
2982 { 6, wxDateTime::Apr
, 1997 },
2983 { 5, wxDateTime::Apr
, 1998 },
2984 { 4, wxDateTime::Apr
, 1999 },
2985 { 2, wxDateTime::Apr
, 2000 },
2986 { 1, wxDateTime::Apr
, 2001 },
2987 { 7, wxDateTime::Apr
, 2002 },
2988 { 6, wxDateTime::Apr
, 2003 },
2989 { 4, wxDateTime::Apr
, 2004 },
2992 { 28, wxDateTime::Oct
, 1990 },
2993 { 27, wxDateTime::Oct
, 1991 },
2994 { 25, wxDateTime::Oct
, 1992 },
2995 { 31, wxDateTime::Oct
, 1993 },
2996 { 30, wxDateTime::Oct
, 1994 },
2997 { 29, wxDateTime::Oct
, 1995 },
2998 { 27, wxDateTime::Oct
, 1996 },
2999 { 26, wxDateTime::Oct
, 1997 },
3000 { 25, wxDateTime::Oct
, 1998 },
3001 { 31, wxDateTime::Oct
, 1999 },
3002 { 29, wxDateTime::Oct
, 2000 },
3003 { 28, wxDateTime::Oct
, 2001 },
3004 { 27, wxDateTime::Oct
, 2002 },
3005 { 26, wxDateTime::Oct
, 2003 },
3006 { 31, wxDateTime::Oct
, 2004 },
3011 for ( year
= 1990; year
< 2005; year
++ )
3013 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3014 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3016 printf("DST period in the US for year %d: from %s to %s",
3017 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3019 size_t n
= year
- 1990;
3020 const Date
& dBegin
= datesDST
[0][n
];
3021 const Date
& dEnd
= datesDST
[1][n
];
3023 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3029 printf(" (ERROR: should be %s %d to %s %d)\n",
3030 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3031 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3037 for ( year
= 1990; year
< 2005; year
++ )
3039 printf("DST period in Europe for year %d: from %s to %s\n",
3041 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3042 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3046 // test wxDateTime -> text conversion
3047 static void TestTimeFormat()
3049 puts("\n*** wxDateTime formatting test ***");
3051 // some information may be lost during conversion, so store what kind
3052 // of info should we recover after a round trip
3055 CompareNone
, // don't try comparing
3056 CompareBoth
, // dates and times should be identical
3057 CompareDate
, // dates only
3058 CompareTime
// time only
3063 CompareKind compareKind
;
3065 } formatTestFormats
[] =
3067 { CompareBoth
, "---> %c" },
3068 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3069 { CompareBoth
, "Date is %x, time is %X" },
3070 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3071 { CompareNone
, "The day of year: %j, the week of year: %W" },
3072 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3075 static const Date formatTestDates
[] =
3077 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3078 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3080 // this test can't work for other centuries because it uses two digit
3081 // years in formats, so don't even try it
3082 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3083 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3084 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3088 // an extra test (as it doesn't depend on date, don't do it in the loop)
3089 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3091 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3095 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3096 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3098 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3099 printf("%s", s
.c_str());
3101 // what can we recover?
3102 int kind
= formatTestFormats
[n
].compareKind
;
3106 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3109 // converion failed - should it have?
3110 if ( kind
== CompareNone
)
3113 puts(" (ERROR: conversion back failed)");
3117 // should have parsed the entire string
3118 puts(" (ERROR: conversion back stopped too soon)");
3122 bool equal
= FALSE
; // suppress compilaer warning
3130 equal
= dt
.IsSameDate(dt2
);
3134 equal
= dt
.IsSameTime(dt2
);
3140 printf(" (ERROR: got back '%s' instead of '%s')\n",
3141 dt2
.Format().c_str(), dt
.Format().c_str());
3152 // test text -> wxDateTime conversion
3153 static void TestTimeParse()
3155 puts("\n*** wxDateTime parse test ***");
3157 struct ParseTestData
3164 static const ParseTestData parseTestDates
[] =
3166 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3167 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3170 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3172 const char *format
= parseTestDates
[n
].format
;
3174 printf("%s => ", format
);
3177 if ( dt
.ParseRfc822Date(format
) )
3179 printf("%s ", dt
.Format().c_str());
3181 if ( parseTestDates
[n
].good
)
3183 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3190 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3195 puts("(ERROR: bad format)");
3200 printf("bad format (%s)\n",
3201 parseTestDates
[n
].good
? "ERROR" : "ok");
3206 static void TestDateTimeInteractive()
3208 puts("\n*** interactive wxDateTime tests ***");
3214 printf("Enter a date: ");
3215 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3218 // kill the last '\n'
3219 buf
[strlen(buf
) - 1] = 0;
3222 const char *p
= dt
.ParseDate(buf
);
3225 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3231 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3234 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3235 dt
.Format("%b %d, %Y").c_str(),
3237 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3238 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3239 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3242 puts("\n*** done ***");
3245 static void TestTimeMS()
3247 puts("*** testing millisecond-resolution support in wxDateTime ***");
3249 wxDateTime dt1
= wxDateTime::Now(),
3250 dt2
= wxDateTime::UNow();
3252 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3253 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3254 printf("Dummy loop: ");
3255 for ( int i
= 0; i
< 6000; i
++ )
3257 //for ( int j = 0; j < 10; j++ )
3260 s
.Printf("%g", sqrt(i
));
3269 dt2
= wxDateTime::UNow();
3270 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3272 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3274 puts("\n*** done ***");
3277 static void TestTimeArithmetics()
3279 puts("\n*** testing arithmetic operations on wxDateTime ***");
3281 static const struct ArithmData
3283 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3284 : span(sp
), name(nam
) { }
3288 } testArithmData
[] =
3290 ArithmData(wxDateSpan::Day(), "day"),
3291 ArithmData(wxDateSpan::Week(), "week"),
3292 ArithmData(wxDateSpan::Month(), "month"),
3293 ArithmData(wxDateSpan::Year(), "year"),
3294 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3297 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3299 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3301 wxDateSpan span
= testArithmData
[n
].span
;
3305 const char *name
= testArithmData
[n
].name
;
3306 printf("%s + %s = %s, %s - %s = %s\n",
3307 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3308 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3310 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3311 if ( dt1
- span
== dt
)
3317 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3320 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3321 if ( dt2
+ span
== dt
)
3327 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3330 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3331 if ( dt2
+ 2*span
== dt1
)
3337 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3344 static void TestTimeHolidays()
3346 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3348 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3349 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3350 dtEnd
= dtStart
.GetLastMonthDay();
3352 wxDateTimeArray hol
;
3353 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3355 const wxChar
*format
= "%d-%b-%Y (%a)";
3357 printf("All holidays between %s and %s:\n",
3358 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3360 size_t count
= hol
.GetCount();
3361 for ( size_t n
= 0; n
< count
; n
++ )
3363 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3369 static void TestTimeZoneBug()
3371 puts("\n*** testing for DST/timezone bug ***\n");
3373 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3374 for ( int i
= 0; i
< 31; i
++ )
3376 printf("Date %s: week day %s.\n",
3377 date
.Format(_T("%d-%m-%Y")).c_str(),
3378 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3380 date
+= wxDateSpan::Day();
3388 // test compatibility with the old wxDate/wxTime classes
3389 static void TestTimeCompatibility()
3391 puts("\n*** wxDateTime compatibility test ***");
3393 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3394 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3396 double jdnNow
= wxDateTime::Now().GetJDN();
3397 long jdnMidnight
= (long)(jdnNow
- 0.5);
3398 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3400 jdnMidnight
= wxDate().Set().GetJulianDate();
3401 printf("wxDateTime for today: %s\n",
3402 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3404 int flags
= wxEUROPEAN
;//wxFULL;
3407 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3408 for ( int n
= 0; n
< 7; n
++ )
3410 printf("Previous %s is %s\n",
3411 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3412 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3418 #endif // TEST_DATETIME
3420 // ----------------------------------------------------------------------------
3422 // ----------------------------------------------------------------------------
3426 #include <wx/thread.h>
3428 static size_t gs_counter
= (size_t)-1;
3429 static wxCriticalSection gs_critsect
;
3430 static wxCondition gs_cond
;
3432 class MyJoinableThread
: public wxThread
3435 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3436 { m_n
= n
; Create(); }
3438 // thread execution starts here
3439 virtual ExitCode
Entry();
3445 wxThread::ExitCode
MyJoinableThread::Entry()
3447 unsigned long res
= 1;
3448 for ( size_t n
= 1; n
< m_n
; n
++ )
3452 // it's a loooong calculation :-)
3456 return (ExitCode
)res
;
3459 class MyDetachedThread
: public wxThread
3462 MyDetachedThread(size_t n
, char ch
)
3466 m_cancelled
= FALSE
;
3471 // thread execution starts here
3472 virtual ExitCode
Entry();
3475 virtual void OnExit();
3478 size_t m_n
; // number of characters to write
3479 char m_ch
; // character to write
3481 bool m_cancelled
; // FALSE if we exit normally
3484 wxThread::ExitCode
MyDetachedThread::Entry()
3487 wxCriticalSectionLocker
lock(gs_critsect
);
3488 if ( gs_counter
== (size_t)-1 )
3494 for ( size_t n
= 0; n
< m_n
; n
++ )
3496 if ( TestDestroy() )
3506 wxThread::Sleep(100);
3512 void MyDetachedThread::OnExit()
3514 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3516 wxCriticalSectionLocker
lock(gs_critsect
);
3517 if ( !--gs_counter
&& !m_cancelled
)
3521 void TestDetachedThreads()
3523 puts("\n*** Testing detached threads ***");
3525 static const size_t nThreads
= 3;
3526 MyDetachedThread
*threads
[nThreads
];
3528 for ( n
= 0; n
< nThreads
; n
++ )
3530 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3533 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3534 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3536 for ( n
= 0; n
< nThreads
; n
++ )
3541 // wait until all threads terminate
3547 void TestJoinableThreads()
3549 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3551 // calc 10! in the background
3552 MyJoinableThread
thread(10);
3555 printf("\nThread terminated with exit code %lu.\n",
3556 (unsigned long)thread
.Wait());
3559 void TestThreadSuspend()
3561 puts("\n*** Testing thread suspend/resume functions ***");
3563 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3567 // this is for this demo only, in a real life program we'd use another
3568 // condition variable which would be signaled from wxThread::Entry() to
3569 // tell us that the thread really started running - but here just wait a
3570 // bit and hope that it will be enough (the problem is, of course, that
3571 // the thread might still not run when we call Pause() which will result
3573 wxThread::Sleep(300);
3575 for ( size_t n
= 0; n
< 3; n
++ )
3579 puts("\nThread suspended");
3582 // don't sleep but resume immediately the first time
3583 wxThread::Sleep(300);
3585 puts("Going to resume the thread");
3590 puts("Waiting until it terminates now");
3592 // wait until the thread terminates
3598 void TestThreadDelete()
3600 // As above, using Sleep() is only for testing here - we must use some
3601 // synchronisation object instead to ensure that the thread is still
3602 // running when we delete it - deleting a detached thread which already
3603 // terminated will lead to a crash!
3605 puts("\n*** Testing thread delete function ***");
3607 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3611 puts("\nDeleted a thread which didn't start to run yet.");
3613 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3617 wxThread::Sleep(300);
3621 puts("\nDeleted a running thread.");
3623 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3627 wxThread::Sleep(300);
3633 puts("\nDeleted a sleeping thread.");
3635 MyJoinableThread
thread3(20);
3640 puts("\nDeleted a joinable thread.");
3642 MyJoinableThread
thread4(2);
3645 wxThread::Sleep(300);
3649 puts("\nDeleted a joinable thread which already terminated.");
3654 #endif // TEST_THREADS
3656 // ----------------------------------------------------------------------------
3658 // ----------------------------------------------------------------------------
3662 static void PrintArray(const char* name
, const wxArrayString
& array
)
3664 printf("Dump of the array '%s'\n", name
);
3666 size_t nCount
= array
.GetCount();
3667 for ( size_t n
= 0; n
< nCount
; n
++ )
3669 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
3673 static void PrintArray(const char* name
, const wxArrayInt
& array
)
3675 printf("Dump of the array '%s'\n", name
);
3677 size_t nCount
= array
.GetCount();
3678 for ( size_t n
= 0; n
< nCount
; n
++ )
3680 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
3684 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
3685 const wxString
& second
)
3687 return first
.length() - second
.length();
3690 int wxCMPFUNC_CONV
IntCompare(int *first
,
3693 return *first
- *second
;
3696 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
3699 return *second
- *first
;
3702 static void TestArrayOfInts()
3704 puts("*** Testing wxArrayInt ***\n");
3715 puts("After sort:");
3719 puts("After reverse sort:");
3720 a
.Sort(IntRevCompare
);
3724 #include "wx/dynarray.h"
3726 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
3727 #include "wx/arrimpl.cpp"
3728 WX_DEFINE_OBJARRAY(ArrayBars
);
3730 static void TestArrayOfObjects()
3732 puts("*** Testing wxObjArray ***\n");
3736 Bar
bar("second bar");
3738 printf("Initially: %u objects in the array, %u objects total.\n",
3739 bars
.GetCount(), Bar::GetNumber());
3741 bars
.Add(new Bar("first bar"));
3744 printf("Now: %u objects in the array, %u objects total.\n",
3745 bars
.GetCount(), Bar::GetNumber());
3749 printf("After Empty(): %u objects in the array, %u objects total.\n",
3750 bars
.GetCount(), Bar::GetNumber());
3753 printf("Finally: no more objects in the array, %u objects total.\n",
3757 #endif // TEST_ARRAYS
3759 // ----------------------------------------------------------------------------
3761 // ----------------------------------------------------------------------------
3765 #include "wx/timer.h"
3766 #include "wx/tokenzr.h"
3768 static void TestStringConstruction()
3770 puts("*** Testing wxString constructores ***");
3772 #define TEST_CTOR(args, res) \
3775 printf("wxString%s = %s ", #args, s.c_str()); \
3782 printf("(ERROR: should be %s)\n", res); \
3786 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
3787 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
3788 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
3789 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
3791 static const wxChar
*s
= _T("?really!");
3792 const wxChar
*start
= wxStrchr(s
, _T('r'));
3793 const wxChar
*end
= wxStrchr(s
, _T('!'));
3794 TEST_CTOR((start
, end
), _T("really"));
3799 static void TestString()
3809 for (int i
= 0; i
< 1000000; ++i
)
3813 c
= "! How'ya doin'?";
3816 c
= "Hello world! What's up?";
3821 printf ("TestString elapsed time: %ld\n", sw
.Time());
3824 static void TestPChar()
3832 for (int i
= 0; i
< 1000000; ++i
)
3834 strcpy (a
, "Hello");
3835 strcpy (b
, " world");
3836 strcpy (c
, "! How'ya doin'?");
3839 strcpy (c
, "Hello world! What's up?");
3840 if (strcmp (c
, a
) == 0)
3844 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
3847 static void TestStringSub()
3849 wxString
s("Hello, world!");
3851 puts("*** Testing wxString substring extraction ***");
3853 printf("String = '%s'\n", s
.c_str());
3854 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
3855 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
3856 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
3857 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
3858 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
3859 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
3861 static const wxChar
*prefixes
[] =
3865 _T("Hello, world!"),
3866 _T("Hello, world!!!"),
3872 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
3874 wxString prefix
= prefixes
[n
], rest
;
3875 bool rc
= s
.StartsWith(prefix
, &rest
);
3876 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
3879 printf(" (the rest is '%s')\n", rest
.c_str());
3890 static void TestStringFormat()
3892 puts("*** Testing wxString formatting ***");
3895 s
.Printf("%03d", 18);
3897 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
3898 printf("Number 18: %s\n", s
.c_str());
3903 // returns "not found" for npos, value for all others
3904 static wxString
PosToString(size_t res
)
3906 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
3907 : wxString::Format(_T("%u"), res
);
3911 static void TestStringFind()
3913 puts("*** Testing wxString find() functions ***");
3915 static const wxChar
*strToFind
= _T("ell");
3916 static const struct StringFindTest
3920 result
; // of searching "ell" in str
3923 { _T("Well, hello world"), 0, 1 },
3924 { _T("Well, hello world"), 6, 7 },
3925 { _T("Well, hello world"), 9, wxString::npos
},
3928 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
3930 const StringFindTest
& ft
= findTestData
[n
];
3931 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
3933 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
3934 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
3936 size_t resTrue
= ft
.result
;
3937 if ( res
== resTrue
)
3943 printf(_T("(ERROR: should be %s)\n"),
3944 PosToString(resTrue
).c_str());
3951 static void TestStringTokenizer()
3953 puts("*** Testing wxStringTokenizer ***");
3955 static const wxChar
*modeNames
[] =
3959 _T("return all empty"),
3964 static const struct StringTokenizerTest
3966 const wxChar
*str
; // string to tokenize
3967 const wxChar
*delims
; // delimiters to use
3968 size_t count
; // count of token
3969 wxStringTokenizerMode mode
; // how should we tokenize it
3970 } tokenizerTestData
[] =
3972 { _T(""), _T(" "), 0 },
3973 { _T("Hello, world"), _T(" "), 2 },
3974 { _T("Hello, world "), _T(" "), 2 },
3975 { _T("Hello, world"), _T(","), 2 },
3976 { _T("Hello, world!"), _T(",!"), 2 },
3977 { _T("Hello,, world!"), _T(",!"), 3 },
3978 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
3979 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
3980 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
3981 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
3982 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
3983 { _T("01/02/99"), _T("/-"), 3 },
3984 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
3987 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
3989 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
3990 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
3992 size_t count
= tkz
.CountTokens();
3993 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
3994 MakePrintable(tt
.str
).c_str(),
3996 MakePrintable(tt
.delims
).c_str(),
3997 modeNames
[tkz
.GetMode()]);
3998 if ( count
== tt
.count
)
4004 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4009 // if we emulate strtok(), check that we do it correctly
4010 wxChar
*buf
, *s
= NULL
, *last
;
4012 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4014 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4015 wxStrcpy(buf
, tt
.str
);
4017 s
= wxStrtok(buf
, tt
.delims
, &last
);
4024 // now show the tokens themselves
4026 while ( tkz
.HasMoreTokens() )
4028 wxString token
= tkz
.GetNextToken();
4030 printf(_T("\ttoken %u: '%s'"),
4032 MakePrintable(token
).c_str());
4042 printf(" (ERROR: should be %s)\n", s
);
4045 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4049 // nothing to compare with
4054 if ( count2
!= count
)
4056 puts(_T("\tERROR: token count mismatch"));
4065 static void TestStringReplace()
4067 puts("*** Testing wxString::replace ***");
4069 static const struct StringReplaceTestData
4071 const wxChar
*original
; // original test string
4072 size_t start
, len
; // the part to replace
4073 const wxChar
*replacement
; // the replacement string
4074 const wxChar
*result
; // and the expected result
4075 } stringReplaceTestData
[] =
4077 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4078 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4079 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4080 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4081 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4084 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4086 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4088 wxString original
= data
.original
;
4089 original
.replace(data
.start
, data
.len
, data
.replacement
);
4091 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4092 data
.original
, data
.start
, data
.len
, data
.replacement
,
4095 if ( original
== data
.result
)
4101 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4108 #endif // TEST_STRINGS
4110 // ----------------------------------------------------------------------------
4112 // ----------------------------------------------------------------------------
4114 int main(int argc
, char **argv
)
4116 if ( !wxInitialize() )
4118 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4122 puts("Sleeping for 3 seconds... z-z-z-z-z...");
4124 #endif // TEST_USLEEP
4127 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4129 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4130 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4132 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4133 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4134 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
4135 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
4137 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4138 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4143 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4145 parser
.AddOption("project_name", "", "full path to project file",
4146 wxCMD_LINE_VAL_STRING
,
4147 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4149 switch ( parser
.Parse() )
4152 wxLogMessage("Help was given, terminating.");
4156 ShowCmdLine(parser
);
4160 wxLogMessage("Syntax error detected, aborting.");
4163 #endif // TEST_CMDLINE
4174 TestStringConstruction();
4177 TestStringTokenizer();
4178 TestStringReplace();
4180 #endif // TEST_STRINGS
4193 puts("*** Initially:");
4195 PrintArray("a1", a1
);
4197 wxArrayString
a2(a1
);
4198 PrintArray("a2", a2
);
4200 wxSortedArrayString
a3(a1
);
4201 PrintArray("a3", a3
);
4203 puts("*** After deleting a string from a1");
4206 PrintArray("a1", a1
);
4207 PrintArray("a2", a2
);
4208 PrintArray("a3", a3
);
4210 puts("*** After reassigning a1 to a2 and a3");
4212 PrintArray("a2", a2
);
4213 PrintArray("a3", a3
);
4215 puts("*** After sorting a1");
4217 PrintArray("a1", a1
);
4219 puts("*** After sorting a1 in reverse order");
4221 PrintArray("a1", a1
);
4223 puts("*** After sorting a1 by the string length");
4224 a1
.Sort(StringLenCompare
);
4225 PrintArray("a1", a1
);
4227 TestArrayOfObjects();
4230 #endif // TEST_ARRAYS
4236 #ifdef TEST_DLLLOADER
4238 #endif // TEST_DLLLOADER
4242 #endif // TEST_ENVIRON
4246 #endif // TEST_EXECUTE
4248 #ifdef TEST_FILECONF
4250 #endif // TEST_FILECONF
4258 for ( size_t n
= 0; n
< 8000; n
++ )
4260 s
<< (char)('A' + (n
% 26));
4264 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4266 // this one shouldn't be truncated
4269 // but this one will because log functions use fixed size buffer
4270 // (note that it doesn't need '\n' at the end neither - will be added
4272 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4284 #ifdef TEST_FILENAME
4285 TestFileNameSplit();
4288 TestFileNameConstruction();
4290 TestFileNameComparison();
4291 TestFileNameOperations();
4293 #endif // TEST_FILENAME
4296 int nCPUs
= wxThread::GetCPUCount();
4297 printf("This system has %d CPUs\n", nCPUs
);
4299 wxThread::SetConcurrency(nCPUs
);
4301 if ( argc
> 1 && argv
[1][0] == 't' )
4302 wxLog::AddTraceMask("thread");
4305 TestDetachedThreads();
4307 TestJoinableThreads();
4309 TestThreadSuspend();
4313 #endif // TEST_THREADS
4315 #ifdef TEST_LONGLONG
4316 // seed pseudo random generator
4317 srand((unsigned)time(NULL
));
4325 TestMultiplication();
4328 TestLongLongConversion();
4329 TestBitOperations();
4331 TestLongLongComparison();
4332 #endif // TEST_LONGLONG
4339 wxLog::AddTraceMask(_T("mime"));
4347 TestMimeAssociate();
4350 #ifdef TEST_INFO_FUNCTIONS
4353 #endif // TEST_INFO_FUNCTIONS
4355 #ifdef TEST_PATHLIST
4357 #endif // TEST_PATHLIST
4359 #ifdef TEST_REGISTRY
4362 TestRegistryAssociation();
4363 #endif // TEST_REGISTRY
4371 #endif // TEST_SOCKETS
4374 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4375 if ( TestFtpConnect() )
4386 TestFtpInteractive();
4388 //else: connecting to the FTP server failed
4398 #endif // TEST_STREAMS
4402 #endif // TEST_TIMER
4404 #ifdef TEST_DATETIME
4417 TestTimeArithmetics();
4425 TestDateTimeInteractive();
4426 #endif // TEST_DATETIME
4432 #endif // TEST_VCARD
4436 #endif // TEST_WCHAR
4440 TestZipStreamRead();
4441 TestZipFileSystem();
4446 TestZlibStreamWrite();
4447 TestZlibStreamRead();