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
52 //#define TEST_LONGLONG
54 //#define TEST_INFO_FUNCTIONS
55 //#define TEST_REGISTRY
56 //#define TEST_SOCKETS
58 //#define TEST_STRINGS
59 //#define TEST_THREADS
61 //#define TEST_VCARD -- don't enable this (VZ)
66 // ----------------------------------------------------------------------------
67 // test class for container objects
68 // ----------------------------------------------------------------------------
70 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
72 class Bar
// Foo is already taken in the hash test
75 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
78 static size_t GetNumber() { return ms_bars
; }
80 const char *GetName() const { return m_name
; }
85 static size_t ms_bars
;
88 size_t Bar::ms_bars
= 0;
90 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
92 // ============================================================================
94 // ============================================================================
96 // ----------------------------------------------------------------------------
98 // ----------------------------------------------------------------------------
100 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
102 // replace TABs with \t and CRs with \n
103 static wxString
MakePrintable(const wxChar
*s
)
106 (void)str
.Replace(_T("\t"), _T("\\t"));
107 (void)str
.Replace(_T("\n"), _T("\\n"));
108 (void)str
.Replace(_T("\r"), _T("\\r"));
113 #endif // MakePrintable() is used
115 // ----------------------------------------------------------------------------
117 // ----------------------------------------------------------------------------
121 #include <wx/cmdline.h>
122 #include <wx/datetime.h>
124 static void ShowCmdLine(const wxCmdLineParser
& parser
)
126 wxString s
= "Input files: ";
128 size_t count
= parser
.GetParamCount();
129 for ( size_t param
= 0; param
< count
; param
++ )
131 s
<< parser
.GetParam(param
) << ' ';
135 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
136 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
141 if ( parser
.Found("o", &strVal
) )
142 s
<< "Output file:\t" << strVal
<< '\n';
143 if ( parser
.Found("i", &strVal
) )
144 s
<< "Input dir:\t" << strVal
<< '\n';
145 if ( parser
.Found("s", &lVal
) )
146 s
<< "Size:\t" << lVal
<< '\n';
147 if ( parser
.Found("d", &dt
) )
148 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
149 if ( parser
.Found("project_name", &strVal
) )
150 s
<< "Project:\t" << strVal
<< '\n';
155 #endif // TEST_CMDLINE
157 // ----------------------------------------------------------------------------
159 // ----------------------------------------------------------------------------
165 static void TestDirEnumHelper(wxDir
& dir
,
166 int flags
= wxDIR_DEFAULT
,
167 const wxString
& filespec
= wxEmptyString
)
171 if ( !dir
.IsOpened() )
174 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
177 printf("\t%s\n", filename
.c_str());
179 cont
= dir
.GetNext(&filename
);
185 static void TestDirEnum()
187 wxDir
dir(wxGetCwd());
189 puts("Enumerating everything in current directory:");
190 TestDirEnumHelper(dir
);
192 puts("Enumerating really everything in current directory:");
193 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
195 puts("Enumerating object files in current directory:");
196 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
198 puts("Enumerating directories in current directory:");
199 TestDirEnumHelper(dir
, wxDIR_DIRS
);
201 puts("Enumerating files in current directory:");
202 TestDirEnumHelper(dir
, wxDIR_FILES
);
204 puts("Enumerating files including hidden in current directory:");
205 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
209 #elif defined(__WXMSW__)
212 #error "don't know where the root directory is"
215 puts("Enumerating everything in root directory:");
216 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
218 puts("Enumerating directories in root directory:");
219 TestDirEnumHelper(dir
, wxDIR_DIRS
);
221 puts("Enumerating files in root directory:");
222 TestDirEnumHelper(dir
, wxDIR_FILES
);
224 puts("Enumerating files including hidden in root directory:");
225 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
227 puts("Enumerating files in non existing directory:");
228 wxDir
dirNo("nosuchdir");
229 TestDirEnumHelper(dirNo
);
234 // ----------------------------------------------------------------------------
236 // ----------------------------------------------------------------------------
238 #ifdef TEST_DLLLOADER
240 #include <wx/dynlib.h>
242 static void TestDllLoad()
244 #if defined(__WXMSW__)
245 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
246 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
247 #elif defined(__UNIX__)
248 // weird: using just libc.so does *not* work!
249 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
250 static const wxChar
*FUNC_NAME
= _T("strlen");
252 #error "don't know how to test wxDllLoader on this platform"
255 puts("*** testing wxDllLoader ***\n");
257 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
260 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
264 typedef int (*strlenType
)(char *);
265 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
268 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
269 FUNC_NAME
, LIB_NAME
);
273 if ( pfnStrlen("foo") != 3 )
275 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
283 wxDllLoader::UnloadLibrary(dllHandle
);
287 #endif // TEST_DLLLOADER
289 // ----------------------------------------------------------------------------
291 // ----------------------------------------------------------------------------
295 #include <wx/utils.h>
297 static wxString
MyGetEnv(const wxString
& var
)
300 if ( !wxGetEnv(var
, &val
) )
303 val
= wxString(_T('\'')) + val
+ _T('\'');
308 static void TestEnvironment()
310 const wxChar
*var
= _T("wxTestVar");
312 puts("*** testing environment access functions ***");
314 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
315 wxSetEnv(var
, _T("value for wxTestVar"));
316 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
317 wxSetEnv(var
, _T("another value"));
318 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
320 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
321 printf("PATH = %s\n", MyGetEnv(_T("PATH")));
324 #endif // TEST_ENVIRON
326 // ----------------------------------------------------------------------------
328 // ----------------------------------------------------------------------------
332 #include <wx/utils.h>
334 static void TestExecute()
336 puts("*** testing wxExecute ***");
339 #define COMMAND "cat -n ../../Makefile" // "echo hi"
340 #define SHELL_COMMAND "echo hi from shell"
341 #define REDIRECT_COMMAND COMMAND // "date"
342 #elif defined(__WXMSW__)
343 #define COMMAND "command.com -c 'echo hi'"
344 #define SHELL_COMMAND "echo hi"
345 #define REDIRECT_COMMAND COMMAND
347 #error "no command to exec"
350 printf("Testing wxShell: ");
352 if ( wxShell(SHELL_COMMAND
) )
357 printf("Testing wxExecute: ");
359 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
364 #if 0 // no, it doesn't work (yet?)
365 printf("Testing async wxExecute: ");
367 if ( wxExecute(COMMAND
) != 0 )
368 puts("Ok (command launched).");
373 printf("Testing wxExecute with redirection:\n");
374 wxArrayString output
;
375 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
381 size_t count
= output
.GetCount();
382 for ( size_t n
= 0; n
< count
; n
++ )
384 printf("\t%s\n", output
[n
].c_str());
391 #endif // TEST_EXECUTE
393 // ----------------------------------------------------------------------------
395 // ----------------------------------------------------------------------------
400 #include <wx/ffile.h>
401 #include <wx/textfile.h>
403 static void TestFileRead()
405 puts("*** wxFile read test ***");
407 wxFile
file(_T("testdata.fc"));
408 if ( file
.IsOpened() )
410 printf("File length: %lu\n", file
.Length());
412 puts("File dump:\n----------");
414 static const off_t len
= 1024;
418 off_t nRead
= file
.Read(buf
, len
);
419 if ( nRead
== wxInvalidOffset
)
421 printf("Failed to read the file.");
425 fwrite(buf
, nRead
, 1, stdout
);
435 printf("ERROR: can't open test file.\n");
441 static void TestTextFileRead()
443 puts("*** wxTextFile read test ***");
445 wxTextFile
file(_T("testdata.fc"));
448 printf("Number of lines: %u\n", file
.GetLineCount());
449 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
453 puts("\nDumping the entire file:");
454 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
456 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
458 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
460 puts("\nAnd now backwards:");
461 for ( s
= file
.GetLastLine();
462 file
.GetCurrentLine() != 0;
463 s
= file
.GetPrevLine() )
465 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
467 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
471 printf("ERROR: can't open '%s'\n", file
.GetName());
477 static void TestFileCopy()
479 puts("*** Testing wxCopyFile ***");
481 static const wxChar
*filename1
= _T("testdata.fc");
482 static const wxChar
*filename2
= _T("test2");
483 if ( !wxCopyFile(filename1
, filename2
) )
485 puts("ERROR: failed to copy file");
489 wxFFile
f1(filename1
, "rb"),
492 if ( !f1
.IsOpened() || !f2
.IsOpened() )
494 puts("ERROR: failed to open file(s)");
499 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
501 puts("ERROR: failed to read file(s)");
505 if ( (s1
.length() != s2
.length()) ||
506 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
508 puts("ERROR: copy error!");
512 puts("File was copied ok.");
518 if ( !wxRemoveFile(filename2
) )
520 puts("ERROR: failed to remove the file");
528 // ----------------------------------------------------------------------------
530 // ----------------------------------------------------------------------------
534 #include <wx/confbase.h>
535 #include <wx/fileconf.h>
537 static const struct FileConfTestData
539 const wxChar
*name
; // value name
540 const wxChar
*value
; // the value from the file
543 { _T("value1"), _T("one") },
544 { _T("value2"), _T("two") },
545 { _T("novalue"), _T("default") },
548 static void TestFileConfRead()
550 puts("*** testing wxFileConfig loading/reading ***");
552 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
553 _T("testdata.fc"), wxEmptyString
,
554 wxCONFIG_USE_RELATIVE_PATH
);
556 // test simple reading
557 puts("\nReading config file:");
558 wxString
defValue(_T("default")), value
;
559 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
561 const FileConfTestData
& data
= fcTestData
[n
];
562 value
= fileconf
.Read(data
.name
, defValue
);
563 printf("\t%s = %s ", data
.name
, value
.c_str());
564 if ( value
== data
.value
)
570 printf("(ERROR: should be %s)\n", data
.value
);
574 // test enumerating the entries
575 puts("\nEnumerating all root entries:");
578 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
581 printf("\t%s = %s\n",
583 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
585 cont
= fileconf
.GetNextEntry(name
, dummy
);
589 #endif // TEST_FILECONF
591 // ----------------------------------------------------------------------------
593 // ----------------------------------------------------------------------------
597 #include <wx/filename.h>
599 static struct FileNameInfo
601 const wxChar
*fullname
;
607 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
608 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
609 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
610 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
611 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
612 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
613 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
614 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
617 static void TestFileNameConstruction()
619 puts("*** testing wxFileName construction ***");
621 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
623 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
625 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
626 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
628 puts("ERROR (couldn't be normalized)");
632 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
639 static void TestFileNameSplit()
641 puts("*** testing wxFileName splitting ***");
643 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
645 const FileNameInfo
&fni
= filenames
[n
];
646 wxString path
, name
, ext
;
647 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
649 printf("%s -> path = '%s', name = '%s', ext = '%s'",
650 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
651 if ( path
!= fni
.path
)
652 printf(" (ERROR: path = '%s')", fni
.path
);
653 if ( name
!= fni
.name
)
654 printf(" (ERROR: name = '%s')", fni
.name
);
655 if ( ext
!= fni
.ext
)
656 printf(" (ERROR: ext = '%s')", fni
.ext
);
663 static void TestFileNameComparison()
668 static void TestFileNameOperations()
673 static void TestFileNameCwd()
678 #endif // TEST_FILENAME
680 // ----------------------------------------------------------------------------
682 // ----------------------------------------------------------------------------
690 Foo(int n_
) { n
= n_
; count
++; }
698 size_t Foo::count
= 0;
700 WX_DECLARE_LIST(Foo
, wxListFoos
);
701 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
703 #include <wx/listimpl.cpp>
705 WX_DEFINE_LIST(wxListFoos
);
707 static void TestHash()
709 puts("*** Testing wxHashTable ***\n");
713 hash
.DeleteContents(TRUE
);
715 printf("Hash created: %u foos in hash, %u foos totally\n",
716 hash
.GetCount(), Foo::count
);
718 static const int hashTestData
[] =
720 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
724 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
726 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
729 printf("Hash filled: %u foos in hash, %u foos totally\n",
730 hash
.GetCount(), Foo::count
);
732 puts("Hash access test:");
733 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
735 printf("\tGetting element with key %d, value %d: ",
737 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
740 printf("ERROR, not found.\n");
744 printf("%d (%s)\n", foo
->n
,
745 (size_t)foo
->n
== n
? "ok" : "ERROR");
749 printf("\nTrying to get an element not in hash: ");
751 if ( hash
.Get(1234) || hash
.Get(1, 0) )
753 puts("ERROR: found!");
757 puts("ok (not found)");
761 printf("Hash destroyed: %u foos left\n", Foo::count
);
766 // ----------------------------------------------------------------------------
768 // ----------------------------------------------------------------------------
774 WX_DECLARE_LIST(Bar
, wxListBars
);
775 #include <wx/listimpl.cpp>
776 WX_DEFINE_LIST(wxListBars
);
778 static void TestListCtor()
780 puts("*** Testing wxList construction ***\n");
784 list1
.Append(new Bar(_T("first")));
785 list1
.Append(new Bar(_T("second")));
787 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
788 list1
.GetCount(), Bar::GetNumber());
793 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
794 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
796 list1
.DeleteContents(TRUE
);
799 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
804 // ----------------------------------------------------------------------------
806 // ----------------------------------------------------------------------------
810 #include <wx/mimetype.h>
812 static wxMimeTypesManager g_mimeManager
;
814 static void TestMimeEnum()
816 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
818 wxArrayString mimetypes
;
820 size_t count
= g_mimeManager
.EnumAllFileTypes(mimetypes
);
822 printf("*** All %u known filetypes: ***\n", count
);
827 for ( size_t n
= 0; n
< count
; n
++ )
829 wxFileType
*filetype
= g_mimeManager
.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());
855 static void TestMimeOverride()
857 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
859 wxString mailcap
= _T("/tmp/mailcap"),
860 mimetypes
= _T("/tmp/mime.types");
862 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
864 g_mimeManager
.ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
865 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
867 g_mimeManager
.ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
870 static void TestMimeFilename()
872 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
874 static const wxChar
*filenames
[] =
881 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
883 const wxString fname
= filenames
[n
];
884 wxString ext
= fname
.AfterLast(_T('.'));
885 wxFileType
*ft
= g_mimeManager
.GetFileTypeFromExtension(ext
);
888 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
893 if ( !ft
->GetDescription(&desc
) )
894 desc
= _T("<no description>");
897 if ( !ft
->GetOpenCommand(&cmd
,
898 wxFileType::MessageParameters(fname
, _T(""))) )
899 cmd
= _T("<no command available>");
901 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
902 fname
.c_str(), desc
.c_str(), cmd
.c_str());
909 static void TestMimeAssociate()
911 wxPuts(_T("*** Testing creation of filetype association ***\n"));
913 wxFileTypeInfo
ftInfo(
914 _T("application/x-xyz"),
915 _T("xyzview '%s'"), // open cmd
917 _T("XYZ File") // description
918 _T(".xyz"), // extensions
919 NULL
// end of extensions
921 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
923 wxFileType
*ft
= g_mimeManager
.Associate(ftInfo
);
926 wxPuts(_T("ERROR: failed to create association!"));
930 // TODO: read it back
937 // ----------------------------------------------------------------------------
938 // misc information functions
939 // ----------------------------------------------------------------------------
941 #ifdef TEST_INFO_FUNCTIONS
943 #include <wx/utils.h>
945 static void TestOsInfo()
947 puts("*** Testing OS info functions ***\n");
950 wxGetOsVersion(&major
, &minor
);
951 printf("Running under: %s, version %d.%d\n",
952 wxGetOsDescription().c_str(), major
, minor
);
954 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
956 printf("Host name is %s (%s).\n",
957 wxGetHostName().c_str(), wxGetFullHostName().c_str());
962 static void TestUserInfo()
964 puts("*** Testing user info functions ***\n");
966 printf("User id is:\t%s\n", wxGetUserId().c_str());
967 printf("User name is:\t%s\n", wxGetUserName().c_str());
968 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
969 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
974 #endif // TEST_INFO_FUNCTIONS
976 // ----------------------------------------------------------------------------
978 // ----------------------------------------------------------------------------
982 #include <wx/longlong.h>
983 #include <wx/timer.h>
985 // make a 64 bit number from 4 16 bit ones
986 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
988 // get a random 64 bit number
989 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
991 #if wxUSE_LONGLONG_WX
992 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
993 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
994 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
995 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
996 #endif // wxUSE_LONGLONG_WX
998 static void TestSpeed()
1000 static const long max
= 100000000;
1007 for ( n
= 0; n
< max
; n
++ )
1012 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1015 #if wxUSE_LONGLONG_NATIVE
1020 for ( n
= 0; n
< max
; n
++ )
1025 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1027 #endif // wxUSE_LONGLONG_NATIVE
1033 for ( n
= 0; n
< max
; n
++ )
1038 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1042 static void TestLongLongConversion()
1044 puts("*** Testing wxLongLong conversions ***\n");
1048 for ( size_t n
= 0; n
< 100000; n
++ )
1052 #if wxUSE_LONGLONG_NATIVE
1053 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1055 wxASSERT_MSG( a
== b
, "conversions failure" );
1057 puts("Can't do it without native long long type, test skipped.");
1060 #endif // wxUSE_LONGLONG_NATIVE
1062 if ( !(nTested
% 1000) )
1074 static void TestMultiplication()
1076 puts("*** Testing wxLongLong multiplication ***\n");
1080 for ( size_t n
= 0; n
< 100000; n
++ )
1085 #if wxUSE_LONGLONG_NATIVE
1086 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1087 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1089 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1090 #else // !wxUSE_LONGLONG_NATIVE
1091 puts("Can't do it without native long long type, test skipped.");
1094 #endif // wxUSE_LONGLONG_NATIVE
1096 if ( !(nTested
% 1000) )
1108 static void TestDivision()
1110 puts("*** Testing wxLongLong division ***\n");
1114 for ( size_t n
= 0; n
< 100000; n
++ )
1116 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1117 // multiplication will not overflow)
1118 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1120 // get a random long (not wxLongLong for now) to divide it with
1125 #if wxUSE_LONGLONG_NATIVE
1126 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1128 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1129 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1130 #else // !wxUSE_LONGLONG_NATIVE
1131 // verify the result
1132 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1133 #endif // wxUSE_LONGLONG_NATIVE
1135 if ( !(nTested
% 1000) )
1147 static void TestAddition()
1149 puts("*** Testing wxLongLong addition ***\n");
1153 for ( size_t n
= 0; n
< 100000; n
++ )
1159 #if wxUSE_LONGLONG_NATIVE
1160 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1161 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1162 "addition failure" );
1163 #else // !wxUSE_LONGLONG_NATIVE
1164 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1165 #endif // wxUSE_LONGLONG_NATIVE
1167 if ( !(nTested
% 1000) )
1179 static void TestBitOperations()
1181 puts("*** Testing wxLongLong bit operation ***\n");
1185 for ( size_t n
= 0; n
< 100000; n
++ )
1189 #if wxUSE_LONGLONG_NATIVE
1190 for ( size_t n
= 0; n
< 33; n
++ )
1193 #else // !wxUSE_LONGLONG_NATIVE
1194 puts("Can't do it without native long long type, test skipped.");
1197 #endif // wxUSE_LONGLONG_NATIVE
1199 if ( !(nTested
% 1000) )
1211 static void TestLongLongComparison()
1213 puts("*** Testing wxLongLong comparison ***\n");
1215 static const long testLongs
[] =
1226 static const long ls
[2] =
1232 wxLongLongWx lls
[2];
1236 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1240 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1242 res
= lls
[m
] > testLongs
[n
];
1243 printf("0x%lx > 0x%lx is %s (%s)\n",
1244 ls
[m
], testLongs
[n
], res
? "true" : "false",
1245 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1247 res
= lls
[m
] < testLongs
[n
];
1248 printf("0x%lx < 0x%lx is %s (%s)\n",
1249 ls
[m
], testLongs
[n
], res
? "true" : "false",
1250 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1252 res
= lls
[m
] == testLongs
[n
];
1253 printf("0x%lx == 0x%lx is %s (%s)\n",
1254 ls
[m
], testLongs
[n
], res
? "true" : "false",
1255 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1263 #endif // TEST_LONGLONG
1265 // ----------------------------------------------------------------------------
1267 // ----------------------------------------------------------------------------
1269 // this is for MSW only
1271 #undef TEST_REGISTRY
1274 #ifdef TEST_REGISTRY
1276 #include <wx/msw/registry.h>
1278 // I chose this one because I liked its name, but it probably only exists under
1280 static const wxChar
*TESTKEY
=
1281 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1283 static void TestRegistryRead()
1285 puts("*** testing registry reading ***");
1287 wxRegKey
key(TESTKEY
);
1288 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1291 puts("ERROR: test key can't be opened, aborting test.");
1296 size_t nSubKeys
, nValues
;
1297 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1299 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1302 printf("Enumerating values:\n");
1306 bool cont
= key
.GetFirstValue(value
, dummy
);
1309 printf("Value '%s': type ", value
.c_str());
1310 switch ( key
.GetValueType(value
) )
1312 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1313 case wxRegKey::Type_String
: printf("SZ"); break;
1314 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1315 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1316 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1317 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1318 default: printf("other (unknown)"); break;
1321 printf(", value = ");
1322 if ( key
.IsNumericValue(value
) )
1325 key
.QueryValue(value
, &val
);
1331 key
.QueryValue(value
, val
);
1332 printf("'%s'", val
.c_str());
1334 key
.QueryRawValue(value
, val
);
1335 printf(" (raw value '%s')", val
.c_str());
1340 cont
= key
.GetNextValue(value
, dummy
);
1344 static void TestRegistryAssociation()
1347 The second call to deleteself genertaes an error message, with a
1348 messagebox saying .flo is crucial to system operation, while the .ddf
1349 call also fails, but with no error message
1354 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1356 key
= "ddxf_auto_file" ;
1357 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1359 key
= "ddxf_auto_file" ;
1360 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1363 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1365 key
= "program \"%1\"" ;
1367 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1369 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1371 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1373 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1377 #endif // TEST_REGISTRY
1379 // ----------------------------------------------------------------------------
1381 // ----------------------------------------------------------------------------
1385 #include <wx/socket.h>
1386 #include <wx/protocol/protocol.h>
1387 #include <wx/protocol/http.h>
1389 static void TestSocketServer()
1391 puts("*** Testing wxSocketServer ***\n");
1393 static const int PORT
= 3000;
1398 wxSocketServer
*server
= new wxSocketServer(addr
);
1399 if ( !server
->Ok() )
1401 puts("ERROR: failed to bind");
1408 printf("Server: waiting for connection on port %d...\n", PORT
);
1410 wxSocketBase
*socket
= server
->Accept();
1413 puts("ERROR: wxSocketServer::Accept() failed.");
1417 puts("Server: got a client.");
1419 server
->SetTimeout(60); // 1 min
1421 while ( socket
->IsConnected() )
1427 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1429 // don't log error if the client just close the connection
1430 if ( socket
->IsConnected() )
1432 puts("ERROR: in wxSocket::Read.");
1452 printf("Server: got '%s'.\n", s
.c_str());
1453 if ( s
== _T("bye") )
1460 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1461 socket
->Write("\r\n", 2);
1462 printf("Server: wrote '%s'.\n", s
.c_str());
1465 puts("Server: lost a client.");
1470 // same as "delete server" but is consistent with GUI programs
1474 static void TestSocketClient()
1476 puts("*** Testing wxSocketClient ***\n");
1478 static const char *hostname
= "www.wxwindows.org";
1481 addr
.Hostname(hostname
);
1484 printf("--- Attempting to connect to %s:80...\n", hostname
);
1486 wxSocketClient client
;
1487 if ( !client
.Connect(addr
) )
1489 printf("ERROR: failed to connect to %s\n", hostname
);
1493 printf("--- Connected to %s:%u...\n",
1494 addr
.Hostname().c_str(), addr
.Service());
1498 // could use simply "GET" here I suppose
1500 wxString::Format("GET http://%s/\r\n", hostname
);
1501 client
.Write(cmdGet
, cmdGet
.length());
1502 printf("--- Sent command '%s' to the server\n",
1503 MakePrintable(cmdGet
).c_str());
1504 client
.Read(buf
, WXSIZEOF(buf
));
1505 printf("--- Server replied:\n%s", buf
);
1509 #endif // TEST_SOCKETS
1511 // ----------------------------------------------------------------------------
1513 // ----------------------------------------------------------------------------
1517 #include <wx/protocol/ftp.h>
1521 #define FTP_ANONYMOUS
1523 #ifdef FTP_ANONYMOUS
1524 static const char *directory
= "/pub";
1525 static const char *filename
= "welcome.msg";
1527 static const char *directory
= "/etc";
1528 static const char *filename
= "issue";
1531 static bool TestFtpConnect()
1533 puts("*** Testing FTP connect ***");
1535 #ifdef FTP_ANONYMOUS
1536 static const char *hostname
= "ftp.wxwindows.org";
1538 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1539 #else // !FTP_ANONYMOUS
1540 static const char *hostname
= "localhost";
1543 fgets(user
, WXSIZEOF(user
), stdin
);
1544 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
1548 printf("Password for %s: ", password
);
1549 fgets(password
, WXSIZEOF(password
), stdin
);
1550 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
1551 ftp
.SetPassword(password
);
1553 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
1554 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
1556 if ( !ftp
.Connect(hostname
) )
1558 printf("ERROR: failed to connect to %s\n", hostname
);
1564 printf("--- Connected to %s, current directory is '%s'\n",
1565 hostname
, ftp
.Pwd().c_str());
1571 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
1572 static void TestFtpWuFtpd()
1575 static const char *hostname
= "ftp.eudora.com";
1576 if ( !ftp
.Connect(hostname
) )
1578 printf("ERROR: failed to connect to %s\n", hostname
);
1582 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
1583 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1586 printf("ERROR: couldn't get input stream for %s\n", filename
);
1590 size_t size
= in
->StreamSize();
1591 printf("Reading file %s (%u bytes)...", filename
, size
);
1593 char *data
= new char[size
];
1594 if ( !in
->Read(data
, size
) )
1596 puts("ERROR: read error");
1600 printf("Successfully retrieved the file.\n");
1609 static void TestFtpList()
1611 puts("*** Testing wxFTP file listing ***\n");
1614 if ( !ftp
.ChDir(directory
) )
1616 printf("ERROR: failed to cd to %s\n", directory
);
1619 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
1621 // test NLIST and LIST
1622 wxArrayString files
;
1623 if ( !ftp
.GetFilesList(files
) )
1625 puts("ERROR: failed to get NLIST of files");
1629 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
1630 size_t count
= files
.GetCount();
1631 for ( size_t n
= 0; n
< count
; n
++ )
1633 printf("\t%s\n", files
[n
].c_str());
1635 puts("End of the file list");
1638 if ( !ftp
.GetDirList(files
) )
1640 puts("ERROR: failed to get LIST of files");
1644 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
1645 size_t count
= files
.GetCount();
1646 for ( size_t n
= 0; n
< count
; n
++ )
1648 printf("\t%s\n", files
[n
].c_str());
1650 puts("End of the file list");
1653 if ( !ftp
.ChDir(_T("..")) )
1655 puts("ERROR: failed to cd to ..");
1658 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
1661 static void TestFtpDownload()
1663 puts("*** Testing wxFTP download ***\n");
1666 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1669 printf("ERROR: couldn't get input stream for %s\n", filename
);
1673 size_t size
= in
->StreamSize();
1674 printf("Reading file %s (%u bytes)...", filename
, size
);
1677 char *data
= new char[size
];
1678 if ( !in
->Read(data
, size
) )
1680 puts("ERROR: read error");
1684 printf("\nContents of %s:\n%s\n", filename
, data
);
1692 static void TestFtpFileSize()
1694 puts("*** Testing FTP SIZE command ***");
1696 if ( !ftp
.ChDir(directory
) )
1698 printf("ERROR: failed to cd to %s\n", directory
);
1701 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
1703 if ( ftp
.FileExists(filename
) )
1705 int size
= ftp
.GetFileSize(filename
);
1707 printf("ERROR: couldn't get size of '%s'\n", filename
);
1709 printf("Size of '%s' is %d bytes.\n", filename
, size
);
1713 printf("ERROR: '%s' doesn't exist\n", filename
);
1717 static void TestFtpMisc()
1719 puts("*** Testing miscellaneous wxFTP functions ***");
1721 if ( ftp
.SendCommand("STAT") != '2' )
1723 puts("ERROR: STAT failed");
1727 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
1730 if ( ftp
.SendCommand("HELP SITE") != '2' )
1732 puts("ERROR: HELP SITE failed");
1736 printf("The list of site-specific commands:\n\n%s\n",
1737 ftp
.GetLastResult().c_str());
1741 static void TestFtpInteractive()
1743 puts("\n*** Interactive wxFTP test ***");
1749 printf("Enter FTP command: ");
1750 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
1753 // kill the last '\n'
1754 buf
[strlen(buf
) - 1] = 0;
1756 // special handling of LIST and NLST as they require data connection
1757 wxString
start(buf
, 4);
1759 if ( start
== "LIST" || start
== "NLST" )
1762 if ( strlen(buf
) > 4 )
1765 wxArrayString files
;
1766 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
1768 printf("ERROR: failed to get %s of files\n", start
.c_str());
1772 printf("--- %s of '%s' under '%s':\n",
1773 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
1774 size_t count
= files
.GetCount();
1775 for ( size_t n
= 0; n
< count
; n
++ )
1777 printf("\t%s\n", files
[n
].c_str());
1779 puts("--- End of the file list");
1784 char ch
= ftp
.SendCommand(buf
);
1785 printf("Command %s", ch
? "succeeded" : "failed");
1788 printf(" (return code %c)", ch
);
1791 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
1795 puts("\n*** done ***");
1798 static void TestFtpUpload()
1800 puts("*** Testing wxFTP uploading ***\n");
1803 static const char *file1
= "test1";
1804 static const char *file2
= "test2";
1805 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
1808 printf("--- Uploading to %s ---\n", file1
);
1809 out
->Write("First hello", 11);
1813 // send a command to check the remote file
1814 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
1816 printf("ERROR: STAT %s failed\n", file1
);
1820 printf("STAT %s returned:\n\n%s\n",
1821 file1
, ftp
.GetLastResult().c_str());
1824 out
= ftp
.GetOutputStream(file2
);
1827 printf("--- Uploading to %s ---\n", file1
);
1828 out
->Write("Second hello", 12);
1835 // ----------------------------------------------------------------------------
1837 // ----------------------------------------------------------------------------
1841 #include <wx/wfstream.h>
1842 #include <wx/mstream.h>
1844 static void TestFileStream()
1846 puts("*** Testing wxFileInputStream ***");
1848 static const wxChar
*filename
= _T("testdata.fs");
1850 wxFileOutputStream
fsOut(filename
);
1851 fsOut
.Write("foo", 3);
1854 wxFileInputStream
fsIn(filename
);
1855 printf("File stream size: %u\n", fsIn
.GetSize());
1856 while ( !fsIn
.Eof() )
1858 putchar(fsIn
.GetC());
1861 if ( !wxRemoveFile(filename
) )
1863 printf("ERROR: failed to remove the file '%s'.\n", filename
);
1866 puts("\n*** wxFileInputStream test done ***");
1869 static void TestMemoryStream()
1871 puts("*** Testing wxMemoryInputStream ***");
1874 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
1876 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
1877 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
1878 while ( !memInpStream
.Eof() )
1880 putchar(memInpStream
.GetC());
1883 puts("\n*** wxMemoryInputStream test done ***");
1886 #endif // TEST_STREAMS
1888 // ----------------------------------------------------------------------------
1890 // ----------------------------------------------------------------------------
1894 #include <wx/timer.h>
1895 #include <wx/utils.h>
1897 static void TestStopWatch()
1899 puts("*** Testing wxStopWatch ***\n");
1902 printf("Sleeping 3 seconds...");
1904 printf("\telapsed time: %ldms\n", sw
.Time());
1907 printf("Sleeping 2 more seconds...");
1909 printf("\telapsed time: %ldms\n", sw
.Time());
1912 printf("And 3 more seconds...");
1914 printf("\telapsed time: %ldms\n", sw
.Time());
1917 puts("\nChecking for 'backwards clock' bug...");
1918 for ( size_t n
= 0; n
< 70; n
++ )
1922 for ( size_t m
= 0; m
< 100000; m
++ )
1924 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
1926 puts("\ntime is negative - ERROR!");
1936 #endif // TEST_TIMER
1938 // ----------------------------------------------------------------------------
1940 // ----------------------------------------------------------------------------
1944 #include <wx/vcard.h>
1946 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
1949 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
1953 wxString(_T('\t'), level
).c_str(),
1954 vcObj
->GetName().c_str());
1957 switch ( vcObj
->GetType() )
1959 case wxVCardObject::String
:
1960 case wxVCardObject::UString
:
1963 vcObj
->GetValue(&val
);
1964 value
<< _T('"') << val
<< _T('"');
1968 case wxVCardObject::Int
:
1971 vcObj
->GetValue(&i
);
1972 value
.Printf(_T("%u"), i
);
1976 case wxVCardObject::Long
:
1979 vcObj
->GetValue(&l
);
1980 value
.Printf(_T("%lu"), l
);
1984 case wxVCardObject::None
:
1987 case wxVCardObject::Object
:
1988 value
= _T("<node>");
1992 value
= _T("<unknown value type>");
1996 printf(" = %s", value
.c_str());
1999 DumpVObject(level
+ 1, *vcObj
);
2002 vcObj
= vcard
.GetNextProp(&cookie
);
2006 static void DumpVCardAddresses(const wxVCard
& vcard
)
2008 puts("\nShowing all addresses from vCard:\n");
2012 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2016 int flags
= addr
->GetFlags();
2017 if ( flags
& wxVCardAddress::Domestic
)
2019 flagsStr
<< _T("domestic ");
2021 if ( flags
& wxVCardAddress::Intl
)
2023 flagsStr
<< _T("international ");
2025 if ( flags
& wxVCardAddress::Postal
)
2027 flagsStr
<< _T("postal ");
2029 if ( flags
& wxVCardAddress::Parcel
)
2031 flagsStr
<< _T("parcel ");
2033 if ( flags
& wxVCardAddress::Home
)
2035 flagsStr
<< _T("home ");
2037 if ( flags
& wxVCardAddress::Work
)
2039 flagsStr
<< _T("work ");
2042 printf("Address %u:\n"
2044 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2047 addr
->GetPostOffice().c_str(),
2048 addr
->GetExtAddress().c_str(),
2049 addr
->GetStreet().c_str(),
2050 addr
->GetLocality().c_str(),
2051 addr
->GetRegion().c_str(),
2052 addr
->GetPostalCode().c_str(),
2053 addr
->GetCountry().c_str()
2057 addr
= vcard
.GetNextAddress(&cookie
);
2061 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2063 puts("\nShowing all phone numbers from vCard:\n");
2067 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2071 int flags
= phone
->GetFlags();
2072 if ( flags
& wxVCardPhoneNumber::Voice
)
2074 flagsStr
<< _T("voice ");
2076 if ( flags
& wxVCardPhoneNumber::Fax
)
2078 flagsStr
<< _T("fax ");
2080 if ( flags
& wxVCardPhoneNumber::Cellular
)
2082 flagsStr
<< _T("cellular ");
2084 if ( flags
& wxVCardPhoneNumber::Modem
)
2086 flagsStr
<< _T("modem ");
2088 if ( flags
& wxVCardPhoneNumber::Home
)
2090 flagsStr
<< _T("home ");
2092 if ( flags
& wxVCardPhoneNumber::Work
)
2094 flagsStr
<< _T("work ");
2097 printf("Phone number %u:\n"
2102 phone
->GetNumber().c_str()
2106 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2110 static void TestVCardRead()
2112 puts("*** Testing wxVCard reading ***\n");
2114 wxVCard
vcard(_T("vcard.vcf"));
2115 if ( !vcard
.IsOk() )
2117 puts("ERROR: couldn't load vCard.");
2121 // read individual vCard properties
2122 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2126 vcObj
->GetValue(&value
);
2131 value
= _T("<none>");
2134 printf("Full name retrieved directly: %s\n", value
.c_str());
2137 if ( !vcard
.GetFullName(&value
) )
2139 value
= _T("<none>");
2142 printf("Full name from wxVCard API: %s\n", value
.c_str());
2144 // now show how to deal with multiply occuring properties
2145 DumpVCardAddresses(vcard
);
2146 DumpVCardPhoneNumbers(vcard
);
2148 // and finally show all
2149 puts("\nNow dumping the entire vCard:\n"
2150 "-----------------------------\n");
2152 DumpVObject(0, vcard
);
2156 static void TestVCardWrite()
2158 puts("*** Testing wxVCard writing ***\n");
2161 if ( !vcard
.IsOk() )
2163 puts("ERROR: couldn't create vCard.");
2168 vcard
.SetName("Zeitlin", "Vadim");
2169 vcard
.SetFullName("Vadim Zeitlin");
2170 vcard
.SetOrganization("wxWindows", "R&D");
2172 // just dump the vCard back
2173 puts("Entire vCard follows:\n");
2174 puts(vcard
.Write());
2178 #endif // TEST_VCARD
2180 // ----------------------------------------------------------------------------
2181 // wide char (Unicode) support
2182 // ----------------------------------------------------------------------------
2186 #include <wx/strconv.h>
2187 #include <wx/fontenc.h>
2188 #include <wx/encconv.h>
2189 #include <wx/buffer.h>
2191 static void TestUtf8()
2193 puts("*** Testing UTF8 support ***\n");
2195 static const char textInUtf8
[] =
2197 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2198 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2199 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2200 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2201 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2202 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2203 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2208 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2210 puts("ERROR: UTF-8 decoding failed.");
2214 // using wxEncodingConverter
2216 wxEncodingConverter ec
;
2217 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2218 ec
.Convert(wbuf
, buf
);
2219 #else // using wxCSConv
2220 wxCSConv
conv(_T("koi8-r"));
2221 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2223 puts("ERROR: conversion to KOI8-R failed.");
2228 printf("The resulting string (in koi8-r): %s\n", buf
);
2232 #endif // TEST_WCHAR
2234 // ----------------------------------------------------------------------------
2236 // ----------------------------------------------------------------------------
2240 #include "wx/zipstrm.h"
2242 static void TestZipStreamRead()
2244 puts("*** Testing ZIP reading ***\n");
2246 wxZipInputStream
istr(_T("idx.zip"), _T("IDX.txt"));
2247 printf("Archive size: %u\n", istr
.GetSize());
2249 puts("Dumping the file:");
2250 while ( !istr
.Eof() )
2252 putchar(istr
.GetC());
2256 puts("\n----- done ------");
2261 // ----------------------------------------------------------------------------
2263 // ----------------------------------------------------------------------------
2267 #include <wx/zstream.h>
2268 #include <wx/wfstream.h>
2270 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2271 static const char *TEST_DATA
= "hello and hello again";
2273 static void TestZlibStreamWrite()
2275 puts("*** Testing Zlib stream reading ***\n");
2277 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2278 wxZlibOutputStream
ostr(fileOutStream
, 0);
2279 printf("Compressing the test string... ");
2280 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2283 puts("(ERROR: failed)");
2290 puts("\n----- done ------");
2293 static void TestZlibStreamRead()
2295 puts("*** Testing Zlib stream reading ***\n");
2297 wxFileInputStream
fileInStream(FILENAME_GZ
);
2298 wxZlibInputStream
istr(fileInStream
);
2299 printf("Archive size: %u\n", istr
.GetSize());
2301 puts("Dumping the file:");
2302 while ( !istr
.Eof() )
2304 putchar(istr
.GetC());
2308 puts("\n----- done ------");
2313 // ----------------------------------------------------------------------------
2315 // ----------------------------------------------------------------------------
2317 #ifdef TEST_DATETIME
2319 #include <wx/date.h>
2321 #include <wx/datetime.h>
2326 wxDateTime::wxDateTime_t day
;
2327 wxDateTime::Month month
;
2329 wxDateTime::wxDateTime_t hour
, min
, sec
;
2331 wxDateTime::WeekDay wday
;
2332 time_t gmticks
, ticks
;
2334 void Init(const wxDateTime::Tm
& tm
)
2343 gmticks
= ticks
= -1;
2346 wxDateTime
DT() const
2347 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2349 bool SameDay(const wxDateTime::Tm
& tm
) const
2351 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2354 wxString
Format() const
2357 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2359 wxDateTime::GetMonthName(month
).c_str(),
2361 abs(wxDateTime::ConvertYearToBC(year
)),
2362 year
> 0 ? "AD" : "BC");
2366 wxString
FormatDate() const
2369 s
.Printf("%02d-%s-%4d%s",
2371 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2372 abs(wxDateTime::ConvertYearToBC(year
)),
2373 year
> 0 ? "AD" : "BC");
2378 static const Date testDates
[] =
2380 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2381 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2382 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2383 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2384 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2385 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2386 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2387 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2388 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2389 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2390 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2391 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2392 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2393 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2394 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2397 // this test miscellaneous static wxDateTime functions
2398 static void TestTimeStatic()
2400 puts("\n*** wxDateTime static methods test ***");
2402 // some info about the current date
2403 int year
= wxDateTime::GetCurrentYear();
2404 printf("Current year %d is %sa leap one and has %d days.\n",
2406 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2407 wxDateTime::GetNumberOfDays(year
));
2409 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2410 printf("Current month is '%s' ('%s') and it has %d days\n",
2411 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2412 wxDateTime::GetMonthName(month
).c_str(),
2413 wxDateTime::GetNumberOfDays(month
));
2416 static const size_t nYears
= 5;
2417 static const size_t years
[2][nYears
] =
2419 // first line: the years to test
2420 { 1990, 1976, 2000, 2030, 1984, },
2422 // second line: TRUE if leap, FALSE otherwise
2423 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2426 for ( size_t n
= 0; n
< nYears
; n
++ )
2428 int year
= years
[0][n
];
2429 bool should
= years
[1][n
] != 0,
2430 is
= wxDateTime::IsLeapYear(year
);
2432 printf("Year %d is %sa leap year (%s)\n",
2435 should
== is
? "ok" : "ERROR");
2437 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2441 // test constructing wxDateTime objects
2442 static void TestTimeSet()
2444 puts("\n*** wxDateTime construction test ***");
2446 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2448 const Date
& d1
= testDates
[n
];
2449 wxDateTime dt
= d1
.DT();
2452 d2
.Init(dt
.GetTm());
2454 wxString s1
= d1
.Format(),
2457 printf("Date: %s == %s (%s)\n",
2458 s1
.c_str(), s2
.c_str(),
2459 s1
== s2
? "ok" : "ERROR");
2463 // test time zones stuff
2464 static void TestTimeZones()
2466 puts("\n*** wxDateTime timezone test ***");
2468 wxDateTime now
= wxDateTime::Now();
2470 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2471 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2472 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2473 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2474 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2475 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2477 wxDateTime::Tm tm
= now
.GetTm();
2478 if ( wxDateTime(tm
) != now
)
2480 printf("ERROR: got %s instead of %s\n",
2481 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2485 // test some minimal support for the dates outside the standard range
2486 static void TestTimeRange()
2488 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2490 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
2492 printf("Unix epoch:\t%s\n",
2493 wxDateTime(2440587.5).Format(fmt
).c_str());
2494 printf("Feb 29, 0: \t%s\n",
2495 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
2496 printf("JDN 0: \t%s\n",
2497 wxDateTime(0.0).Format(fmt
).c_str());
2498 printf("Jan 1, 1AD:\t%s\n",
2499 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
2500 printf("May 29, 2099:\t%s\n",
2501 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
2504 static void TestTimeTicks()
2506 puts("\n*** wxDateTime ticks test ***");
2508 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2510 const Date
& d
= testDates
[n
];
2511 if ( d
.ticks
== -1 )
2514 wxDateTime dt
= d
.DT();
2515 long ticks
= (dt
.GetValue() / 1000).ToLong();
2516 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2517 if ( ticks
== d
.ticks
)
2523 printf(" (ERROR: should be %ld, delta = %ld)\n",
2524 d
.ticks
, ticks
- d
.ticks
);
2527 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
2528 ticks
= (dt
.GetValue() / 1000).ToLong();
2529 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2530 if ( ticks
== d
.gmticks
)
2536 printf(" (ERROR: should be %ld, delta = %ld)\n",
2537 d
.gmticks
, ticks
- d
.gmticks
);
2544 // test conversions to JDN &c
2545 static void TestTimeJDN()
2547 puts("\n*** wxDateTime to JDN test ***");
2549 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2551 const Date
& d
= testDates
[n
];
2552 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2553 double jdn
= dt
.GetJulianDayNumber();
2555 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
2562 printf(" (ERROR: should be %f, delta = %f)\n",
2563 d
.jdn
, jdn
- d
.jdn
);
2568 // test week days computation
2569 static void TestTimeWDays()
2571 puts("\n*** wxDateTime weekday test ***");
2573 // test GetWeekDay()
2575 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2577 const Date
& d
= testDates
[n
];
2578 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2580 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
2583 wxDateTime::GetWeekDayName(wday
).c_str());
2584 if ( wday
== d
.wday
)
2590 printf(" (ERROR: should be %s)\n",
2591 wxDateTime::GetWeekDayName(d
.wday
).c_str());
2597 // test SetToWeekDay()
2598 struct WeekDateTestData
2600 Date date
; // the real date (precomputed)
2601 int nWeek
; // its week index in the month
2602 wxDateTime::WeekDay wday
; // the weekday
2603 wxDateTime::Month month
; // the month
2604 int year
; // and the year
2606 wxString
Format() const
2609 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
2611 case 1: which
= "first"; break;
2612 case 2: which
= "second"; break;
2613 case 3: which
= "third"; break;
2614 case 4: which
= "fourth"; break;
2615 case 5: which
= "fifth"; break;
2617 case -1: which
= "last"; break;
2622 which
+= " from end";
2625 s
.Printf("The %s %s of %s in %d",
2627 wxDateTime::GetWeekDayName(wday
).c_str(),
2628 wxDateTime::GetMonthName(month
).c_str(),
2635 // the array data was generated by the following python program
2637 from DateTime import *
2638 from whrandom import *
2639 from string import *
2641 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2642 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2644 week = DateTimeDelta(7)
2647 year = randint(1900, 2100)
2648 month = randint(1, 12)
2649 day = randint(1, 28)
2650 dt = DateTime(year, month, day)
2651 wday = dt.day_of_week
2653 countFromEnd = choice([-1, 1])
2656 while dt.month is month:
2657 dt = dt - countFromEnd * week
2658 weekNum = weekNum + countFromEnd
2660 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
2662 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
2663 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
2666 static const WeekDateTestData weekDatesTestData
[] =
2668 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
2669 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
2670 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
2671 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
2672 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
2673 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
2674 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
2675 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
2676 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
2677 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
2678 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
2679 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
2680 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
2681 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
2682 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
2683 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
2684 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
2685 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
2686 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
2687 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
2690 static const char *fmt
= "%d-%b-%Y";
2693 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
2695 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
2697 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
2699 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
2701 const Date
& d
= wd
.date
;
2702 if ( d
.SameDay(dt
.GetTm()) )
2708 dt
.Set(d
.day
, d
.month
, d
.year
);
2710 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
2715 // test the computation of (ISO) week numbers
2716 static void TestTimeWNumber()
2718 puts("\n*** wxDateTime week number test ***");
2720 struct WeekNumberTestData
2722 Date date
; // the date
2723 wxDateTime::wxDateTime_t week
; // the week number in the year
2724 wxDateTime::wxDateTime_t wmon
; // the week number in the month
2725 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
2726 wxDateTime::wxDateTime_t dnum
; // day number in the year
2729 // data generated with the following python script:
2731 from DateTime import *
2732 from whrandom import *
2733 from string import *
2735 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2736 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2738 def GetMonthWeek(dt):
2739 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
2740 if weekNumMonth < 0:
2741 weekNumMonth = weekNumMonth + 53
2744 def GetLastSundayBefore(dt):
2745 if dt.iso_week[2] == 7:
2748 return dt - DateTimeDelta(dt.iso_week[2])
2751 year = randint(1900, 2100)
2752 month = randint(1, 12)
2753 day = randint(1, 28)
2754 dt = DateTime(year, month, day)
2755 dayNum = dt.day_of_year
2756 weekNum = dt.iso_week[1]
2757 weekNumMonth = GetMonthWeek(dt)
2760 dtSunday = GetLastSundayBefore(dt)
2762 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
2763 weekNumMonth2 = weekNumMonth2 + 1
2764 dtSunday = dtSunday - DateTimeDelta(7)
2766 data = { 'day': rjust(`day`, 2), \
2767 'month': monthNames[month - 1], \
2769 'weekNum': rjust(`weekNum`, 2), \
2770 'weekNumMonth': weekNumMonth, \
2771 'weekNumMonth2': weekNumMonth2, \
2772 'dayNum': rjust(`dayNum`, 3) }
2774 print " { { %(day)s, "\
2775 "wxDateTime::%(month)s, "\
2778 "%(weekNumMonth)s, "\
2779 "%(weekNumMonth2)s, "\
2780 "%(dayNum)s }," % data
2783 static const WeekNumberTestData weekNumberTestDates
[] =
2785 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
2786 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
2787 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
2788 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
2789 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
2790 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
2791 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
2792 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
2793 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
2794 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
2795 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
2796 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
2797 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
2798 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
2799 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
2800 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
2801 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
2802 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
2803 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
2804 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
2807 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
2809 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
2810 const Date
& d
= wn
.date
;
2812 wxDateTime dt
= d
.DT();
2814 wxDateTime::wxDateTime_t
2815 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
2816 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2817 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2818 dnum
= dt
.GetDayOfYear();
2820 printf("%s: the day number is %d",
2821 d
.FormatDate().c_str(), dnum
);
2822 if ( dnum
== wn
.dnum
)
2828 printf(" (ERROR: should be %d)", wn
.dnum
);
2831 printf(", week in month is %d", wmon
);
2832 if ( wmon
== wn
.wmon
)
2838 printf(" (ERROR: should be %d)", wn
.wmon
);
2841 printf(" or %d", wmon2
);
2842 if ( wmon2
== wn
.wmon2
)
2848 printf(" (ERROR: should be %d)", wn
.wmon2
);
2851 printf(", week in year is %d", week
);
2852 if ( week
== wn
.week
)
2858 printf(" (ERROR: should be %d)\n", wn
.week
);
2863 // test DST calculations
2864 static void TestTimeDST()
2866 puts("\n*** wxDateTime DST test ***");
2868 printf("DST is%s in effect now.\n\n",
2869 wxDateTime::Now().IsDST() ? "" : " not");
2871 // taken from http://www.energy.ca.gov/daylightsaving.html
2872 static const Date datesDST
[2][2004 - 1900 + 1] =
2875 { 1, wxDateTime::Apr
, 1990 },
2876 { 7, wxDateTime::Apr
, 1991 },
2877 { 5, wxDateTime::Apr
, 1992 },
2878 { 4, wxDateTime::Apr
, 1993 },
2879 { 3, wxDateTime::Apr
, 1994 },
2880 { 2, wxDateTime::Apr
, 1995 },
2881 { 7, wxDateTime::Apr
, 1996 },
2882 { 6, wxDateTime::Apr
, 1997 },
2883 { 5, wxDateTime::Apr
, 1998 },
2884 { 4, wxDateTime::Apr
, 1999 },
2885 { 2, wxDateTime::Apr
, 2000 },
2886 { 1, wxDateTime::Apr
, 2001 },
2887 { 7, wxDateTime::Apr
, 2002 },
2888 { 6, wxDateTime::Apr
, 2003 },
2889 { 4, wxDateTime::Apr
, 2004 },
2892 { 28, wxDateTime::Oct
, 1990 },
2893 { 27, wxDateTime::Oct
, 1991 },
2894 { 25, wxDateTime::Oct
, 1992 },
2895 { 31, wxDateTime::Oct
, 1993 },
2896 { 30, wxDateTime::Oct
, 1994 },
2897 { 29, wxDateTime::Oct
, 1995 },
2898 { 27, wxDateTime::Oct
, 1996 },
2899 { 26, wxDateTime::Oct
, 1997 },
2900 { 25, wxDateTime::Oct
, 1998 },
2901 { 31, wxDateTime::Oct
, 1999 },
2902 { 29, wxDateTime::Oct
, 2000 },
2903 { 28, wxDateTime::Oct
, 2001 },
2904 { 27, wxDateTime::Oct
, 2002 },
2905 { 26, wxDateTime::Oct
, 2003 },
2906 { 31, wxDateTime::Oct
, 2004 },
2911 for ( year
= 1990; year
< 2005; year
++ )
2913 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
2914 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
2916 printf("DST period in the US for year %d: from %s to %s",
2917 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
2919 size_t n
= year
- 1990;
2920 const Date
& dBegin
= datesDST
[0][n
];
2921 const Date
& dEnd
= datesDST
[1][n
];
2923 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
2929 printf(" (ERROR: should be %s %d to %s %d)\n",
2930 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
2931 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
2937 for ( year
= 1990; year
< 2005; year
++ )
2939 printf("DST period in Europe for year %d: from %s to %s\n",
2941 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
2942 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
2946 // test wxDateTime -> text conversion
2947 static void TestTimeFormat()
2949 puts("\n*** wxDateTime formatting test ***");
2951 // some information may be lost during conversion, so store what kind
2952 // of info should we recover after a round trip
2955 CompareNone
, // don't try comparing
2956 CompareBoth
, // dates and times should be identical
2957 CompareDate
, // dates only
2958 CompareTime
// time only
2963 CompareKind compareKind
;
2965 } formatTestFormats
[] =
2967 { CompareBoth
, "---> %c" },
2968 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
2969 { CompareBoth
, "Date is %x, time is %X" },
2970 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
2971 { CompareNone
, "The day of year: %j, the week of year: %W" },
2972 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
2975 static const Date formatTestDates
[] =
2977 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
2978 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
2980 // this test can't work for other centuries because it uses two digit
2981 // years in formats, so don't even try it
2982 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
2983 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
2984 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
2988 // an extra test (as it doesn't depend on date, don't do it in the loop)
2989 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
2991 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
2995 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
2996 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
2998 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
2999 printf("%s", s
.c_str());
3001 // what can we recover?
3002 int kind
= formatTestFormats
[n
].compareKind
;
3006 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3009 // converion failed - should it have?
3010 if ( kind
== CompareNone
)
3013 puts(" (ERROR: conversion back failed)");
3017 // should have parsed the entire string
3018 puts(" (ERROR: conversion back stopped too soon)");
3022 bool equal
= FALSE
; // suppress compilaer warning
3030 equal
= dt
.IsSameDate(dt2
);
3034 equal
= dt
.IsSameTime(dt2
);
3040 printf(" (ERROR: got back '%s' instead of '%s')\n",
3041 dt2
.Format().c_str(), dt
.Format().c_str());
3052 // test text -> wxDateTime conversion
3053 static void TestTimeParse()
3055 puts("\n*** wxDateTime parse test ***");
3057 struct ParseTestData
3064 static const ParseTestData parseTestDates
[] =
3066 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3067 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3070 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3072 const char *format
= parseTestDates
[n
].format
;
3074 printf("%s => ", format
);
3077 if ( dt
.ParseRfc822Date(format
) )
3079 printf("%s ", dt
.Format().c_str());
3081 if ( parseTestDates
[n
].good
)
3083 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3090 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3095 puts("(ERROR: bad format)");
3100 printf("bad format (%s)\n",
3101 parseTestDates
[n
].good
? "ERROR" : "ok");
3106 static void TestDateTimeInteractive()
3108 puts("\n*** interactive wxDateTime tests ***");
3114 printf("Enter a date: ");
3115 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3118 // kill the last '\n'
3119 buf
[strlen(buf
) - 1] = 0;
3122 const char *p
= dt
.ParseDate(buf
);
3125 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3131 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3134 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3135 dt
.Format("%b %d, %Y").c_str(),
3137 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3138 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3139 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3142 puts("\n*** done ***");
3145 static void TestTimeMS()
3147 puts("*** testing millisecond-resolution support in wxDateTime ***");
3149 wxDateTime dt1
= wxDateTime::Now(),
3150 dt2
= wxDateTime::UNow();
3152 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3153 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3154 printf("Dummy loop: ");
3155 for ( int i
= 0; i
< 6000; i
++ )
3157 //for ( int j = 0; j < 10; j++ )
3160 s
.Printf("%g", sqrt(i
));
3169 dt2
= wxDateTime::UNow();
3170 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3172 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3174 puts("\n*** done ***");
3177 static void TestTimeArithmetics()
3179 puts("\n*** testing arithmetic operations on wxDateTime ***");
3181 static const struct ArithmData
3183 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3184 : span(sp
), name(nam
) { }
3188 } testArithmData
[] =
3190 ArithmData(wxDateSpan::Day(), "day"),
3191 ArithmData(wxDateSpan::Week(), "week"),
3192 ArithmData(wxDateSpan::Month(), "month"),
3193 ArithmData(wxDateSpan::Year(), "year"),
3194 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3197 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3199 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3201 wxDateSpan span
= testArithmData
[n
].span
;
3205 const char *name
= testArithmData
[n
].name
;
3206 printf("%s + %s = %s, %s - %s = %s\n",
3207 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3208 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3210 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3211 if ( dt1
- span
== dt
)
3217 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3220 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3221 if ( dt2
+ span
== dt
)
3227 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3230 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3231 if ( dt2
+ 2*span
== dt1
)
3237 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3244 static void TestTimeHolidays()
3246 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3248 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3249 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3250 dtEnd
= dtStart
.GetLastMonthDay();
3252 wxDateTimeArray hol
;
3253 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3255 const wxChar
*format
= "%d-%b-%Y (%a)";
3257 printf("All holidays between %s and %s:\n",
3258 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3260 size_t count
= hol
.GetCount();
3261 for ( size_t n
= 0; n
< count
; n
++ )
3263 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3269 static void TestTimeZoneBug()
3271 puts("\n*** testing for DST/timezone bug ***\n");
3273 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3274 for ( int i
= 0; i
< 31; i
++ )
3276 printf("Date %s: week day %s.\n",
3277 date
.Format(_T("%d-%m-%Y")).c_str(),
3278 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3280 date
+= wxDateSpan::Day();
3288 // test compatibility with the old wxDate/wxTime classes
3289 static void TestTimeCompatibility()
3291 puts("\n*** wxDateTime compatibility test ***");
3293 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3294 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3296 double jdnNow
= wxDateTime::Now().GetJDN();
3297 long jdnMidnight
= (long)(jdnNow
- 0.5);
3298 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3300 jdnMidnight
= wxDate().Set().GetJulianDate();
3301 printf("wxDateTime for today: %s\n",
3302 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3304 int flags
= wxEUROPEAN
;//wxFULL;
3307 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3308 for ( int n
= 0; n
< 7; n
++ )
3310 printf("Previous %s is %s\n",
3311 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3312 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3318 #endif // TEST_DATETIME
3320 // ----------------------------------------------------------------------------
3322 // ----------------------------------------------------------------------------
3326 #include <wx/thread.h>
3328 static size_t gs_counter
= (size_t)-1;
3329 static wxCriticalSection gs_critsect
;
3330 static wxCondition gs_cond
;
3332 class MyJoinableThread
: public wxThread
3335 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3336 { m_n
= n
; Create(); }
3338 // thread execution starts here
3339 virtual ExitCode
Entry();
3345 wxThread::ExitCode
MyJoinableThread::Entry()
3347 unsigned long res
= 1;
3348 for ( size_t n
= 1; n
< m_n
; n
++ )
3352 // it's a loooong calculation :-)
3356 return (ExitCode
)res
;
3359 class MyDetachedThread
: public wxThread
3362 MyDetachedThread(size_t n
, char ch
)
3366 m_cancelled
= FALSE
;
3371 // thread execution starts here
3372 virtual ExitCode
Entry();
3375 virtual void OnExit();
3378 size_t m_n
; // number of characters to write
3379 char m_ch
; // character to write
3381 bool m_cancelled
; // FALSE if we exit normally
3384 wxThread::ExitCode
MyDetachedThread::Entry()
3387 wxCriticalSectionLocker
lock(gs_critsect
);
3388 if ( gs_counter
== (size_t)-1 )
3394 for ( size_t n
= 0; n
< m_n
; n
++ )
3396 if ( TestDestroy() )
3406 wxThread::Sleep(100);
3412 void MyDetachedThread::OnExit()
3414 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3416 wxCriticalSectionLocker
lock(gs_critsect
);
3417 if ( !--gs_counter
&& !m_cancelled
)
3421 void TestDetachedThreads()
3423 puts("\n*** Testing detached threads ***");
3425 static const size_t nThreads
= 3;
3426 MyDetachedThread
*threads
[nThreads
];
3428 for ( n
= 0; n
< nThreads
; n
++ )
3430 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3433 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3434 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3436 for ( n
= 0; n
< nThreads
; n
++ )
3441 // wait until all threads terminate
3447 void TestJoinableThreads()
3449 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3451 // calc 10! in the background
3452 MyJoinableThread
thread(10);
3455 printf("\nThread terminated with exit code %lu.\n",
3456 (unsigned long)thread
.Wait());
3459 void TestThreadSuspend()
3461 puts("\n*** Testing thread suspend/resume functions ***");
3463 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3467 // this is for this demo only, in a real life program we'd use another
3468 // condition variable which would be signaled from wxThread::Entry() to
3469 // tell us that the thread really started running - but here just wait a
3470 // bit and hope that it will be enough (the problem is, of course, that
3471 // the thread might still not run when we call Pause() which will result
3473 wxThread::Sleep(300);
3475 for ( size_t n
= 0; n
< 3; n
++ )
3479 puts("\nThread suspended");
3482 // don't sleep but resume immediately the first time
3483 wxThread::Sleep(300);
3485 puts("Going to resume the thread");
3490 puts("Waiting until it terminates now");
3492 // wait until the thread terminates
3498 void TestThreadDelete()
3500 // As above, using Sleep() is only for testing here - we must use some
3501 // synchronisation object instead to ensure that the thread is still
3502 // running when we delete it - deleting a detached thread which already
3503 // terminated will lead to a crash!
3505 puts("\n*** Testing thread delete function ***");
3507 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3511 puts("\nDeleted a thread which didn't start to run yet.");
3513 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3517 wxThread::Sleep(300);
3521 puts("\nDeleted a running thread.");
3523 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3527 wxThread::Sleep(300);
3533 puts("\nDeleted a sleeping thread.");
3535 MyJoinableThread
thread3(20);
3540 puts("\nDeleted a joinable thread.");
3542 MyJoinableThread
thread4(2);
3545 wxThread::Sleep(300);
3549 puts("\nDeleted a joinable thread which already terminated.");
3554 #endif // TEST_THREADS
3556 // ----------------------------------------------------------------------------
3558 // ----------------------------------------------------------------------------
3562 static void PrintArray(const char* name
, const wxArrayString
& array
)
3564 printf("Dump of the array '%s'\n", name
);
3566 size_t nCount
= array
.GetCount();
3567 for ( size_t n
= 0; n
< nCount
; n
++ )
3569 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
3573 static void PrintArray(const char* name
, const wxArrayInt
& array
)
3575 printf("Dump of the array '%s'\n", name
);
3577 size_t nCount
= array
.GetCount();
3578 for ( size_t n
= 0; n
< nCount
; n
++ )
3580 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
3584 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
3585 const wxString
& second
)
3587 return first
.length() - second
.length();
3590 int wxCMPFUNC_CONV
IntCompare(int *first
,
3593 return *first
- *second
;
3596 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
3599 return *second
- *first
;
3602 static void TestArrayOfInts()
3604 puts("*** Testing wxArrayInt ***\n");
3615 puts("After sort:");
3619 puts("After reverse sort:");
3620 a
.Sort(IntRevCompare
);
3624 #include "wx/dynarray.h"
3626 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
3627 #include "wx/arrimpl.cpp"
3628 WX_DEFINE_OBJARRAY(ArrayBars
);
3630 static void TestArrayOfObjects()
3632 puts("*** Testing wxObjArray ***\n");
3636 Bar
bar("second bar");
3638 printf("Initially: %u objects in the array, %u objects total.\n",
3639 bars
.GetCount(), Bar::GetNumber());
3641 bars
.Add(new Bar("first bar"));
3644 printf("Now: %u objects in the array, %u objects total.\n",
3645 bars
.GetCount(), Bar::GetNumber());
3649 printf("After Empty(): %u objects in the array, %u objects total.\n",
3650 bars
.GetCount(), Bar::GetNumber());
3653 printf("Finally: no more objects in the array, %u objects total.\n",
3657 #endif // TEST_ARRAYS
3659 // ----------------------------------------------------------------------------
3661 // ----------------------------------------------------------------------------
3665 #include "wx/timer.h"
3666 #include "wx/tokenzr.h"
3668 static void TestStringConstruction()
3670 puts("*** Testing wxString constructores ***");
3672 #define TEST_CTOR(args, res) \
3675 printf("wxString%s = %s ", #args, s.c_str()); \
3682 printf("(ERROR: should be %s)\n", res); \
3686 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
3687 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
3688 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
3689 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
3691 static const wxChar
*s
= _T("?really!");
3692 const wxChar
*start
= wxStrchr(s
, _T('r'));
3693 const wxChar
*end
= wxStrchr(s
, _T('!'));
3694 TEST_CTOR((start
, end
), _T("really"));
3699 static void TestString()
3709 for (int i
= 0; i
< 1000000; ++i
)
3713 c
= "! How'ya doin'?";
3716 c
= "Hello world! What's up?";
3721 printf ("TestString elapsed time: %ld\n", sw
.Time());
3724 static void TestPChar()
3732 for (int i
= 0; i
< 1000000; ++i
)
3734 strcpy (a
, "Hello");
3735 strcpy (b
, " world");
3736 strcpy (c
, "! How'ya doin'?");
3739 strcpy (c
, "Hello world! What's up?");
3740 if (strcmp (c
, a
) == 0)
3744 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
3747 static void TestStringSub()
3749 wxString
s("Hello, world!");
3751 puts("*** Testing wxString substring extraction ***");
3753 printf("String = '%s'\n", s
.c_str());
3754 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
3755 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
3756 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
3757 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
3758 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
3759 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
3761 static const wxChar
*prefixes
[] =
3765 _T("Hello, world!"),
3766 _T("Hello, world!!!"),
3772 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
3774 wxString prefix
= prefixes
[n
], rest
;
3775 bool rc
= s
.StartsWith(prefix
, &rest
);
3776 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
3779 printf(" (the rest is '%s')\n", rest
.c_str());
3790 static void TestStringFormat()
3792 puts("*** Testing wxString formatting ***");
3795 s
.Printf("%03d", 18);
3797 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
3798 printf("Number 18: %s\n", s
.c_str());
3803 // returns "not found" for npos, value for all others
3804 static wxString
PosToString(size_t res
)
3806 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
3807 : wxString::Format(_T("%u"), res
);
3811 static void TestStringFind()
3813 puts("*** Testing wxString find() functions ***");
3815 static const wxChar
*strToFind
= _T("ell");
3816 static const struct StringFindTest
3820 result
; // of searching "ell" in str
3823 { _T("Well, hello world"), 0, 1 },
3824 { _T("Well, hello world"), 6, 7 },
3825 { _T("Well, hello world"), 9, wxString::npos
},
3828 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
3830 const StringFindTest
& ft
= findTestData
[n
];
3831 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
3833 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
3834 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
3836 size_t resTrue
= ft
.result
;
3837 if ( res
== resTrue
)
3843 printf(_T("(ERROR: should be %s)\n"),
3844 PosToString(resTrue
).c_str());
3851 static void TestStringTokenizer()
3853 puts("*** Testing wxStringTokenizer ***");
3855 static const wxChar
*modeNames
[] =
3859 _T("return all empty"),
3864 static const struct StringTokenizerTest
3866 const wxChar
*str
; // string to tokenize
3867 const wxChar
*delims
; // delimiters to use
3868 size_t count
; // count of token
3869 wxStringTokenizerMode mode
; // how should we tokenize it
3870 } tokenizerTestData
[] =
3872 { _T(""), _T(" "), 0 },
3873 { _T("Hello, world"), _T(" "), 2 },
3874 { _T("Hello, world "), _T(" "), 2 },
3875 { _T("Hello, world"), _T(","), 2 },
3876 { _T("Hello, world!"), _T(",!"), 2 },
3877 { _T("Hello,, world!"), _T(",!"), 3 },
3878 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
3879 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
3880 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
3881 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
3882 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
3883 { _T("01/02/99"), _T("/-"), 3 },
3884 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
3887 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
3889 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
3890 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
3892 size_t count
= tkz
.CountTokens();
3893 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
3894 MakePrintable(tt
.str
).c_str(),
3896 MakePrintable(tt
.delims
).c_str(),
3897 modeNames
[tkz
.GetMode()]);
3898 if ( count
== tt
.count
)
3904 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
3909 // if we emulate strtok(), check that we do it correctly
3910 wxChar
*buf
, *s
= NULL
, *last
;
3912 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
3914 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
3915 wxStrcpy(buf
, tt
.str
);
3917 s
= wxStrtok(buf
, tt
.delims
, &last
);
3924 // now show the tokens themselves
3926 while ( tkz
.HasMoreTokens() )
3928 wxString token
= tkz
.GetNextToken();
3930 printf(_T("\ttoken %u: '%s'"),
3932 MakePrintable(token
).c_str());
3942 printf(" (ERROR: should be %s)\n", s
);
3945 s
= wxStrtok(NULL
, tt
.delims
, &last
);
3949 // nothing to compare with
3954 if ( count2
!= count
)
3956 puts(_T("\tERROR: token count mismatch"));
3965 static void TestStringReplace()
3967 puts("*** Testing wxString::replace ***");
3969 static const struct StringReplaceTestData
3971 const wxChar
*original
; // original test string
3972 size_t start
, len
; // the part to replace
3973 const wxChar
*replacement
; // the replacement string
3974 const wxChar
*result
; // and the expected result
3975 } stringReplaceTestData
[] =
3977 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
3978 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
3979 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
3980 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
3981 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
3984 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
3986 const StringReplaceTestData data
= stringReplaceTestData
[n
];
3988 wxString original
= data
.original
;
3989 original
.replace(data
.start
, data
.len
, data
.replacement
);
3991 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
3992 data
.original
, data
.start
, data
.len
, data
.replacement
,
3995 if ( original
== data
.result
)
4001 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4008 #endif // TEST_STRINGS
4010 // ----------------------------------------------------------------------------
4012 // ----------------------------------------------------------------------------
4014 int main(int argc
, char **argv
)
4016 if ( !wxInitialize() )
4018 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4022 puts("Sleeping for 3 seconds... z-z-z-z-z...");
4024 #endif // TEST_USLEEP
4027 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4029 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4030 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4032 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4033 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4034 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
4035 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
4037 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4038 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4043 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4045 parser
.AddOption("project_name", "", "full path to project file",
4046 wxCMD_LINE_VAL_STRING
,
4047 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4049 switch ( parser
.Parse() )
4052 wxLogMessage("Help was given, terminating.");
4056 ShowCmdLine(parser
);
4060 wxLogMessage("Syntax error detected, aborting.");
4063 #endif // TEST_CMDLINE
4074 TestStringConstruction();
4077 TestStringTokenizer();
4078 TestStringReplace();
4080 #endif // TEST_STRINGS
4093 puts("*** Initially:");
4095 PrintArray("a1", a1
);
4097 wxArrayString
a2(a1
);
4098 PrintArray("a2", a2
);
4100 wxSortedArrayString
a3(a1
);
4101 PrintArray("a3", a3
);
4103 puts("*** After deleting a string from a1");
4106 PrintArray("a1", a1
);
4107 PrintArray("a2", a2
);
4108 PrintArray("a3", a3
);
4110 puts("*** After reassigning a1 to a2 and a3");
4112 PrintArray("a2", a2
);
4113 PrintArray("a3", a3
);
4115 puts("*** After sorting a1");
4117 PrintArray("a1", a1
);
4119 puts("*** After sorting a1 in reverse order");
4121 PrintArray("a1", a1
);
4123 puts("*** After sorting a1 by the string length");
4124 a1
.Sort(StringLenCompare
);
4125 PrintArray("a1", a1
);
4127 TestArrayOfObjects();
4130 #endif // TEST_ARRAYS
4136 #ifdef TEST_DLLLOADER
4138 #endif // TEST_DLLLOADER
4142 #endif // TEST_ENVIRON
4146 #endif // TEST_EXECUTE
4148 #ifdef TEST_FILECONF
4150 #endif // TEST_FILECONF
4158 for ( size_t n
= 0; n
< 8000; n
++ )
4160 s
<< (char)('A' + (n
% 26));
4164 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4166 // this one shouldn't be truncated
4169 // but this one will because log functions use fixed size buffer
4170 // (note that it doesn't need '\n' at the end neither - will be added
4172 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4184 #ifdef TEST_FILENAME
4185 TestFileNameSplit();
4188 TestFileNameConstruction();
4190 TestFileNameComparison();
4191 TestFileNameOperations();
4193 #endif // TEST_FILENAME
4196 int nCPUs
= wxThread::GetCPUCount();
4197 printf("This system has %d CPUs\n", nCPUs
);
4199 wxThread::SetConcurrency(nCPUs
);
4201 if ( argc
> 1 && argv
[1][0] == 't' )
4202 wxLog::AddTraceMask("thread");
4205 TestDetachedThreads();
4207 TestJoinableThreads();
4209 TestThreadSuspend();
4213 #endif // TEST_THREADS
4215 #ifdef TEST_LONGLONG
4216 // seed pseudo random generator
4217 srand((unsigned)time(NULL
));
4225 TestMultiplication();
4228 TestLongLongConversion();
4229 TestBitOperations();
4231 TestLongLongComparison();
4232 #endif // TEST_LONGLONG
4239 wxLog::AddTraceMask(_T("mime"));
4247 TestMimeAssociate();
4250 #ifdef TEST_INFO_FUNCTIONS
4253 #endif // TEST_INFO_FUNCTIONS
4255 #ifdef TEST_REGISTRY
4258 TestRegistryAssociation();
4259 #endif // TEST_REGISTRY
4267 #endif // TEST_SOCKETS
4270 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4271 if ( TestFtpConnect() )
4282 TestFtpInteractive();
4284 //else: connecting to the FTP server failed
4294 #endif // TEST_STREAMS
4298 #endif // TEST_TIMER
4300 #ifdef TEST_DATETIME
4313 TestTimeArithmetics();
4321 TestDateTimeInteractive();
4322 #endif // TEST_DATETIME
4328 #endif // TEST_VCARD
4332 #endif // TEST_WCHAR
4335 TestZipStreamRead();
4340 TestZlibStreamWrite();
4341 TestZlibStreamRead();