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
42 //#define TEST_DLLLOADER
43 //#define TEST_EXECUTE
45 //#define TEST_FILECONF
49 //#define TEST_LONGLONG
51 //#define TEST_INFO_FUNCTIONS
52 //#define TEST_SOCKETS
53 //#define TEST_STRINGS
54 //#define TEST_THREADS
60 // ----------------------------------------------------------------------------
61 // test class for container objects
62 // ----------------------------------------------------------------------------
64 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
66 class Bar
// Foo is already taken in the hash test
69 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
72 static size_t GetNumber() { return ms_bars
; }
74 const char *GetName() const { return m_name
; }
79 static size_t ms_bars
;
82 size_t Bar::ms_bars
= 0;
84 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
86 // ============================================================================
88 // ============================================================================
90 // ----------------------------------------------------------------------------
92 // ----------------------------------------------------------------------------
94 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
96 // replace TABs with \t and CRs with \n
97 static wxString
MakePrintable(const wxChar
*s
)
100 (void)str
.Replace(_T("\t"), _T("\\t"));
101 (void)str
.Replace(_T("\n"), _T("\\n"));
102 (void)str
.Replace(_T("\r"), _T("\\r"));
107 #endif // MakePrintable() is used
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
115 #include <wx/cmdline.h>
116 #include <wx/datetime.h>
118 static void ShowCmdLine(const wxCmdLineParser
& parser
)
120 wxString s
= "Input files: ";
122 size_t count
= parser
.GetParamCount();
123 for ( size_t param
= 0; param
< count
; param
++ )
125 s
<< parser
.GetParam(param
) << ' ';
129 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
130 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
135 if ( parser
.Found("o", &strVal
) )
136 s
<< "Output file:\t" << strVal
<< '\n';
137 if ( parser
.Found("i", &strVal
) )
138 s
<< "Input dir:\t" << strVal
<< '\n';
139 if ( parser
.Found("s", &lVal
) )
140 s
<< "Size:\t" << lVal
<< '\n';
141 if ( parser
.Found("d", &dt
) )
142 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
143 if ( parser
.Found("project_name", &strVal
) )
144 s
<< "Project:\t" << strVal
<< '\n';
149 #endif // TEST_CMDLINE
151 // ----------------------------------------------------------------------------
153 // ----------------------------------------------------------------------------
159 static void TestDirEnumHelper(wxDir
& dir
,
160 int flags
= wxDIR_DEFAULT
,
161 const wxString
& filespec
= wxEmptyString
)
165 if ( !dir
.IsOpened() )
168 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
171 printf("\t%s\n", filename
.c_str());
173 cont
= dir
.GetNext(&filename
);
179 static void TestDirEnum()
181 wxDir
dir(wxGetCwd());
183 puts("Enumerating everything in current directory:");
184 TestDirEnumHelper(dir
);
186 puts("Enumerating really everything in current directory:");
187 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
189 puts("Enumerating object files in current directory:");
190 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
192 puts("Enumerating directories in current directory:");
193 TestDirEnumHelper(dir
, wxDIR_DIRS
);
195 puts("Enumerating files in current directory:");
196 TestDirEnumHelper(dir
, wxDIR_FILES
);
198 puts("Enumerating files including hidden in current directory:");
199 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
203 #elif defined(__WXMSW__)
206 #error "don't know where the root directory is"
209 puts("Enumerating everything in root directory:");
210 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
212 puts("Enumerating directories in root directory:");
213 TestDirEnumHelper(dir
, wxDIR_DIRS
);
215 puts("Enumerating files in root directory:");
216 TestDirEnumHelper(dir
, wxDIR_FILES
);
218 puts("Enumerating files including hidden in root directory:");
219 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
221 puts("Enumerating files in non existing directory:");
222 wxDir
dirNo("nosuchdir");
223 TestDirEnumHelper(dirNo
);
228 // ----------------------------------------------------------------------------
230 // ----------------------------------------------------------------------------
232 #ifdef TEST_DLLLOADER
234 #include <wx/dynlib.h>
236 static void TestDllLoad()
238 #if defined(__WXMSW__)
239 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
240 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
241 #elif defined(__UNIX__)
242 // weird: using just libc.so does *not* work!
243 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
244 static const wxChar
*FUNC_NAME
= _T("strlen");
246 #error "don't know how to test wxDllLoader on this platform"
249 puts("*** testing wxDllLoader ***\n");
251 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
254 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
258 typedef int (*strlenType
)(char *);
259 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
262 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
263 FUNC_NAME
, LIB_NAME
);
267 if ( pfnStrlen("foo") != 3 )
269 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
277 wxDllLoader::UnloadLibrary(dllHandle
);
281 #endif // TEST_DLLLOADER
283 // ----------------------------------------------------------------------------
285 // ----------------------------------------------------------------------------
289 #include <wx/utils.h>
291 static void TestExecute()
293 puts("*** testing wxExecute ***");
296 #define COMMAND "echo hi"
297 #define SHELL_COMMAND "echo hi from shell"
298 #define REDIRECT_COMMAND "date"
299 #elif defined(__WXMSW__)
300 #define COMMAND "command.com -c 'echo hi'"
301 #define SHELL_COMMAND "echo hi"
302 #define REDIRECT_COMMAND COMMAND
304 #error "no command to exec"
307 printf("Testing wxShell: ");
309 if ( wxShell(SHELL_COMMAND
) )
314 printf("Testing wxExecute: ");
316 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
321 #if 0 // no, it doesn't work (yet?)
322 printf("Testing async wxExecute: ");
324 if ( wxExecute(COMMAND
) != 0 )
325 puts("Ok (command launched).");
330 printf("Testing wxExecute with redirection:\n");
331 wxArrayString output
;
332 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
338 size_t count
= output
.GetCount();
339 for ( size_t n
= 0; n
< count
; n
++ )
341 printf("\t%s\n", output
[n
].c_str());
348 #endif // TEST_EXECUTE
350 // ----------------------------------------------------------------------------
352 // ----------------------------------------------------------------------------
357 #include <wx/textfile.h>
359 static void TestFileRead()
361 puts("*** wxFile read test ***");
363 wxFile
file(_T("testdata.fc"));
364 if ( file
.IsOpened() )
366 printf("File length: %lu\n", file
.Length());
368 puts("File dump:\n----------");
370 static const size_t len
= 1024;
374 off_t nRead
= file
.Read(buf
, len
);
375 if ( nRead
== wxInvalidOffset
)
377 printf("Failed to read the file.");
381 fwrite(buf
, nRead
, 1, stdout
);
391 printf("ERROR: can't open test file.\n");
397 static void TestTextFileRead()
399 puts("*** wxTextFile read test ***");
401 wxTextFile
file(_T("testdata.fc"));
404 printf("Number of lines: %u\n", file
.GetLineCount());
405 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
409 printf("ERROR: can't open '%s'\n", file
.GetName());
417 // ----------------------------------------------------------------------------
419 // ----------------------------------------------------------------------------
423 #include <wx/confbase.h>
424 #include <wx/fileconf.h>
426 static const struct FileConfTestData
428 const wxChar
*name
; // value name
429 const wxChar
*value
; // the value from the file
432 { _T("value1"), _T("one") },
433 { _T("value2"), _T("two") },
434 { _T("novalue"), _T("default") },
437 static void TestFileConfRead()
439 puts("*** testing wxFileConfig loading/reading ***");
441 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
442 _T("testdata.fc"), wxEmptyString
,
443 wxCONFIG_USE_RELATIVE_PATH
);
445 // test simple reading
446 puts("\nReading config file:");
447 wxString
defValue(_T("default")), value
;
448 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
450 const FileConfTestData
& data
= fcTestData
[n
];
451 value
= fileconf
.Read(data
.name
, defValue
);
452 printf("\t%s = %s ", data
.name
, value
.c_str());
453 if ( value
== data
.value
)
459 printf("(ERROR: should be %s)\n", data
.value
);
463 // test enumerating the entries
464 puts("\nEnumerating all root entries:");
467 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
470 printf("\t%s = %s\n",
472 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
474 cont
= fileconf
.GetNextEntry(name
, dummy
);
478 #endif // TEST_FILECONF
480 // ----------------------------------------------------------------------------
482 // ----------------------------------------------------------------------------
490 Foo(int n_
) { n
= n_
; count
++; }
498 size_t Foo::count
= 0;
500 WX_DECLARE_LIST(Foo
, wxListFoos
);
501 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
503 #include <wx/listimpl.cpp>
505 WX_DEFINE_LIST(wxListFoos
);
507 static void TestHash()
509 puts("*** Testing wxHashTable ***\n");
513 hash
.DeleteContents(TRUE
);
515 printf("Hash created: %u foos in hash, %u foos totally\n",
516 hash
.GetCount(), Foo::count
);
518 static const int hashTestData
[] =
520 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
524 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
526 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
529 printf("Hash filled: %u foos in hash, %u foos totally\n",
530 hash
.GetCount(), Foo::count
);
532 puts("Hash access test:");
533 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
535 printf("\tGetting element with key %d, value %d: ",
537 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
540 printf("ERROR, not found.\n");
544 printf("%d (%s)\n", foo
->n
,
545 (size_t)foo
->n
== n
? "ok" : "ERROR");
549 printf("\nTrying to get an element not in hash: ");
551 if ( hash
.Get(1234) || hash
.Get(1, 0) )
553 puts("ERROR: found!");
557 puts("ok (not found)");
561 printf("Hash destroyed: %u foos left\n", Foo::count
);
566 // ----------------------------------------------------------------------------
568 // ----------------------------------------------------------------------------
574 WX_DECLARE_LIST(Bar
, wxListBars
);
575 #include <wx/listimpl.cpp>
576 WX_DEFINE_LIST(wxListBars
);
578 static void TestListCtor()
580 puts("*** Testing wxList construction ***\n");
584 list1
.Append(new Bar(_T("first")));
585 list1
.Append(new Bar(_T("second")));
587 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
588 list1
.GetCount(), Bar::GetNumber());
593 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
594 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
596 list1
.DeleteContents(TRUE
);
599 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
604 // ----------------------------------------------------------------------------
606 // ----------------------------------------------------------------------------
610 #include <wx/mimetype.h>
612 static wxMimeTypesManager g_mimeManager
;
614 static void TestMimeEnum()
616 wxArrayString mimetypes
;
618 size_t count
= g_mimeManager
.EnumAllFileTypes(mimetypes
);
620 printf("*** All %u known filetypes: ***\n", count
);
625 for ( size_t n
= 0; n
< count
; n
++ )
627 wxFileType
*filetype
= g_mimeManager
.GetFileTypeFromMimeType(mimetypes
[n
]);
630 printf("nothing known about the filetype '%s'!\n",
631 mimetypes
[n
].c_str());
635 filetype
->GetDescription(&desc
);
636 filetype
->GetExtensions(exts
);
638 filetype
->GetIcon(NULL
);
641 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
648 printf("\t%s: %s (%s)\n",
649 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
653 static void TestMimeOverride()
655 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
657 wxString mailcap
= _T("/tmp/mailcap"),
658 mimetypes
= _T("/tmp/mime.types");
660 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
662 g_mimeManager
.ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
663 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
665 g_mimeManager
.ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
668 static void TestMimeFilename()
670 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
672 static const wxChar
*filenames
[] =
679 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
681 const wxString fname
= filenames
[n
];
682 wxString ext
= fname
.AfterLast(_T('.'));
683 wxFileType
*ft
= g_mimeManager
.GetFileTypeFromExtension(ext
);
686 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
691 if ( !ft
->GetDescription(&desc
) )
692 desc
= _T("<no description>");
695 if ( !ft
->GetOpenCommand(&cmd
,
696 wxFileType::MessageParameters(fname
, _T(""))) )
697 cmd
= _T("<no command available>");
699 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
700 fname
.c_str(), desc
.c_str(), cmd
.c_str());
709 // ----------------------------------------------------------------------------
710 // misc information functions
711 // ----------------------------------------------------------------------------
713 #ifdef TEST_INFO_FUNCTIONS
715 #include <wx/utils.h>
717 static void TestOsInfo()
719 puts("*** Testing OS info functions ***\n");
722 wxGetOsVersion(&major
, &minor
);
723 printf("Running under: %s, version %d.%d\n",
724 wxGetOsDescription().c_str(), major
, minor
);
726 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
728 printf("Host name is %s (%s).\n",
729 wxGetHostName().c_str(), wxGetFullHostName().c_str());
734 static void TestUserInfo()
736 puts("*** Testing user info functions ***\n");
738 printf("User id is:\t%s\n", wxGetUserId().c_str());
739 printf("User name is:\t%s\n", wxGetUserName().c_str());
740 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
741 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
746 #endif // TEST_INFO_FUNCTIONS
748 // ----------------------------------------------------------------------------
750 // ----------------------------------------------------------------------------
754 #include <wx/longlong.h>
755 #include <wx/timer.h>
757 // make a 64 bit number from 4 16 bit ones
758 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
760 // get a random 64 bit number
761 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
763 #if wxUSE_LONGLONG_WX
764 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
765 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
766 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
767 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
768 #endif // wxUSE_LONGLONG_WX
770 static void TestSpeed()
772 static const long max
= 100000000;
779 for ( n
= 0; n
< max
; n
++ )
784 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
787 #if wxUSE_LONGLONG_NATIVE
792 for ( n
= 0; n
< max
; n
++ )
797 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
799 #endif // wxUSE_LONGLONG_NATIVE
805 for ( n
= 0; n
< max
; n
++ )
810 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
814 static void TestLongLongConversion()
816 puts("*** Testing wxLongLong conversions ***\n");
820 for ( size_t n
= 0; n
< 100000; n
++ )
824 #if wxUSE_LONGLONG_NATIVE
825 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
827 wxASSERT_MSG( a
== b
, "conversions failure" );
829 puts("Can't do it without native long long type, test skipped.");
832 #endif // wxUSE_LONGLONG_NATIVE
834 if ( !(nTested
% 1000) )
846 static void TestMultiplication()
848 puts("*** Testing wxLongLong multiplication ***\n");
852 for ( size_t n
= 0; n
< 100000; n
++ )
857 #if wxUSE_LONGLONG_NATIVE
858 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
859 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
861 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
862 #else // !wxUSE_LONGLONG_NATIVE
863 puts("Can't do it without native long long type, test skipped.");
866 #endif // wxUSE_LONGLONG_NATIVE
868 if ( !(nTested
% 1000) )
880 static void TestDivision()
882 puts("*** Testing wxLongLong division ***\n");
886 for ( size_t n
= 0; n
< 100000; n
++ )
888 // get a random wxLongLong (shifting by 12 the MSB ensures that the
889 // multiplication will not overflow)
890 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
892 // get a random long (not wxLongLong for now) to divide it with
897 #if wxUSE_LONGLONG_NATIVE
898 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
900 wxLongLongNative p
= m
/ l
, s
= m
% l
;
901 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
902 #else // !wxUSE_LONGLONG_NATIVE
904 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
905 #endif // wxUSE_LONGLONG_NATIVE
907 if ( !(nTested
% 1000) )
919 static void TestAddition()
921 puts("*** Testing wxLongLong addition ***\n");
925 for ( size_t n
= 0; n
< 100000; n
++ )
931 #if wxUSE_LONGLONG_NATIVE
932 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
933 wxLongLongNative(b
.GetHi(), b
.GetLo()),
934 "addition failure" );
935 #else // !wxUSE_LONGLONG_NATIVE
936 wxASSERT_MSG( c
- b
== a
, "addition failure" );
937 #endif // wxUSE_LONGLONG_NATIVE
939 if ( !(nTested
% 1000) )
951 static void TestBitOperations()
953 puts("*** Testing wxLongLong bit operation ***\n");
957 for ( size_t n
= 0; n
< 100000; n
++ )
961 #if wxUSE_LONGLONG_NATIVE
962 for ( size_t n
= 0; n
< 33; n
++ )
965 #else // !wxUSE_LONGLONG_NATIVE
966 puts("Can't do it without native long long type, test skipped.");
969 #endif // wxUSE_LONGLONG_NATIVE
971 if ( !(nTested
% 1000) )
983 static void TestLongLongComparison()
985 puts("*** Testing wxLongLong comparison ***\n");
987 static const long testLongs
[] =
998 static const long ls
[2] =
1004 wxLongLongWx lls
[2];
1008 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1012 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1014 res
= lls
[m
] > testLongs
[n
];
1015 printf("0x%lx > 0x%lx is %s (%s)\n",
1016 ls
[m
], testLongs
[n
], res
? "true" : "false",
1017 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1019 res
= lls
[m
] < testLongs
[n
];
1020 printf("0x%lx < 0x%lx is %s (%s)\n",
1021 ls
[m
], testLongs
[n
], res
? "true" : "false",
1022 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1024 res
= lls
[m
] == testLongs
[n
];
1025 printf("0x%lx == 0x%lx is %s (%s)\n",
1026 ls
[m
], testLongs
[n
], res
? "true" : "false",
1027 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1035 #endif // TEST_LONGLONG
1037 // ----------------------------------------------------------------------------
1039 // ----------------------------------------------------------------------------
1043 #include <wx/socket.h>
1044 #include <wx/protocol/protocol.h>
1045 #include <wx/protocol/ftp.h>
1046 #include <wx/protocol/http.h>
1048 static void TestSocketServer()
1050 puts("*** Testing wxSocketServer ***\n");
1052 static const int PORT
= 3000;
1057 wxSocketServer
*server
= new wxSocketServer(addr
);
1058 if ( !server
->Ok() )
1060 puts("ERROR: failed to bind");
1067 printf("Server: waiting for connection on port %d...\n", PORT
);
1069 wxSocketBase
*socket
= server
->Accept();
1072 puts("ERROR: wxSocketServer::Accept() failed.");
1076 puts("Server: got a client.");
1078 server
->SetTimeout(60); // 1 min
1080 while ( socket
->IsConnected() )
1086 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1088 // don't log error if the client just close the connection
1089 if ( socket
->IsConnected() )
1091 puts("ERROR: in wxSocket::Read.");
1111 printf("Server: got '%s'.\n", s
.c_str());
1112 if ( s
== _T("bye") )
1119 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1120 socket
->Write("\r\n", 2);
1121 printf("Server: wrote '%s'.\n", s
.c_str());
1124 puts("Server: lost a client.");
1129 // same as "delete server" but is consistent with GUI programs
1133 static void TestSocketClient()
1135 puts("*** Testing wxSocketClient ***\n");
1137 static const char *hostname
= "www.wxwindows.org";
1140 addr
.Hostname(hostname
);
1143 printf("--- Attempting to connect to %s:80...\n", hostname
);
1145 wxSocketClient client
;
1146 if ( !client
.Connect(addr
) )
1148 printf("ERROR: failed to connect to %s\n", hostname
);
1152 printf("--- Connected to %s:%u...\n",
1153 addr
.Hostname().c_str(), addr
.Service());
1157 // could use simply "GET" here I suppose
1159 wxString::Format("GET http://%s/\r\n", hostname
);
1160 client
.Write(cmdGet
, cmdGet
.length());
1161 printf("--- Sent command '%s' to the server\n",
1162 MakePrintable(cmdGet
).c_str());
1163 client
.Read(buf
, WXSIZEOF(buf
));
1164 printf("--- Server replied:\n%s", buf
);
1168 static void TestProtocolFtp()
1170 puts("*** Testing wxFTP download ***\n");
1172 wxLog::AddTraceMask(_T("ftp"));
1174 static const char *hostname
= "ftp.wxwindows.org";
1176 printf("--- Attempting to connect to %s:21...\n", hostname
);
1179 if ( !ftp
.Connect(hostname
) )
1181 printf("ERROR: failed to connect to %s\n", hostname
);
1185 printf("--- Connected to %s, current directory is '%s'\n",
1186 hostname
, ftp
.Pwd().c_str());
1187 if ( !ftp
.ChDir(_T("pub")) )
1189 puts("ERROR: failed to cd to pub");
1192 wxArrayString files
;
1193 if ( !ftp
.GetList(files
) )
1195 puts("ERROR: failed to get list of files");
1199 printf("List of files under '%s':\n", ftp
.Pwd().c_str());
1200 size_t count
= files
.GetCount();
1201 for ( size_t n
= 0; n
< count
; n
++ )
1203 printf("\t%s\n", files
[n
].c_str());
1205 puts("End of the file list");
1208 if ( !ftp
.ChDir(_T("..")) )
1210 puts("ERROR: failed to cd to ..");
1213 static const char *filename
= "welcome.msg";
1214 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1217 puts("ERROR: couldn't get input stream");
1221 size_t size
= in
->StreamSize();
1222 printf("Reading file %s (%u bytes)...", filename
, size
);
1224 char *data
= new char[size
];
1225 if ( !in
->Read(data
, size
) )
1227 puts("ERROR: read error");
1231 printf("\nContents of %s:\n%s\n", filename
, data
);
1240 static void TestProtocolFtpUpload()
1242 puts("*** Testing wxFTP uploading ***\n");
1244 wxLog::AddTraceMask(_T("ftp"));
1246 static const char *hostname
= "localhost";
1248 printf("--- Attempting to connect to %s:21...\n", hostname
);
1251 ftp
.SetUser("zeitlin");
1252 ftp
.SetPassword("insert your password here");
1253 if ( !ftp
.Connect(hostname
) )
1255 printf("ERROR: failed to connect to %s\n", hostname
);
1259 printf("--- Connected to %s, current directory is '%s'\n",
1260 hostname
, ftp
.Pwd().c_str());
1263 static const char *file1
= "test1";
1264 static const char *file2
= "test2";
1265 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
1268 printf("--- Uploading to %s ---\n", file1
);
1269 out
->Write("First hello", 11);
1273 out
= ftp
.GetOutputStream(file2
);
1276 printf("--- Uploading to %s ---\n", file1
);
1277 out
->Write("Second hello", 12);
1283 #endif // TEST_SOCKETS
1285 // ----------------------------------------------------------------------------
1287 // ----------------------------------------------------------------------------
1291 #include <wx/timer.h>
1292 #include <wx/utils.h>
1294 static void TestStopWatch()
1296 puts("*** Testing wxStopWatch ***\n");
1299 printf("Sleeping 3 seconds...");
1301 printf("\telapsed time: %ldms\n", sw
.Time());
1304 printf("Sleeping 2 more seconds...");
1306 printf("\telapsed time: %ldms\n", sw
.Time());
1309 printf("And 3 more seconds...");
1311 printf("\telapsed time: %ldms\n", sw
.Time());
1314 puts("\nChecking for 'backwards clock' bug...");
1315 for ( size_t n
= 0; n
< 70; n
++ )
1319 for ( size_t m
= 0; m
< 100000; m
++ )
1321 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
1323 puts("\ntime is negative - ERROR!");
1333 #endif // TEST_TIMER
1335 // ----------------------------------------------------------------------------
1337 // ----------------------------------------------------------------------------
1341 #include <wx/vcard.h>
1343 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
1346 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
1350 wxString(_T('\t'), level
).c_str(),
1351 vcObj
->GetName().c_str());
1354 switch ( vcObj
->GetType() )
1356 case wxVCardObject::String
:
1357 case wxVCardObject::UString
:
1360 vcObj
->GetValue(&val
);
1361 value
<< _T('"') << val
<< _T('"');
1365 case wxVCardObject::Int
:
1368 vcObj
->GetValue(&i
);
1369 value
.Printf(_T("%u"), i
);
1373 case wxVCardObject::Long
:
1376 vcObj
->GetValue(&l
);
1377 value
.Printf(_T("%lu"), l
);
1381 case wxVCardObject::None
:
1384 case wxVCardObject::Object
:
1385 value
= _T("<node>");
1389 value
= _T("<unknown value type>");
1393 printf(" = %s", value
.c_str());
1396 DumpVObject(level
+ 1, *vcObj
);
1399 vcObj
= vcard
.GetNextProp(&cookie
);
1403 static void DumpVCardAddresses(const wxVCard
& vcard
)
1405 puts("\nShowing all addresses from vCard:\n");
1409 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
1413 int flags
= addr
->GetFlags();
1414 if ( flags
& wxVCardAddress::Domestic
)
1416 flagsStr
<< _T("domestic ");
1418 if ( flags
& wxVCardAddress::Intl
)
1420 flagsStr
<< _T("international ");
1422 if ( flags
& wxVCardAddress::Postal
)
1424 flagsStr
<< _T("postal ");
1426 if ( flags
& wxVCardAddress::Parcel
)
1428 flagsStr
<< _T("parcel ");
1430 if ( flags
& wxVCardAddress::Home
)
1432 flagsStr
<< _T("home ");
1434 if ( flags
& wxVCardAddress::Work
)
1436 flagsStr
<< _T("work ");
1439 printf("Address %u:\n"
1441 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
1444 addr
->GetPostOffice().c_str(),
1445 addr
->GetExtAddress().c_str(),
1446 addr
->GetStreet().c_str(),
1447 addr
->GetLocality().c_str(),
1448 addr
->GetRegion().c_str(),
1449 addr
->GetPostalCode().c_str(),
1450 addr
->GetCountry().c_str()
1454 addr
= vcard
.GetNextAddress(&cookie
);
1458 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
1460 puts("\nShowing all phone numbers from vCard:\n");
1464 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
1468 int flags
= phone
->GetFlags();
1469 if ( flags
& wxVCardPhoneNumber::Voice
)
1471 flagsStr
<< _T("voice ");
1473 if ( flags
& wxVCardPhoneNumber::Fax
)
1475 flagsStr
<< _T("fax ");
1477 if ( flags
& wxVCardPhoneNumber::Cellular
)
1479 flagsStr
<< _T("cellular ");
1481 if ( flags
& wxVCardPhoneNumber::Modem
)
1483 flagsStr
<< _T("modem ");
1485 if ( flags
& wxVCardPhoneNumber::Home
)
1487 flagsStr
<< _T("home ");
1489 if ( flags
& wxVCardPhoneNumber::Work
)
1491 flagsStr
<< _T("work ");
1494 printf("Phone number %u:\n"
1499 phone
->GetNumber().c_str()
1503 phone
= vcard
.GetNextPhoneNumber(&cookie
);
1507 static void TestVCardRead()
1509 puts("*** Testing wxVCard reading ***\n");
1511 wxVCard
vcard(_T("vcard.vcf"));
1512 if ( !vcard
.IsOk() )
1514 puts("ERROR: couldn't load vCard.");
1518 // read individual vCard properties
1519 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
1523 vcObj
->GetValue(&value
);
1528 value
= _T("<none>");
1531 printf("Full name retrieved directly: %s\n", value
.c_str());
1534 if ( !vcard
.GetFullName(&value
) )
1536 value
= _T("<none>");
1539 printf("Full name from wxVCard API: %s\n", value
.c_str());
1541 // now show how to deal with multiply occuring properties
1542 DumpVCardAddresses(vcard
);
1543 DumpVCardPhoneNumbers(vcard
);
1545 // and finally show all
1546 puts("\nNow dumping the entire vCard:\n"
1547 "-----------------------------\n");
1549 DumpVObject(0, vcard
);
1553 static void TestVCardWrite()
1555 puts("*** Testing wxVCard writing ***\n");
1558 if ( !vcard
.IsOk() )
1560 puts("ERROR: couldn't create vCard.");
1565 vcard
.SetName("Zeitlin", "Vadim");
1566 vcard
.SetFullName("Vadim Zeitlin");
1567 vcard
.SetOrganization("wxWindows", "R&D");
1569 // just dump the vCard back
1570 puts("Entire vCard follows:\n");
1571 puts(vcard
.Write());
1575 #endif // TEST_VCARD
1577 // ----------------------------------------------------------------------------
1578 // wide char (Unicode) support
1579 // ----------------------------------------------------------------------------
1583 #include <wx/strconv.h>
1584 #include <wx/buffer.h>
1586 static void TestUtf8()
1588 puts("*** Testing UTF8 support ***\n");
1590 wxString testString
= "français";
1592 "************ French - Français ****************"
1593 "Juste un petit exemple pour dire que les français aussi"
1594 "ont à cœur de pouvoir utiliser tous leurs caractères ! :)";
1597 wxWCharBuffer wchBuf
= testString
.wc_str(wxConvUTF8
);
1598 const wchar_t *pwz
= (const wchar_t *)wchBuf
;
1599 wxString
testString2(pwz
, wxConvLocal
);
1601 printf("Decoding '%s' => '%s'\n", testString
.c_str(), testString2
.c_str());
1603 char *psz
= "fran" "\xe7" "ais";
1604 size_t len
= strlen(psz
);
1605 wchar_t *pwz2
= new wchar_t[len
+ 1];
1606 for ( size_t n
= 0; n
<= len
; n
++ )
1608 pwz2
[n
] = (wchar_t)(unsigned char)psz
[n
];
1611 wxString
testString3(pwz2
, wxConvUTF8
);
1614 printf("Encoding '%s' -> '%s'\n", psz
, testString3
.c_str());
1617 #endif // TEST_WCHAR
1619 // ----------------------------------------------------------------------------
1621 // ----------------------------------------------------------------------------
1625 #include "wx/zipstrm.h"
1627 static void TestZipStreamRead()
1629 puts("*** Testing ZIP reading ***\n");
1631 wxZipInputStream
istr(_T("idx.zip"), _T("IDX.txt"));
1632 printf("Archive size: %u\n", istr
.GetSize());
1634 puts("Dumping the file:");
1635 while ( !istr
.Eof() )
1637 putchar(istr
.GetC());
1641 puts("\n----- done ------");
1646 // ----------------------------------------------------------------------------
1648 // ----------------------------------------------------------------------------
1650 #ifdef TEST_DATETIME
1652 #include <wx/date.h>
1654 #include <wx/datetime.h>
1659 wxDateTime::wxDateTime_t day
;
1660 wxDateTime::Month month
;
1662 wxDateTime::wxDateTime_t hour
, min
, sec
;
1664 wxDateTime::WeekDay wday
;
1665 time_t gmticks
, ticks
;
1667 void Init(const wxDateTime::Tm
& tm
)
1676 gmticks
= ticks
= -1;
1679 wxDateTime
DT() const
1680 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
1682 bool SameDay(const wxDateTime::Tm
& tm
) const
1684 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
1687 wxString
Format() const
1690 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
1692 wxDateTime::GetMonthName(month
).c_str(),
1694 abs(wxDateTime::ConvertYearToBC(year
)),
1695 year
> 0 ? "AD" : "BC");
1699 wxString
FormatDate() const
1702 s
.Printf("%02d-%s-%4d%s",
1704 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
1705 abs(wxDateTime::ConvertYearToBC(year
)),
1706 year
> 0 ? "AD" : "BC");
1711 static const Date testDates
[] =
1713 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
1714 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
1715 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
1716 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
1717 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
1718 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
1719 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
1720 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
1721 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
1722 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
1723 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
1724 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
1725 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
1726 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
1727 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
1730 // this test miscellaneous static wxDateTime functions
1731 static void TestTimeStatic()
1733 puts("\n*** wxDateTime static methods test ***");
1735 // some info about the current date
1736 int year
= wxDateTime::GetCurrentYear();
1737 printf("Current year %d is %sa leap one and has %d days.\n",
1739 wxDateTime::IsLeapYear(year
) ? "" : "not ",
1740 wxDateTime::GetNumberOfDays(year
));
1742 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
1743 printf("Current month is '%s' ('%s') and it has %d days\n",
1744 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
1745 wxDateTime::GetMonthName(month
).c_str(),
1746 wxDateTime::GetNumberOfDays(month
));
1749 static const size_t nYears
= 5;
1750 static const size_t years
[2][nYears
] =
1752 // first line: the years to test
1753 { 1990, 1976, 2000, 2030, 1984, },
1755 // second line: TRUE if leap, FALSE otherwise
1756 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
1759 for ( size_t n
= 0; n
< nYears
; n
++ )
1761 int year
= years
[0][n
];
1762 bool should
= years
[1][n
] != 0,
1763 is
= wxDateTime::IsLeapYear(year
);
1765 printf("Year %d is %sa leap year (%s)\n",
1768 should
== is
? "ok" : "ERROR");
1770 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
1774 // test constructing wxDateTime objects
1775 static void TestTimeSet()
1777 puts("\n*** wxDateTime construction test ***");
1779 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1781 const Date
& d1
= testDates
[n
];
1782 wxDateTime dt
= d1
.DT();
1785 d2
.Init(dt
.GetTm());
1787 wxString s1
= d1
.Format(),
1790 printf("Date: %s == %s (%s)\n",
1791 s1
.c_str(), s2
.c_str(),
1792 s1
== s2
? "ok" : "ERROR");
1796 // test time zones stuff
1797 static void TestTimeZones()
1799 puts("\n*** wxDateTime timezone test ***");
1801 wxDateTime now
= wxDateTime::Now();
1803 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
1804 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
1805 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
1806 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
1807 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
1808 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
1810 wxDateTime::Tm tm
= now
.GetTm();
1811 if ( wxDateTime(tm
) != now
)
1813 printf("ERROR: got %s instead of %s\n",
1814 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
1818 // test some minimal support for the dates outside the standard range
1819 static void TestTimeRange()
1821 puts("\n*** wxDateTime out-of-standard-range dates test ***");
1823 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
1825 printf("Unix epoch:\t%s\n",
1826 wxDateTime(2440587.5).Format(fmt
).c_str());
1827 printf("Feb 29, 0: \t%s\n",
1828 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
1829 printf("JDN 0: \t%s\n",
1830 wxDateTime(0.0).Format(fmt
).c_str());
1831 printf("Jan 1, 1AD:\t%s\n",
1832 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
1833 printf("May 29, 2099:\t%s\n",
1834 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
1837 static void TestTimeTicks()
1839 puts("\n*** wxDateTime ticks test ***");
1841 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1843 const Date
& d
= testDates
[n
];
1844 if ( d
.ticks
== -1 )
1847 wxDateTime dt
= d
.DT();
1848 long ticks
= (dt
.GetValue() / 1000).ToLong();
1849 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
1850 if ( ticks
== d
.ticks
)
1856 printf(" (ERROR: should be %ld, delta = %ld)\n",
1857 d
.ticks
, ticks
- d
.ticks
);
1860 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
1861 ticks
= (dt
.GetValue() / 1000).ToLong();
1862 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
1863 if ( ticks
== d
.gmticks
)
1869 printf(" (ERROR: should be %ld, delta = %ld)\n",
1870 d
.gmticks
, ticks
- d
.gmticks
);
1877 // test conversions to JDN &c
1878 static void TestTimeJDN()
1880 puts("\n*** wxDateTime to JDN test ***");
1882 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1884 const Date
& d
= testDates
[n
];
1885 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
1886 double jdn
= dt
.GetJulianDayNumber();
1888 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
1895 printf(" (ERROR: should be %f, delta = %f)\n",
1896 d
.jdn
, jdn
- d
.jdn
);
1901 // test week days computation
1902 static void TestTimeWDays()
1904 puts("\n*** wxDateTime weekday test ***");
1906 // test GetWeekDay()
1908 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1910 const Date
& d
= testDates
[n
];
1911 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
1913 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
1916 wxDateTime::GetWeekDayName(wday
).c_str());
1917 if ( wday
== d
.wday
)
1923 printf(" (ERROR: should be %s)\n",
1924 wxDateTime::GetWeekDayName(d
.wday
).c_str());
1930 // test SetToWeekDay()
1931 struct WeekDateTestData
1933 Date date
; // the real date (precomputed)
1934 int nWeek
; // its week index in the month
1935 wxDateTime::WeekDay wday
; // the weekday
1936 wxDateTime::Month month
; // the month
1937 int year
; // and the year
1939 wxString
Format() const
1942 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
1944 case 1: which
= "first"; break;
1945 case 2: which
= "second"; break;
1946 case 3: which
= "third"; break;
1947 case 4: which
= "fourth"; break;
1948 case 5: which
= "fifth"; break;
1950 case -1: which
= "last"; break;
1955 which
+= " from end";
1958 s
.Printf("The %s %s of %s in %d",
1960 wxDateTime::GetWeekDayName(wday
).c_str(),
1961 wxDateTime::GetMonthName(month
).c_str(),
1968 // the array data was generated by the following python program
1970 from DateTime import *
1971 from whrandom import *
1972 from string import *
1974 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1975 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1977 week = DateTimeDelta(7)
1980 year = randint(1900, 2100)
1981 month = randint(1, 12)
1982 day = randint(1, 28)
1983 dt = DateTime(year, month, day)
1984 wday = dt.day_of_week
1986 countFromEnd = choice([-1, 1])
1989 while dt.month is month:
1990 dt = dt - countFromEnd * week
1991 weekNum = weekNum + countFromEnd
1993 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
1995 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
1996 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
1999 static const WeekDateTestData weekDatesTestData
[] =
2001 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
2002 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
2003 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
2004 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
2005 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
2006 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
2007 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
2008 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
2009 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
2010 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
2011 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
2012 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
2013 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
2014 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
2015 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
2016 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
2017 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
2018 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
2019 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
2020 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
2023 static const char *fmt
= "%d-%b-%Y";
2026 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
2028 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
2030 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
2032 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
2034 const Date
& d
= wd
.date
;
2035 if ( d
.SameDay(dt
.GetTm()) )
2041 dt
.Set(d
.day
, d
.month
, d
.year
);
2043 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
2048 // test the computation of (ISO) week numbers
2049 static void TestTimeWNumber()
2051 puts("\n*** wxDateTime week number test ***");
2053 struct WeekNumberTestData
2055 Date date
; // the date
2056 wxDateTime::wxDateTime_t week
; // the week number in the year
2057 wxDateTime::wxDateTime_t wmon
; // the week number in the month
2058 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
2059 wxDateTime::wxDateTime_t dnum
; // day number in the year
2062 // data generated with the following python script:
2064 from DateTime import *
2065 from whrandom import *
2066 from string import *
2068 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2069 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2071 def GetMonthWeek(dt):
2072 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
2073 if weekNumMonth < 0:
2074 weekNumMonth = weekNumMonth + 53
2077 def GetLastSundayBefore(dt):
2078 if dt.iso_week[2] == 7:
2081 return dt - DateTimeDelta(dt.iso_week[2])
2084 year = randint(1900, 2100)
2085 month = randint(1, 12)
2086 day = randint(1, 28)
2087 dt = DateTime(year, month, day)
2088 dayNum = dt.day_of_year
2089 weekNum = dt.iso_week[1]
2090 weekNumMonth = GetMonthWeek(dt)
2093 dtSunday = GetLastSundayBefore(dt)
2095 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
2096 weekNumMonth2 = weekNumMonth2 + 1
2097 dtSunday = dtSunday - DateTimeDelta(7)
2099 data = { 'day': rjust(`day`, 2), \
2100 'month': monthNames[month - 1], \
2102 'weekNum': rjust(`weekNum`, 2), \
2103 'weekNumMonth': weekNumMonth, \
2104 'weekNumMonth2': weekNumMonth2, \
2105 'dayNum': rjust(`dayNum`, 3) }
2107 print " { { %(day)s, "\
2108 "wxDateTime::%(month)s, "\
2111 "%(weekNumMonth)s, "\
2112 "%(weekNumMonth2)s, "\
2113 "%(dayNum)s }," % data
2116 static const WeekNumberTestData weekNumberTestDates
[] =
2118 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
2119 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
2120 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
2121 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
2122 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
2123 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
2124 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
2125 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
2126 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
2127 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
2128 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
2129 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
2130 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
2131 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
2132 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
2133 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
2134 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
2135 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
2136 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
2137 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
2140 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
2142 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
2143 const Date
& d
= wn
.date
;
2145 wxDateTime dt
= d
.DT();
2147 wxDateTime::wxDateTime_t
2148 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
2149 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2150 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2151 dnum
= dt
.GetDayOfYear();
2153 printf("%s: the day number is %d",
2154 d
.FormatDate().c_str(), dnum
);
2155 if ( dnum
== wn
.dnum
)
2161 printf(" (ERROR: should be %d)", wn
.dnum
);
2164 printf(", week in month is %d", wmon
);
2165 if ( wmon
== wn
.wmon
)
2171 printf(" (ERROR: should be %d)", wn
.wmon
);
2174 printf(" or %d", wmon2
);
2175 if ( wmon2
== wn
.wmon2
)
2181 printf(" (ERROR: should be %d)", wn
.wmon2
);
2184 printf(", week in year is %d", week
);
2185 if ( week
== wn
.week
)
2191 printf(" (ERROR: should be %d)\n", wn
.week
);
2196 // test DST calculations
2197 static void TestTimeDST()
2199 puts("\n*** wxDateTime DST test ***");
2201 printf("DST is%s in effect now.\n\n",
2202 wxDateTime::Now().IsDST() ? "" : " not");
2204 // taken from http://www.energy.ca.gov/daylightsaving.html
2205 static const Date datesDST
[2][2004 - 1900 + 1] =
2208 { 1, wxDateTime::Apr
, 1990 },
2209 { 7, wxDateTime::Apr
, 1991 },
2210 { 5, wxDateTime::Apr
, 1992 },
2211 { 4, wxDateTime::Apr
, 1993 },
2212 { 3, wxDateTime::Apr
, 1994 },
2213 { 2, wxDateTime::Apr
, 1995 },
2214 { 7, wxDateTime::Apr
, 1996 },
2215 { 6, wxDateTime::Apr
, 1997 },
2216 { 5, wxDateTime::Apr
, 1998 },
2217 { 4, wxDateTime::Apr
, 1999 },
2218 { 2, wxDateTime::Apr
, 2000 },
2219 { 1, wxDateTime::Apr
, 2001 },
2220 { 7, wxDateTime::Apr
, 2002 },
2221 { 6, wxDateTime::Apr
, 2003 },
2222 { 4, wxDateTime::Apr
, 2004 },
2225 { 28, wxDateTime::Oct
, 1990 },
2226 { 27, wxDateTime::Oct
, 1991 },
2227 { 25, wxDateTime::Oct
, 1992 },
2228 { 31, wxDateTime::Oct
, 1993 },
2229 { 30, wxDateTime::Oct
, 1994 },
2230 { 29, wxDateTime::Oct
, 1995 },
2231 { 27, wxDateTime::Oct
, 1996 },
2232 { 26, wxDateTime::Oct
, 1997 },
2233 { 25, wxDateTime::Oct
, 1998 },
2234 { 31, wxDateTime::Oct
, 1999 },
2235 { 29, wxDateTime::Oct
, 2000 },
2236 { 28, wxDateTime::Oct
, 2001 },
2237 { 27, wxDateTime::Oct
, 2002 },
2238 { 26, wxDateTime::Oct
, 2003 },
2239 { 31, wxDateTime::Oct
, 2004 },
2244 for ( year
= 1990; year
< 2005; year
++ )
2246 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
2247 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
2249 printf("DST period in the US for year %d: from %s to %s",
2250 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
2252 size_t n
= year
- 1990;
2253 const Date
& dBegin
= datesDST
[0][n
];
2254 const Date
& dEnd
= datesDST
[1][n
];
2256 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
2262 printf(" (ERROR: should be %s %d to %s %d)\n",
2263 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
2264 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
2270 for ( year
= 1990; year
< 2005; year
++ )
2272 printf("DST period in Europe for year %d: from %s to %s\n",
2274 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
2275 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
2279 // test wxDateTime -> text conversion
2280 static void TestTimeFormat()
2282 puts("\n*** wxDateTime formatting test ***");
2284 // some information may be lost during conversion, so store what kind
2285 // of info should we recover after a round trip
2288 CompareNone
, // don't try comparing
2289 CompareBoth
, // dates and times should be identical
2290 CompareDate
, // dates only
2291 CompareTime
// time only
2296 CompareKind compareKind
;
2298 } formatTestFormats
[] =
2300 { CompareBoth
, "---> %c" },
2301 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
2302 { CompareBoth
, "Date is %x, time is %X" },
2303 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
2304 { CompareNone
, "The day of year: %j, the week of year: %W" },
2305 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
2308 static const Date formatTestDates
[] =
2310 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
2311 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
2313 // this test can't work for other centuries because it uses two digit
2314 // years in formats, so don't even try it
2315 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
2316 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
2317 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
2321 // an extra test (as it doesn't depend on date, don't do it in the loop)
2322 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
2324 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
2328 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
2329 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
2331 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
2332 printf("%s", s
.c_str());
2334 // what can we recover?
2335 int kind
= formatTestFormats
[n
].compareKind
;
2339 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
2342 // converion failed - should it have?
2343 if ( kind
== CompareNone
)
2346 puts(" (ERROR: conversion back failed)");
2350 // should have parsed the entire string
2351 puts(" (ERROR: conversion back stopped too soon)");
2355 bool equal
= FALSE
; // suppress compilaer warning
2363 equal
= dt
.IsSameDate(dt2
);
2367 equal
= dt
.IsSameTime(dt2
);
2373 printf(" (ERROR: got back '%s' instead of '%s')\n",
2374 dt2
.Format().c_str(), dt
.Format().c_str());
2385 // test text -> wxDateTime conversion
2386 static void TestTimeParse()
2388 puts("\n*** wxDateTime parse test ***");
2390 struct ParseTestData
2397 static const ParseTestData parseTestDates
[] =
2399 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
2400 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
2403 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
2405 const char *format
= parseTestDates
[n
].format
;
2407 printf("%s => ", format
);
2410 if ( dt
.ParseRfc822Date(format
) )
2412 printf("%s ", dt
.Format().c_str());
2414 if ( parseTestDates
[n
].good
)
2416 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
2423 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
2428 puts("(ERROR: bad format)");
2433 printf("bad format (%s)\n",
2434 parseTestDates
[n
].good
? "ERROR" : "ok");
2439 static void TestInteractive()
2441 puts("\n*** interactive wxDateTime tests ***");
2447 printf("Enter a date: ");
2448 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2451 // kill the last '\n'
2452 buf
[strlen(buf
) - 1] = 0;
2455 const char *p
= dt
.ParseDate(buf
);
2458 printf("ERROR: failed to parse the date '%s'.\n", buf
);
2464 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
2467 printf("%s: day %u, week of month %u/%u, week of year %u\n",
2468 dt
.Format("%b %d, %Y").c_str(),
2470 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2471 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2472 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
2475 puts("\n*** done ***");
2478 static void TestTimeMS()
2480 puts("*** testing millisecond-resolution support in wxDateTime ***");
2482 wxDateTime dt1
= wxDateTime::Now(),
2483 dt2
= wxDateTime::UNow();
2485 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
2486 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
2487 printf("Difference is %s\n", (dt2
- dt1
).Format("%l").c_str());
2489 puts("\n*** done ***");
2492 static void TestTimeArithmetics()
2494 puts("\n*** testing arithmetic operations on wxDateTime ***");
2496 static const struct ArithmData
2498 ArithmData(const wxDateSpan
& sp
, const char *nam
)
2499 : span(sp
), name(nam
) { }
2503 } testArithmData
[] =
2505 ArithmData(wxDateSpan::Day(), "day"),
2506 ArithmData(wxDateSpan::Week(), "week"),
2507 ArithmData(wxDateSpan::Month(), "month"),
2508 ArithmData(wxDateSpan::Year(), "year"),
2509 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
2512 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
2514 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
2516 wxDateSpan span
= testArithmData
[n
].span
;
2520 const char *name
= testArithmData
[n
].name
;
2521 printf("%s + %s = %s, %s - %s = %s\n",
2522 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
2523 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
2525 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
2526 if ( dt1
- span
== dt
)
2532 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
2535 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
2536 if ( dt2
+ span
== dt
)
2542 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
2545 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
2546 if ( dt2
+ 2*span
== dt1
)
2552 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
2559 static void TestTimeHolidays()
2561 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
2563 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
2564 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
2565 dtEnd
= dtStart
.GetLastMonthDay();
2567 wxDateTimeArray hol
;
2568 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
2570 const wxChar
*format
= "%d-%b-%Y (%a)";
2572 printf("All holidays between %s and %s:\n",
2573 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
2575 size_t count
= hol
.GetCount();
2576 for ( size_t n
= 0; n
< count
; n
++ )
2578 printf("\t%s\n", hol
[n
].Format(format
).c_str());
2584 static void TestTimeZoneBug()
2586 puts("\n*** testing for DST/timezone bug ***\n");
2588 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
2589 for ( int i
= 0; i
< 31; i
++ )
2591 printf("Date %s: week day %s.\n",
2592 date
.Format(_T("%d-%m-%Y")).c_str(),
2593 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
2595 date
+= wxDateSpan::Day();
2603 // test compatibility with the old wxDate/wxTime classes
2604 static void TestTimeCompatibility()
2606 puts("\n*** wxDateTime compatibility test ***");
2608 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
2609 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
2611 double jdnNow
= wxDateTime::Now().GetJDN();
2612 long jdnMidnight
= (long)(jdnNow
- 0.5);
2613 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
2615 jdnMidnight
= wxDate().Set().GetJulianDate();
2616 printf("wxDateTime for today: %s\n",
2617 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
2619 int flags
= wxEUROPEAN
;//wxFULL;
2622 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
2623 for ( int n
= 0; n
< 7; n
++ )
2625 printf("Previous %s is %s\n",
2626 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
2627 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
2633 #endif // TEST_DATETIME
2635 // ----------------------------------------------------------------------------
2637 // ----------------------------------------------------------------------------
2641 #include <wx/thread.h>
2643 static size_t gs_counter
= (size_t)-1;
2644 static wxCriticalSection gs_critsect
;
2645 static wxCondition gs_cond
;
2647 class MyJoinableThread
: public wxThread
2650 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
2651 { m_n
= n
; Create(); }
2653 // thread execution starts here
2654 virtual ExitCode
Entry();
2660 wxThread::ExitCode
MyJoinableThread::Entry()
2662 unsigned long res
= 1;
2663 for ( size_t n
= 1; n
< m_n
; n
++ )
2667 // it's a loooong calculation :-)
2671 return (ExitCode
)res
;
2674 class MyDetachedThread
: public wxThread
2677 MyDetachedThread(size_t n
, char ch
)
2681 m_cancelled
= FALSE
;
2686 // thread execution starts here
2687 virtual ExitCode
Entry();
2690 virtual void OnExit();
2693 size_t m_n
; // number of characters to write
2694 char m_ch
; // character to write
2696 bool m_cancelled
; // FALSE if we exit normally
2699 wxThread::ExitCode
MyDetachedThread::Entry()
2702 wxCriticalSectionLocker
lock(gs_critsect
);
2703 if ( gs_counter
== (size_t)-1 )
2709 for ( size_t n
= 0; n
< m_n
; n
++ )
2711 if ( TestDestroy() )
2721 wxThread::Sleep(100);
2727 void MyDetachedThread::OnExit()
2729 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
2731 wxCriticalSectionLocker
lock(gs_critsect
);
2732 if ( !--gs_counter
&& !m_cancelled
)
2736 void TestDetachedThreads()
2738 puts("\n*** Testing detached threads ***");
2740 static const size_t nThreads
= 3;
2741 MyDetachedThread
*threads
[nThreads
];
2743 for ( n
= 0; n
< nThreads
; n
++ )
2745 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
2748 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
2749 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
2751 for ( n
= 0; n
< nThreads
; n
++ )
2756 // wait until all threads terminate
2762 void TestJoinableThreads()
2764 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
2766 // calc 10! in the background
2767 MyJoinableThread
thread(10);
2770 printf("\nThread terminated with exit code %lu.\n",
2771 (unsigned long)thread
.Wait());
2774 void TestThreadSuspend()
2776 puts("\n*** Testing thread suspend/resume functions ***");
2778 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
2782 // this is for this demo only, in a real life program we'd use another
2783 // condition variable which would be signaled from wxThread::Entry() to
2784 // tell us that the thread really started running - but here just wait a
2785 // bit and hope that it will be enough (the problem is, of course, that
2786 // the thread might still not run when we call Pause() which will result
2788 wxThread::Sleep(300);
2790 for ( size_t n
= 0; n
< 3; n
++ )
2794 puts("\nThread suspended");
2797 // don't sleep but resume immediately the first time
2798 wxThread::Sleep(300);
2800 puts("Going to resume the thread");
2805 puts("Waiting until it terminates now");
2807 // wait until the thread terminates
2813 void TestThreadDelete()
2815 // As above, using Sleep() is only for testing here - we must use some
2816 // synchronisation object instead to ensure that the thread is still
2817 // running when we delete it - deleting a detached thread which already
2818 // terminated will lead to a crash!
2820 puts("\n*** Testing thread delete function ***");
2822 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
2826 puts("\nDeleted a thread which didn't start to run yet.");
2828 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
2832 wxThread::Sleep(300);
2836 puts("\nDeleted a running thread.");
2838 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
2842 wxThread::Sleep(300);
2848 puts("\nDeleted a sleeping thread.");
2850 MyJoinableThread
thread3(20);
2855 puts("\nDeleted a joinable thread.");
2857 MyJoinableThread
thread4(2);
2860 wxThread::Sleep(300);
2864 puts("\nDeleted a joinable thread which already terminated.");
2869 #endif // TEST_THREADS
2871 // ----------------------------------------------------------------------------
2873 // ----------------------------------------------------------------------------
2877 static void PrintArray(const char* name
, const wxArrayString
& array
)
2879 printf("Dump of the array '%s'\n", name
);
2881 size_t nCount
= array
.GetCount();
2882 for ( size_t n
= 0; n
< nCount
; n
++ )
2884 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
2888 static int StringLenCompare(const wxString
& first
, const wxString
& second
)
2890 return first
.length() - second
.length();
2893 #include "wx/dynarray.h"
2895 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
2896 #include "wx/arrimpl.cpp"
2897 WX_DEFINE_OBJARRAY(ArrayBars
);
2899 static void TestArrayOfObjects()
2901 puts("*** Testing wxObjArray ***\n");
2905 Bar
bar("second bar");
2907 printf("Initially: %u objects in the array, %u objects total.\n",
2908 bars
.GetCount(), Bar::GetNumber());
2910 bars
.Add(new Bar("first bar"));
2913 printf("Now: %u objects in the array, %u objects total.\n",
2914 bars
.GetCount(), Bar::GetNumber());
2918 printf("After Empty(): %u objects in the array, %u objects total.\n",
2919 bars
.GetCount(), Bar::GetNumber());
2922 printf("Finally: no more objects in the array, %u objects total.\n",
2926 #endif // TEST_ARRAYS
2928 // ----------------------------------------------------------------------------
2930 // ----------------------------------------------------------------------------
2934 #include "wx/timer.h"
2935 #include "wx/tokenzr.h"
2937 static void TestStringConstruction()
2939 puts("*** Testing wxString constructores ***");
2941 #define TEST_CTOR(args, res) \
2944 printf("wxString%s = %s ", #args, s.c_str()); \
2951 printf("(ERROR: should be %s)\n", res); \
2955 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
2956 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
2957 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
2958 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
2960 static const wxChar
*s
= _T("?really!");
2961 const wxChar
*start
= wxStrchr(s
, _T('r'));
2962 const wxChar
*end
= wxStrchr(s
, _T('!'));
2963 TEST_CTOR((start
, end
), _T("really"));
2968 static void TestString()
2978 for (int i
= 0; i
< 1000000; ++i
)
2982 c
= "! How'ya doin'?";
2985 c
= "Hello world! What's up?";
2990 printf ("TestString elapsed time: %ld\n", sw
.Time());
2993 static void TestPChar()
3001 for (int i
= 0; i
< 1000000; ++i
)
3003 strcpy (a
, "Hello");
3004 strcpy (b
, " world");
3005 strcpy (c
, "! How'ya doin'?");
3008 strcpy (c
, "Hello world! What's up?");
3009 if (strcmp (c
, a
) == 0)
3013 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
3016 static void TestStringSub()
3018 wxString
s("Hello, world!");
3020 puts("*** Testing wxString substring extraction ***");
3022 printf("String = '%s'\n", s
.c_str());
3023 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
3024 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
3025 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
3026 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
3027 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
3028 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
3030 static const wxChar
*prefixes
[] =
3034 _T("Hello, world!"),
3035 _T("Hello, world!!!"),
3041 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
3043 wxString prefix
= prefixes
[n
], rest
;
3044 bool rc
= s
.StartsWith(prefix
, &rest
);
3045 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
3048 printf(" (the rest is '%s')\n", rest
.c_str());
3059 static void TestStringFormat()
3061 puts("*** Testing wxString formatting ***");
3064 s
.Printf("%03d", 18);
3066 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
3067 printf("Number 18: %s\n", s
.c_str());
3072 // returns "not found" for npos, value for all others
3073 static wxString
PosToString(size_t res
)
3075 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
3076 : wxString::Format(_T("%u"), res
);
3080 static void TestStringFind()
3082 puts("*** Testing wxString find() functions ***");
3084 static const wxChar
*strToFind
= _T("ell");
3085 static const struct StringFindTest
3089 result
; // of searching "ell" in str
3092 { _T("Well, hello world"), 0, 1 },
3093 { _T("Well, hello world"), 6, 7 },
3094 { _T("Well, hello world"), 9, wxString::npos
},
3097 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
3099 const StringFindTest
& ft
= findTestData
[n
];
3100 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
3102 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
3103 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
3105 size_t resTrue
= ft
.result
;
3106 if ( res
== resTrue
)
3112 printf(_T("(ERROR: should be %s)\n"),
3113 PosToString(resTrue
).c_str());
3120 static void TestStringTokenizer()
3122 puts("*** Testing wxStringTokenizer ***");
3124 static const wxChar
*modeNames
[] =
3128 _T("return all empty"),
3133 static const struct StringTokenizerTest
3135 const wxChar
*str
; // string to tokenize
3136 const wxChar
*delims
; // delimiters to use
3137 size_t count
; // count of token
3138 wxStringTokenizerMode mode
; // how should we tokenize it
3139 } tokenizerTestData
[] =
3141 { _T(""), _T(" "), 0 },
3142 { _T("Hello, world"), _T(" "), 2 },
3143 { _T("Hello, world "), _T(" "), 2 },
3144 { _T("Hello, world"), _T(","), 2 },
3145 { _T("Hello, world!"), _T(",!"), 2 },
3146 { _T("Hello,, world!"), _T(",!"), 3 },
3147 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
3148 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
3149 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
3150 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
3151 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
3152 { _T("01/02/99"), _T("/-"), 3 },
3153 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
3156 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
3158 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
3159 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
3161 size_t count
= tkz
.CountTokens();
3162 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
3163 MakePrintable(tt
.str
).c_str(),
3165 MakePrintable(tt
.delims
).c_str(),
3166 modeNames
[tkz
.GetMode()]);
3167 if ( count
== tt
.count
)
3173 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
3178 // if we emulate strtok(), check that we do it correctly
3179 wxChar
*buf
, *s
= NULL
, *last
;
3181 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
3183 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
3184 wxStrcpy(buf
, tt
.str
);
3186 s
= wxStrtok(buf
, tt
.delims
, &last
);
3193 // now show the tokens themselves
3195 while ( tkz
.HasMoreTokens() )
3197 wxString token
= tkz
.GetNextToken();
3199 printf(_T("\ttoken %u: '%s'"),
3201 MakePrintable(token
).c_str());
3211 printf(" (ERROR: should be %s)\n", s
);
3214 s
= wxStrtok(NULL
, tt
.delims
, &last
);
3218 // nothing to compare with
3223 if ( count2
!= count
)
3225 puts(_T("\tERROR: token count mismatch"));
3234 static void TestStringReplace()
3236 puts("*** Testing wxString::replace ***");
3238 static const struct StringReplaceTestData
3240 const wxChar
*original
; // original test string
3241 size_t start
, len
; // the part to replace
3242 const wxChar
*replacement
; // the replacement string
3243 const wxChar
*result
; // and the expected result
3244 } stringReplaceTestData
[] =
3246 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
3247 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
3248 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
3249 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
3250 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
3253 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
3255 const StringReplaceTestData data
= stringReplaceTestData
[n
];
3257 wxString original
= data
.original
;
3258 original
.replace(data
.start
, data
.len
, data
.replacement
);
3260 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
3261 data
.original
, data
.start
, data
.len
, data
.replacement
,
3264 if ( original
== data
.result
)
3270 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
3277 #endif // TEST_STRINGS
3279 // ----------------------------------------------------------------------------
3281 // ----------------------------------------------------------------------------
3283 int main(int argc
, char **argv
)
3285 if ( !wxInitialize() )
3287 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
3291 puts("Sleeping for 3 seconds... z-z-z-z-z...");
3293 #endif // TEST_USLEEP
3296 static const wxCmdLineEntryDesc cmdLineDesc
[] =
3298 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
3299 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
3301 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
3302 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
3303 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
3304 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
3306 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
3307 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
3312 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
3314 parser
.AddOption("project_name", "", "full path to project file",
3315 wxCMD_LINE_VAL_STRING
,
3316 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
3318 switch ( parser
.Parse() )
3321 wxLogMessage("Help was given, terminating.");
3325 ShowCmdLine(parser
);
3329 wxLogMessage("Syntax error detected, aborting.");
3332 #endif // TEST_CMDLINE
3343 TestStringConstruction();
3346 TestStringTokenizer();
3347 TestStringReplace();
3349 #endif // TEST_STRINGS
3360 puts("*** Initially:");
3362 PrintArray("a1", a1
);
3364 wxArrayString
a2(a1
);
3365 PrintArray("a2", a2
);
3367 wxSortedArrayString
a3(a1
);
3368 PrintArray("a3", a3
);
3370 puts("*** After deleting a string from a1");
3373 PrintArray("a1", a1
);
3374 PrintArray("a2", a2
);
3375 PrintArray("a3", a3
);
3377 puts("*** After reassigning a1 to a2 and a3");
3379 PrintArray("a2", a2
);
3380 PrintArray("a3", a3
);
3382 puts("*** After sorting a1");
3384 PrintArray("a1", a1
);
3386 puts("*** After sorting a1 in reverse order");
3388 PrintArray("a1", a1
);
3390 puts("*** After sorting a1 by the string length");
3391 a1
.Sort(StringLenCompare
);
3392 PrintArray("a1", a1
);
3394 TestArrayOfObjects();
3395 #endif // TEST_ARRAYS
3401 #ifdef TEST_DLLLOADER
3403 #endif // TEST_DLLLOADER
3407 #endif // TEST_EXECUTE
3409 #ifdef TEST_FILECONF
3411 #endif // TEST_FILECONF
3419 for ( size_t n
= 0; n
< 8000; n
++ )
3421 s
<< (char)('A' + (n
% 26));
3425 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
3427 // this one shouldn't be truncated
3430 // but this one will because log functions use fixed size buffer
3431 // (note that it doesn't need '\n' at the end neither - will be added
3433 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
3442 int nCPUs
= wxThread::GetCPUCount();
3443 printf("This system has %d CPUs\n", nCPUs
);
3445 wxThread::SetConcurrency(nCPUs
);
3447 if ( argc
> 1 && argv
[1][0] == 't' )
3448 wxLog::AddTraceMask("thread");
3451 TestDetachedThreads();
3453 TestJoinableThreads();
3455 TestThreadSuspend();
3459 #endif // TEST_THREADS
3461 #ifdef TEST_LONGLONG
3462 // seed pseudo random generator
3463 srand((unsigned)time(NULL
));
3471 TestMultiplication();
3474 TestLongLongConversion();
3475 TestBitOperations();
3477 TestLongLongComparison();
3478 #endif // TEST_LONGLONG
3485 wxLog::AddTraceMask(_T("mime"));
3492 #ifdef TEST_INFO_FUNCTIONS
3495 #endif // TEST_INFO_FUNCTIONS
3504 TestProtocolFtpUpload();
3505 #endif // TEST_SOCKETS
3509 #endif // TEST_TIMER
3511 #ifdef TEST_DATETIME
3524 TestTimeArithmetics();
3533 #endif // TEST_DATETIME
3539 #endif // TEST_VCARD
3543 #endif // TEST_WCHAR
3546 TestZipStreamRead();