]> git.saurik.com Git - wxWidgets.git/blame - samples/console/console.cpp
oops, compilation error - fixed
[wxWidgets.git] / samples / console / console.cpp
CommitLineData
37667812
VZ
1/////////////////////////////////////////////////////////////////////////////
2// Name: samples/console/console.cpp
3// Purpose: a sample console (as opposed to GUI) progam using wxWindows
4// Author: Vadim Zeitlin
5// Modified by:
6// Created: 04.10.99
7// RCS-ID: $Id$
8// Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9// Licence: wxWindows license
10/////////////////////////////////////////////////////////////////////////////
11
e87271f3
VZ
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
37667812
VZ
20#include <stdio.h>
21
22#include <wx/string.h>
bbfa0322 23#include <wx/file.h>
37667812 24#include <wx/app.h>
e87271f3 25
d31b7b68
VZ
26// without this pragma, the stupid compiler precompiles #defines below so that
27// changing them doesn't "take place" later!
28#ifdef __VISUALC__
29 #pragma hdrstop
30#endif
31
e87271f3
VZ
32// ----------------------------------------------------------------------------
33// conditional compilation
34// ----------------------------------------------------------------------------
35
d31b7b68 36// what to test (in alphabetic order)?
378b05f7 37
bbf8fc53
VZ
38//#define TEST_ARRAYS
39//#define TEST_CMDLINE
d31b7b68 40//#define TEST_DATETIME
bbf8fc53 41//#define TEST_DIR
d31b7b68 42//#define TEST_EXECUTE
2c8e4738
VZ
43//#define TEST_FILECONF
44//#define TEST_HASH
bbf8fc53
VZ
45//#define TEST_LOG
46//#define TEST_LONGLONG
47//#define TEST_MIME
8e907a13 48#define TEST_SOCKETS
ee6e1b1d 49//#define TEST_STRINGS
bbf8fc53 50//#define TEST_THREADS
8e907a13 51//#define TEST_TIMER
e87271f3
VZ
52
53// ============================================================================
54// implementation
55// ============================================================================
56
8e907a13
VZ
57// ----------------------------------------------------------------------------
58// helper functions
59// ----------------------------------------------------------------------------
60
61#if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
62
63// replace TABs with \t and CRs with \n
64static wxString MakePrintable(const wxChar *s)
65{
66 wxString str(s);
67 (void)str.Replace(_T("\t"), _T("\\t"));
68 (void)str.Replace(_T("\n"), _T("\\n"));
69 (void)str.Replace(_T("\r"), _T("\\r"));
70
71 return str;
72}
73
74#endif // MakePrintable() is used
75
d34bce84
VZ
76// ----------------------------------------------------------------------------
77// wxCmdLineParser
78// ----------------------------------------------------------------------------
79
d31b7b68
VZ
80#ifdef TEST_CMDLINE
81
d34bce84
VZ
82#include <wx/cmdline.h>
83#include <wx/datetime.h>
84
85static void ShowCmdLine(const wxCmdLineParser& parser)
86{
87 wxString s = "Input files: ";
88
89 size_t count = parser.GetParamCount();
90 for ( size_t param = 0; param < count; param++ )
91 {
92 s << parser.GetParam(param) << ' ';
93 }
94
95 s << '\n'
96 << "Verbose:\t" << (parser.Found("v") ? "yes" : "no") << '\n'
97 << "Quiet:\t" << (parser.Found("q") ? "yes" : "no") << '\n';
98
99 wxString strVal;
100 long lVal;
101 wxDateTime dt;
102 if ( parser.Found("o", &strVal) )
103 s << "Output file:\t" << strVal << '\n';
104 if ( parser.Found("i", &strVal) )
105 s << "Input dir:\t" << strVal << '\n';
106 if ( parser.Found("s", &lVal) )
107 s << "Size:\t" << lVal << '\n';
108 if ( parser.Found("d", &dt) )
109 s << "Date:\t" << dt.FormatISODate() << '\n';
110
111 wxLogMessage(s);
112}
113
114#endif // TEST_CMDLINE
115
1944c6bd
VZ
116// ----------------------------------------------------------------------------
117// wxDir
118// ----------------------------------------------------------------------------
119
120#ifdef TEST_DIR
121
122#include <wx/dir.h>
123
124static void TestDirEnumHelper(wxDir& dir,
125 int flags = wxDIR_DEFAULT,
126 const wxString& filespec = wxEmptyString)
127{
128 wxString filename;
129
130 if ( !dir.IsOpened() )
131 return;
132
133 bool cont = dir.GetFirst(&filename, filespec, flags);
134 while ( cont )
135 {
136 printf("\t%s\n", filename.c_str());
137
138 cont = dir.GetNext(&filename);
139 }
140
141 puts("");
142}
143
144static void TestDirEnum()
145{
146 wxDir dir(wxGetCwd());
147
148 puts("Enumerating everything in current directory:");
149 TestDirEnumHelper(dir);
150
151 puts("Enumerating really everything in current directory:");
152 TestDirEnumHelper(dir, wxDIR_DEFAULT | wxDIR_DOTDOT);
153
154 puts("Enumerating object files in current directory:");
155 TestDirEnumHelper(dir, wxDIR_DEFAULT, "*.o");
156
157 puts("Enumerating directories in current directory:");
158 TestDirEnumHelper(dir, wxDIR_DIRS);
159
160 puts("Enumerating files in current directory:");
161 TestDirEnumHelper(dir, wxDIR_FILES);
162
163 puts("Enumerating files including hidden in current directory:");
164 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
165
166#ifdef __UNIX__
167 dir.Open("/");
168#elif defined(__WXMSW__)
169 dir.Open("c:\\");
170#else
171 #error "don't know where the root directory is"
172#endif
173
174 puts("Enumerating everything in root directory:");
175 TestDirEnumHelper(dir, wxDIR_DEFAULT);
176
177 puts("Enumerating directories in root directory:");
178 TestDirEnumHelper(dir, wxDIR_DIRS);
179
180 puts("Enumerating files in root directory:");
181 TestDirEnumHelper(dir, wxDIR_FILES);
182
183 puts("Enumerating files including hidden in root directory:");
184 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
185
186 puts("Enumerating files in non existing directory:");
187 wxDir dirNo("nosuchdir");
188 TestDirEnumHelper(dirNo);
189}
190
191#endif // TEST_DIR
192
d93c719a
VZ
193// ----------------------------------------------------------------------------
194// wxExecute
195// ----------------------------------------------------------------------------
196
197#ifdef TEST_EXECUTE
198
199#include <wx/utils.h>
200
201static void TestExecute()
202{
203 puts("*** testing wxExecute ***");
204
205#ifdef __UNIX__
206 #define COMMAND "echo hi"
2c8e4738
VZ
207 #define SHELL_COMMAND "echo hi from shell"
208 #define REDIRECT_COMMAND "date"
d93c719a
VZ
209#elif defined(__WXMSW__)
210 #define COMMAND "command.com -c 'echo hi'"
2c8e4738
VZ
211 #define SHELL_COMMAND "echo hi"
212 #define REDIRECT_COMMAND COMMAND
d93c719a
VZ
213#else
214 #error "no command to exec"
215#endif // OS
216
2c8e4738
VZ
217 printf("Testing wxShell: ");
218 fflush(stdout);
219 if ( wxShell(SHELL_COMMAND) )
220 puts("Ok.");
d93c719a 221 else
2c8e4738
VZ
222 puts("ERROR.");
223
224 printf("Testing wxExecute: ");
225 fflush(stdout);
226 if ( wxExecute(COMMAND, TRUE /* sync */) == 0 )
227 puts("Ok.");
228 else
229 puts("ERROR.");
230
231#if 0 // no, it doesn't work (yet?)
232 printf("Testing async wxExecute: ");
233 fflush(stdout);
234 if ( wxExecute(COMMAND) != 0 )
235 puts("Ok (command launched).");
236 else
237 puts("ERROR.");
238#endif // 0
239
240 printf("Testing wxExecute with redirection:\n");
241 wxArrayString output;
242 if ( wxExecute(REDIRECT_COMMAND, output) != 0 )
243 {
244 puts("ERROR.");
245 }
246 else
247 {
248 size_t count = output.GetCount();
249 for ( size_t n = 0; n < count; n++ )
250 {
251 printf("\t%s\n", output[n].c_str());
252 }
253
254 puts("Ok.");
255 }
d93c719a
VZ
256}
257
258#endif // TEST_EXECUTE
259
ee6e1b1d
VZ
260// ----------------------------------------------------------------------------
261// wxFileConfig
262// ----------------------------------------------------------------------------
263
264#ifdef TEST_FILECONF
265
266#include <wx/confbase.h>
267#include <wx/fileconf.h>
268
269static const struct FileConfTestData
270{
271 const wxChar *name; // value name
272 const wxChar *value; // the value from the file
273} fcTestData[] =
274{
275 { _T("value1"), _T("one") },
276 { _T("value2"), _T("two") },
277 { _T("novalue"), _T("default") },
278};
279
280static void TestFileConfRead()
281{
282 puts("*** testing wxFileConfig loading/reading ***");
283
284 wxFileConfig fileconf(_T("test"), wxEmptyString,
285 _T("testdata.fc"), wxEmptyString,
286 wxCONFIG_USE_RELATIVE_PATH);
287
288 // test simple reading
289 puts("\nReading config file:");
290 wxString defValue(_T("default")), value;
291 for ( size_t n = 0; n < WXSIZEOF(fcTestData); n++ )
292 {
293 const FileConfTestData& data = fcTestData[n];
294 value = fileconf.Read(data.name, defValue);
295 printf("\t%s = %s ", data.name, value.c_str());
296 if ( value == data.value )
297 {
298 puts("(ok)");
299 }
300 else
301 {
302 printf("(ERROR: should be %s)\n", data.value);
303 }
304 }
305
306 // test enumerating the entries
307 puts("\nEnumerating all root entries:");
308 long dummy;
309 wxString name;
310 bool cont = fileconf.GetFirstEntry(name, dummy);
311 while ( cont )
312 {
313 printf("\t%s = %s\n",
314 name.c_str(),
315 fileconf.Read(name.c_str(), _T("ERROR")).c_str());
316
317 cont = fileconf.GetNextEntry(name, dummy);
318 }
319}
320
321#endif // TEST_FILECONF
322
2c8e4738
VZ
323// ----------------------------------------------------------------------------
324// wxHashTable
325// ----------------------------------------------------------------------------
326
327#ifdef TEST_HASH
328
329#include <wx/hash.h>
330
331struct Foo
332{
333 Foo(int n_) { n = n_; count++; }
334 ~Foo() { count--; }
335
336 int n;
337
338 static size_t count;
339};
340
341size_t Foo::count = 0;
342
343WX_DECLARE_LIST(Foo, wxListFoos);
344WX_DECLARE_HASH(Foo, wxListFoos, wxHashFoos);
345
346#include <wx/listimpl.cpp>
347
348WX_DEFINE_LIST(wxListFoos);
349
350static void TestHash()
351{
352 puts("*** Testing wxHashTable ***\n");
353
354 {
355 wxHashFoos hash;
356 hash.DeleteContents(TRUE);
357
358 printf("Hash created: %u foos in hash, %u foos totally\n",
359 hash.GetCount(), Foo::count);
360
361 static const int hashTestData[] =
362 {
363 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
364 };
365
366 size_t n;
367 for ( n = 0; n < WXSIZEOF(hashTestData); n++ )
368 {
369 hash.Put(hashTestData[n], n, new Foo(n));
370 }
371
372 printf("Hash filled: %u foos in hash, %u foos totally\n",
373 hash.GetCount(), Foo::count);
374
375 puts("Hash access test:");
376 for ( n = 0; n < WXSIZEOF(hashTestData); n++ )
377 {
378 printf("\tGetting element with key %d, value %d: ",
379 hashTestData[n], n);
380 Foo *foo = hash.Get(hashTestData[n], n);
381 if ( !foo )
382 {
383 printf("ERROR, not found.\n");
384 }
385 else
386 {
387 printf("%d (%s)\n", foo->n,
388 (size_t)foo->n == n ? "ok" : "ERROR");
389 }
390 }
391
392 printf("\nTrying to get an element not in hash: ");
393
394 if ( hash.Get(1234) || hash.Get(1, 0) )
395 {
396 puts("ERROR: found!");
397 }
398 else
399 {
400 puts("ok (not found)");
401 }
402 }
403
404 printf("Hash destroyed: %u foos left\n", Foo::count);
405}
406
407#endif // TEST_HASH
408
696e1ea0
VZ
409// ----------------------------------------------------------------------------
410// MIME types
411// ----------------------------------------------------------------------------
412
413#ifdef TEST_MIME
414
415#include <wx/mimetype.h>
416
417static void TestMimeEnum()
418{
419 wxMimeTypesManager mimeTM;
420 wxArrayString mimetypes;
421
422 size_t count = mimeTM.EnumAllFileTypes(mimetypes);
423
424 printf("*** All %u known filetypes: ***\n", count);
425
426 wxArrayString exts;
427 wxString desc;
428
429 for ( size_t n = 0; n < count; n++ )
430 {
431 wxFileType *filetype = mimeTM.GetFileTypeFromMimeType(mimetypes[n]);
432 if ( !filetype )
c61f4f6d 433 {
97e0ceea
VZ
434 printf("nothing known about the filetype '%s'!\n",
435 mimetypes[n].c_str());
696e1ea0 436 continue;
c61f4f6d
VZ
437 }
438
696e1ea0
VZ
439 filetype->GetDescription(&desc);
440 filetype->GetExtensions(exts);
441
299fcbfe
VZ
442 filetype->GetIcon(NULL);
443
696e1ea0
VZ
444 wxString extsAll;
445 for ( size_t e = 0; e < exts.GetCount(); e++ )
446 {
447 if ( e > 0 )
448 extsAll << _T(", ");
449 extsAll += exts[e];
450 }
451
54acce90
VZ
452 printf("\t%s: %s (%s)\n",
453 mimetypes[n].c_str(), desc.c_str(), extsAll.c_str());
696e1ea0
VZ
454 }
455}
456
457#endif // TEST_MIME
458
b76b015e
VZ
459// ----------------------------------------------------------------------------
460// long long
461// ----------------------------------------------------------------------------
462
463#ifdef TEST_LONGLONG
464
465#include <wx/longlong.h>
466#include <wx/timer.h>
467
2a310492
VZ
468// make a 64 bit number from 4 16 bit ones
469#define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
470
471// get a random 64 bit number
472#define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
473
7d0bb74d 474#if wxUSE_LONGLONG_WX
2a310492
VZ
475inline bool operator==(const wxLongLongWx& a, const wxLongLongNative& b)
476 { return a.GetHi() == b.GetHi() && a.GetLo() == b.GetLo(); }
477inline bool operator==(const wxLongLongNative& a, const wxLongLongWx& b)
478 { return a.GetHi() == b.GetHi() && a.GetLo() == b.GetLo(); }
7d0bb74d 479#endif // wxUSE_LONGLONG_WX
2a310492 480
b76b015e
VZ
481static void TestSpeed()
482{
483 static const long max = 100000000;
484 long n;
9fc3ad34 485
b76b015e
VZ
486 {
487 wxStopWatch sw;
488
489 long l = 0;
490 for ( n = 0; n < max; n++ )
491 {
492 l += n;
493 }
494
495 printf("Summing longs took %ld milliseconds.\n", sw.Time());
496 }
497
2ea24d9f 498#if wxUSE_LONGLONG_NATIVE
b76b015e
VZ
499 {
500 wxStopWatch sw;
501
2ea24d9f 502 wxLongLong_t l = 0;
b76b015e
VZ
503 for ( n = 0; n < max; n++ )
504 {
505 l += n;
506 }
507
2ea24d9f 508 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw.Time());
b76b015e 509 }
2ea24d9f 510#endif // wxUSE_LONGLONG_NATIVE
b76b015e
VZ
511
512 {
513 wxStopWatch sw;
514
515 wxLongLong l;
516 for ( n = 0; n < max; n++ )
517 {
518 l += n;
519 }
520
521 printf("Summing wxLongLongs took %ld milliseconds.\n", sw.Time());
522 }
523}
524
2a310492 525static void TestLongLongConversion()
b76b015e 526{
2a310492
VZ
527 puts("*** Testing wxLongLong conversions ***\n");
528
529 wxLongLong a;
530 size_t nTested = 0;
531 for ( size_t n = 0; n < 100000; n++ )
532 {
533 a = RAND_LL();
534
535#if wxUSE_LONGLONG_NATIVE
536 wxLongLongNative b(a.GetHi(), a.GetLo());
5e6a0e83 537
2a310492
VZ
538 wxASSERT_MSG( a == b, "conversions failure" );
539#else
540 puts("Can't do it without native long long type, test skipped.");
b76b015e 541
2a310492
VZ
542 return;
543#endif // wxUSE_LONGLONG_NATIVE
544
545 if ( !(nTested % 1000) )
546 {
547 putchar('.');
548 fflush(stdout);
549 }
550
551 nTested++;
552 }
553
554 puts(" done!");
555}
556
557static void TestMultiplication()
558{
559 puts("*** Testing wxLongLong multiplication ***\n");
560
561 wxLongLong a, b;
562 size_t nTested = 0;
563 for ( size_t n = 0; n < 100000; n++ )
564 {
565 a = RAND_LL();
566 b = RAND_LL();
567
568#if wxUSE_LONGLONG_NATIVE
569 wxLongLongNative aa(a.GetHi(), a.GetLo());
570 wxLongLongNative bb(b.GetHi(), b.GetLo());
571
572 wxASSERT_MSG( a*b == aa*bb, "multiplication failure" );
573#else // !wxUSE_LONGLONG_NATIVE
574 puts("Can't do it without native long long type, test skipped.");
575
576 return;
577#endif // wxUSE_LONGLONG_NATIVE
578
579 if ( !(nTested % 1000) )
580 {
581 putchar('.');
582 fflush(stdout);
583 }
584
585 nTested++;
586 }
587
588 puts(" done!");
589}
590
591static void TestDivision()
592{
593 puts("*** Testing wxLongLong division ***\n");
2f02cb89 594
2ea24d9f 595 wxLongLong q, r;
2f02cb89 596 size_t nTested = 0;
5e6a0e83 597 for ( size_t n = 0; n < 100000; n++ )
2f02cb89
VZ
598 {
599 // get a random wxLongLong (shifting by 12 the MSB ensures that the
600 // multiplication will not overflow)
601 wxLongLong ll = MAKE_LL((rand() >> 12), rand(), rand(), rand());
602
2ea24d9f
VZ
603 // get a random long (not wxLongLong for now) to divide it with
604 long l = rand();
605 q = ll / l;
606 r = ll % l;
607
2a310492
VZ
608#if wxUSE_LONGLONG_NATIVE
609 wxLongLongNative m(ll.GetHi(), ll.GetLo());
610
611 wxLongLongNative p = m / l, s = m % l;
612 wxASSERT_MSG( q == p && r == s, "division failure" );
613#else // !wxUSE_LONGLONG_NATIVE
5e6a0e83 614 // verify the result
2ea24d9f 615 wxASSERT_MSG( ll == q*l + r, "division failure" );
2a310492 616#endif // wxUSE_LONGLONG_NATIVE
2f02cb89 617
5e6a0e83
VZ
618 if ( !(nTested % 1000) )
619 {
620 putchar('.');
621 fflush(stdout);
622 }
623
2f02cb89
VZ
624 nTested++;
625 }
626
5e6a0e83 627 puts(" done!");
2a310492 628}
2f02cb89 629
2a310492
VZ
630static void TestAddition()
631{
632 puts("*** Testing wxLongLong addition ***\n");
633
634 wxLongLong a, b, c;
635 size_t nTested = 0;
636 for ( size_t n = 0; n < 100000; n++ )
637 {
638 a = RAND_LL();
639 b = RAND_LL();
640 c = a + b;
641
642#if wxUSE_LONGLONG_NATIVE
643 wxASSERT_MSG( c == wxLongLongNative(a.GetHi(), a.GetLo()) +
644 wxLongLongNative(b.GetHi(), b.GetLo()),
7c968cee 645 "addition failure" );
2a310492
VZ
646#else // !wxUSE_LONGLONG_NATIVE
647 wxASSERT_MSG( c - b == a, "addition failure" );
648#endif // wxUSE_LONGLONG_NATIVE
649
650 if ( !(nTested % 1000) )
651 {
652 putchar('.');
653 fflush(stdout);
654 }
655
656 nTested++;
657 }
658
659 puts(" done!");
b76b015e
VZ
660}
661
2a310492
VZ
662static void TestBitOperations()
663{
664 puts("*** Testing wxLongLong bit operation ***\n");
665
666 wxLongLong a, c;
667 size_t nTested = 0;
668 for ( size_t n = 0; n < 100000; n++ )
669 {
670 a = RAND_LL();
671
672#if wxUSE_LONGLONG_NATIVE
673 for ( size_t n = 0; n < 33; n++ )
674 {
675 wxLongLongNative b(a.GetHi(), a.GetLo());
676
677 b >>= n;
678 c = a >> n;
679
680 wxASSERT_MSG( b == c, "bit shift failure" );
681
682 b = wxLongLongNative(a.GetHi(), a.GetLo()) << n;
683 c = a << n;
684
685 wxASSERT_MSG( b == c, "bit shift failure" );
686 }
687
688#else // !wxUSE_LONGLONG_NATIVE
689 puts("Can't do it without native long long type, test skipped.");
690
691 return;
692#endif // wxUSE_LONGLONG_NATIVE
693
694 if ( !(nTested % 1000) )
695 {
696 putchar('.');
697 fflush(stdout);
698 }
699
700 nTested++;
701 }
702
703 puts(" done!");
704}
705
706#undef MAKE_LL
707#undef RAND_LL
708
b76b015e
VZ
709#endif // TEST_LONGLONG
710
2c8e4738
VZ
711// ----------------------------------------------------------------------------
712// sockets
713// ----------------------------------------------------------------------------
714
715#ifdef TEST_SOCKETS
716
717#include <wx/socket.h>
8e907a13
VZ
718#include <wx/protocol/protocol.h>
719#include <wx/protocol/ftp.h>
720#include <wx/protocol/http.h>
721
722static void TestSocketServer()
723{
724 puts("*** Testing wxSocketServer ***\n");
725
ccdb23df
VZ
726 static const int PORT = 3000;
727
8e907a13 728 wxIPV4address addr;
ccdb23df 729 addr.Service(PORT);
8e907a13
VZ
730
731 wxSocketServer *server = new wxSocketServer(addr);
732 if ( !server->Ok() )
733 {
734 puts("ERROR: failed to bind");
ccdb23df
VZ
735
736 return;
8e907a13 737 }
8dfea369
VZ
738
739 for ( ;; )
740 {
ccdb23df 741 printf("Server: waiting for connection on port %d...\n", PORT);
8dfea369
VZ
742
743 wxSocketBase *socket = server->Accept();
744 if ( !socket )
745 {
746 puts("ERROR: wxSocketServer::Accept() failed.");
747 break;
748 }
749
750 puts("Server: got a client.");
751
ccdb23df
VZ
752 server->SetTimeout(60); // 1 min
753
754 while ( socket->IsConnected() )
8dfea369 755 {
ccdb23df
VZ
756 wxString s;
757 char ch = '\0';
758 for ( ;; )
8dfea369 759 {
ccdb23df
VZ
760 if ( socket->Read(&ch, sizeof(ch)).Error() )
761 {
762 // don't log error if the client just close the connection
763 if ( socket->IsConnected() )
764 {
765 puts("ERROR: in wxSocket::Read.");
766 }
8dfea369 767
ccdb23df
VZ
768 break;
769 }
8dfea369 770
ccdb23df
VZ
771 if ( ch == '\r' )
772 continue;
8dfea369 773
ccdb23df
VZ
774 if ( ch == '\n' )
775 break;
8dfea369 776
ccdb23df
VZ
777 s += ch;
778 }
8dfea369 779
ccdb23df
VZ
780 if ( ch != '\n' )
781 {
782 break;
783 }
8dfea369 784
ccdb23df
VZ
785 printf("Server: got '%s'.\n", s.c_str());
786 if ( s == _T("bye") )
787 {
788 delete socket;
8dfea369 789
ccdb23df
VZ
790 break;
791 }
792
793 socket->Write(s.MakeUpper().c_str(), s.length());
794 socket->Write("\r\n", 2);
795 printf("Server: wrote '%s'.\n", s.c_str());
8dfea369
VZ
796 }
797
ccdb23df 798 puts("Server: lost a client.");
8dfea369 799
ccdb23df 800 socket->Destroy();
8dfea369 801 }
9fc3cba7 802
ccdb23df
VZ
803 // same as "delete server" but is consistent with GUI programs
804 server->Destroy();
8e907a13 805}
2c8e4738
VZ
806
807static void TestSocketClient()
808{
809 puts("*** Testing wxSocketClient ***\n");
810
8e907a13
VZ
811 static const char *hostname = "www.wxwindows.org";
812
813 wxIPV4address addr;
814 addr.Hostname(hostname);
815 addr.Service(80);
816
817 printf("--- Attempting to connect to %s:80...\n", hostname);
2c8e4738
VZ
818
819 wxSocketClient client;
8e907a13 820 if ( !client.Connect(addr) )
2c8e4738 821 {
8e907a13 822 printf("ERROR: failed to connect to %s\n", hostname);
2c8e4738
VZ
823 }
824 else
825 {
8e907a13
VZ
826 printf("--- Connected to %s:%u...\n",
827 addr.Hostname().c_str(), addr.Service());
828
2c8e4738
VZ
829 char buf[8192];
830
8e907a13
VZ
831 // could use simply "GET" here I suppose
832 wxString cmdGet =
833 wxString::Format("GET http://%s/\r\n", hostname);
834 client.Write(cmdGet, cmdGet.length());
835 printf("--- Sent command '%s' to the server\n",
836 MakePrintable(cmdGet).c_str());
2c8e4738 837 client.Read(buf, WXSIZEOF(buf));
8e907a13
VZ
838 printf("--- Server replied:\n%s", buf);
839 }
840}
841
842static void TestProtocolFtp()
843{
844 puts("*** Testing wxFTP ***\n");
845
846 wxLog::AddTraceMask(_T("ftp"));
847
848 static const char *hostname = "ftp.wxwindows.org";
849
850 printf("--- Attempting to connect to %s:21...\n", hostname);
851
852 wxFTP ftp;
853 if ( !ftp.Connect(hostname) )
854 {
855 printf("ERROR: failed to connect to %s\n", hostname);
856 }
857 else
858 {
859 printf("--- Connected to %s, current directory is '%s'\n",
860 hostname, ftp.Pwd().c_str());
861 if ( !ftp.ChDir(_T("pub")) )
862 {
863 puts("ERROR: failed to cd to pub");
864 }
865
866 wxArrayString files;
867 if ( !ftp.GetList(files) )
868 {
869 puts("ERROR: failed to get list of files");
870 }
871 else
872 {
873 printf("List of files under '%s':\n", ftp.Pwd().c_str());
874 size_t count = files.GetCount();
875 for ( size_t n = 0; n < count; n++ )
876 {
877 printf("\t%s\n", files[n].c_str());
878 }
879 puts("End of the file list");
880 }
881
882 if ( !ftp.ChDir(_T("..")) )
883 {
884 puts("ERROR: failed to cd to ..");
885 }
886
887 static const char *filename = "welcome.msg";
888 wxInputStream *in = ftp.GetInputStream(filename);
889 if ( !in )
890 {
891 puts("ERROR: couldn't get input stream");
892 }
893 else
894 {
895 size_t size = in->StreamSize();
896 printf("Reading file %s (%u bytes)...", filename, size);
897
898 char *data = new char[size];
899 if ( !in->Read(data, size) )
900 {
901 puts("ERROR: read error");
902 }
903 else
904 {
905 printf("\nContents of %s:\n%s\n", filename, data);
906 }
907
908 delete [] data;
909 delete in;
910 }
2c8e4738
VZ
911 }
912}
913
914#endif // TEST_SOCKETS
915
d31b7b68
VZ
916// ----------------------------------------------------------------------------
917// timers
918// ----------------------------------------------------------------------------
919
920#ifdef TEST_TIMER
921
922#include <wx/timer.h>
923#include <wx/utils.h>
924
925static void TestStopWatch()
926{
927 puts("*** Testing wxStopWatch ***\n");
928
929 wxStopWatch sw;
930 printf("Sleeping 3 seconds...");
931 wxSleep(3);
87798c00 932 printf("\telapsed time: %ldms\n", sw.Time());
d31b7b68
VZ
933
934 sw.Pause();
935 printf("Sleeping 2 more seconds...");
936 wxSleep(2);
87798c00 937 printf("\telapsed time: %ldms\n", sw.Time());
d31b7b68
VZ
938
939 sw.Resume();
940 printf("And 3 more seconds...");
941 wxSleep(3);
87798c00
VZ
942 printf("\telapsed time: %ldms\n", sw.Time());
943
944 wxStopWatch sw2;
945 puts("\nChecking for 'backwards clock' bug...");
946 for ( size_t n = 0; n < 70; n++ )
947 {
948 sw2.Start();
89e6463c
GRG
949
950 for ( size_t m = 0; m < 100000; m++ )
87798c00 951 {
89e6463c
GRG
952 if ( sw.Time() < 0 || sw2.Time() < 0 )
953 {
954 puts("\ntime is negative - ERROR!");
955 }
87798c00
VZ
956 }
957
958 putchar('.');
959 }
960
961 puts(", ok.");
d31b7b68
VZ
962}
963
964#endif // TEST_TIMER
965
b76b015e
VZ
966// ----------------------------------------------------------------------------
967// date time
968// ----------------------------------------------------------------------------
969
d31b7b68 970#ifdef TEST_DATETIME
b76b015e 971
97e0ceea
VZ
972#include <wx/date.h>
973
b76b015e
VZ
974#include <wx/datetime.h>
975
299fcbfe
VZ
976// the test data
977struct Date
978{
979 wxDateTime::wxDateTime_t day;
980 wxDateTime::Month month;
981 int year;
982 wxDateTime::wxDateTime_t hour, min, sec;
983 double jdn;
211c2250 984 wxDateTime::WeekDay wday;
299fcbfe
VZ
985 time_t gmticks, ticks;
986
987 void Init(const wxDateTime::Tm& tm)
988 {
989 day = tm.mday;
990 month = tm.mon;
991 year = tm.year;
992 hour = tm.hour;
993 min = tm.min;
994 sec = tm.sec;
995 jdn = 0.0;
996 gmticks = ticks = -1;
997 }
998
999 wxDateTime DT() const
1000 { return wxDateTime(day, month, year, hour, min, sec); }
1001
239446b4
VZ
1002 bool SameDay(const wxDateTime::Tm& tm) const
1003 {
1004 return day == tm.mday && month == tm.mon && year == tm.year;
1005 }
1006
299fcbfe
VZ
1007 wxString Format() const
1008 {
1009 wxString s;
1010 s.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
1011 hour, min, sec,
1012 wxDateTime::GetMonthName(month).c_str(),
1013 day,
1014 abs(wxDateTime::ConvertYearToBC(year)),
1015 year > 0 ? "AD" : "BC");
1016 return s;
1017 }
239446b4
VZ
1018
1019 wxString FormatDate() const
1020 {
1021 wxString s;
1022 s.Printf("%02d-%s-%4d%s",
1023 day,
f0f951fa 1024 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
239446b4
VZ
1025 abs(wxDateTime::ConvertYearToBC(year)),
1026 year > 0 ? "AD" : "BC");
1027 return s;
1028 }
299fcbfe
VZ
1029};
1030
1031static const Date testDates[] =
1032{
211c2250
VZ
1033 { 1, wxDateTime::Jan, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu, 0, -3600 },
1034 { 21, wxDateTime::Jan, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon, -1, -1 },
1035 { 29, wxDateTime::May, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat, 202219200, 202212000 },
1036 { 29, wxDateTime::Feb, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun, 194400000, 194396400 },
1037 { 1, wxDateTime::Jan, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon, -1, -1 },
1038 { 1, wxDateTime::Jan, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon, -1, -1 },
1039 { 15, wxDateTime::Oct, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri, -1, -1 },
1040 { 4, wxDateTime::Oct, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon, -1, -1 },
1041 { 1, wxDateTime::Mar, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu, -1, -1 },
1042 { 1, wxDateTime::Jan, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon, -1, -1 },
239446b4
VZ
1043 { 31, wxDateTime::Dec, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun, -1, -1 },
1044 { 1, wxDateTime::Jan, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat, -1, -1 },
1045 { 12, wxDateTime::Aug, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri, -1, -1 },
1046 { 12, wxDateTime::Aug, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat, -1, -1 },
211c2250 1047 { 24, wxDateTime::Nov, -4713, 00, 00, 00, -0.5, wxDateTime::Mon, -1, -1 },
299fcbfe
VZ
1048};
1049
2f02cb89
VZ
1050// this test miscellaneous static wxDateTime functions
1051static void TestTimeStatic()
1052{
1053 puts("\n*** wxDateTime static methods test ***");
1054
1055 // some info about the current date
1056 int year = wxDateTime::GetCurrentYear();
1057 printf("Current year %d is %sa leap one and has %d days.\n",
1058 year,
1059 wxDateTime::IsLeapYear(year) ? "" : "not ",
1060 wxDateTime::GetNumberOfDays(year));
1061
1062 wxDateTime::Month month = wxDateTime::GetCurrentMonth();
1063 printf("Current month is '%s' ('%s') and it has %d days\n",
f0f951fa 1064 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
2f02cb89
VZ
1065 wxDateTime::GetMonthName(month).c_str(),
1066 wxDateTime::GetNumberOfDays(month));
1067
1068 // leap year logic
fcc3d7cb
VZ
1069 static const size_t nYears = 5;
1070 static const size_t years[2][nYears] =
2f02cb89
VZ
1071 {
1072 // first line: the years to test
1073 { 1990, 1976, 2000, 2030, 1984, },
1074
1075 // second line: TRUE if leap, FALSE otherwise
1076 { FALSE, TRUE, TRUE, FALSE, TRUE }
1077 };
1078
1079 for ( size_t n = 0; n < nYears; n++ )
1080 {
1081 int year = years[0][n];
239446b4
VZ
1082 bool should = years[1][n] != 0,
1083 is = wxDateTime::IsLeapYear(year);
2f02cb89 1084
239446b4 1085 printf("Year %d is %sa leap year (%s)\n",
2f02cb89 1086 year,
239446b4
VZ
1087 is ? "" : "not ",
1088 should == is ? "ok" : "ERROR");
2f02cb89
VZ
1089
1090 wxASSERT( should == wxDateTime::IsLeapYear(year) );
1091 }
1092}
1093
1094// test constructing wxDateTime objects
1095static void TestTimeSet()
1096{
1097 puts("\n*** wxDateTime construction test ***");
1098
299fcbfe
VZ
1099 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
1100 {
1101 const Date& d1 = testDates[n];
1102 wxDateTime dt = d1.DT();
1103
1104 Date d2;
1105 d2.Init(dt.GetTm());
1106
1107 wxString s1 = d1.Format(),
1108 s2 = d2.Format();
1109
1110 printf("Date: %s == %s (%s)\n",
1111 s1.c_str(), s2.c_str(),
1112 s1 == s2 ? "ok" : "ERROR");
1113 }
2f02cb89
VZ
1114}
1115
fcc3d7cb
VZ
1116// test time zones stuff
1117static void TestTimeZones()
1118{
1119 puts("\n*** wxDateTime timezone test ***");
1120
1121 wxDateTime now = wxDateTime::Now();
1122
299fcbfe
VZ
1123 printf("Current GMT time:\t%s\n", now.Format("%c", wxDateTime::GMT0).c_str());
1124 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0).c_str());
1125 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST).c_str());
1126 printf("Current time in Paris:\t%s\n", now.Format("%c", wxDateTime::CET).c_str());
1127 printf(" Moscow:\t%s\n", now.Format("%c", wxDateTime::MSK).c_str());
1128 printf(" New York:\t%s\n", now.Format("%c", wxDateTime::EST).c_str());
9d9b7755
VZ
1129
1130 wxDateTime::Tm tm = now.GetTm();
1131 if ( wxDateTime(tm) != now )
1132 {
1133 printf("ERROR: got %s instead of %s\n",
1134 wxDateTime(tm).Format().c_str(), now.Format().c_str());
1135 }
fcc3d7cb
VZ
1136}
1137
e6ec579c
VZ
1138// test some minimal support for the dates outside the standard range
1139static void TestTimeRange()
1140{
1141 puts("\n*** wxDateTime out-of-standard-range dates test ***");
1142
211c2250
VZ
1143 static const char *fmt = "%d-%b-%Y %H:%M:%S";
1144
1ef54dcf 1145 printf("Unix epoch:\t%s\n",
211c2250 1146 wxDateTime(2440587.5).Format(fmt).c_str());
1ef54dcf 1147 printf("Feb 29, 0: \t%s\n",
211c2250 1148 wxDateTime(29, wxDateTime::Feb, 0).Format(fmt).c_str());
e6ec579c 1149 printf("JDN 0: \t%s\n",
211c2250 1150 wxDateTime(0.0).Format(fmt).c_str());
e6ec579c 1151 printf("Jan 1, 1AD:\t%s\n",
211c2250 1152 wxDateTime(1, wxDateTime::Jan, 1).Format(fmt).c_str());
e6ec579c 1153 printf("May 29, 2099:\t%s\n",
211c2250 1154 wxDateTime(29, wxDateTime::May, 2099).Format(fmt).c_str());
e6ec579c
VZ
1155}
1156
299fcbfe 1157static void TestTimeTicks()
e6ec579c 1158{
299fcbfe 1159 puts("\n*** wxDateTime ticks test ***");
e6ec579c 1160
299fcbfe 1161 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
1ef54dcf 1162 {
299fcbfe
VZ
1163 const Date& d = testDates[n];
1164 if ( d.ticks == -1 )
1165 continue;
1ef54dcf 1166
299fcbfe
VZ
1167 wxDateTime dt = d.DT();
1168 long ticks = (dt.GetValue() / 1000).ToLong();
1169 printf("Ticks of %s:\t% 10ld", d.Format().c_str(), ticks);
1170 if ( ticks == d.ticks )
1171 {
1172 puts(" (ok)");
1173 }
1174 else
1175 {
1176 printf(" (ERROR: should be %ld, delta = %ld)\n",
1177 d.ticks, ticks - d.ticks);
1178 }
1179
1180 dt = d.DT().ToTimezone(wxDateTime::GMT0);
1181 ticks = (dt.GetValue() / 1000).ToLong();
1182 printf("GMtks of %s:\t% 10ld", d.Format().c_str(), ticks);
1183 if ( ticks == d.gmticks )
1184 {
1185 puts(" (ok)");
1186 }
1187 else
1188 {
1189 printf(" (ERROR: should be %ld, delta = %ld)\n",
1190 d.gmticks, ticks - d.gmticks);
1191 }
1192 }
1193
1194 puts("");
1195}
1196
1197// test conversions to JDN &c
1198static void TestTimeJDN()
1199{
1200 puts("\n*** wxDateTime to JDN test ***");
1ef54dcf
VZ
1201
1202 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
1203 {
1204 const Date& d = testDates[n];
299fcbfe 1205 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
1ef54dcf
VZ
1206 double jdn = dt.GetJulianDayNumber();
1207
299fcbfe 1208 printf("JDN of %s is:\t% 15.6f", d.Format().c_str(), jdn);
1ef54dcf
VZ
1209 if ( jdn == d.jdn )
1210 {
1211 puts(" (ok)");
1212 }
1213 else
1214 {
1215 printf(" (ERROR: should be %f, delta = %f)\n",
1216 d.jdn, jdn - d.jdn);
1217 }
1218 }
e6ec579c
VZ
1219}
1220
211c2250
VZ
1221// test week days computation
1222static void TestTimeWDays()
1223{
1224 puts("\n*** wxDateTime weekday test ***");
1225
239446b4
VZ
1226 // test GetWeekDay()
1227 size_t n;
1228 for ( n = 0; n < WXSIZEOF(testDates); n++ )
211c2250
VZ
1229 {
1230 const Date& d = testDates[n];
1231 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
1232
1233 wxDateTime::WeekDay wday = dt.GetWeekDay();
1234 printf("%s is: %s",
1235 d.Format().c_str(),
239446b4 1236 wxDateTime::GetWeekDayName(wday).c_str());
211c2250
VZ
1237 if ( wday == d.wday )
1238 {
1239 puts(" (ok)");
1240 }
1241 else
1242 {
1243 printf(" (ERROR: should be %s)\n",
239446b4
VZ
1244 wxDateTime::GetWeekDayName(d.wday).c_str());
1245 }
1246 }
1247
1248 puts("");
1249
1250 // test SetToWeekDay()
1251 struct WeekDateTestData
1252 {
1253 Date date; // the real date (precomputed)
1254 int nWeek; // its week index in the month
1255 wxDateTime::WeekDay wday; // the weekday
1256 wxDateTime::Month month; // the month
1257 int year; // and the year
1258
1259 wxString Format() const
1260 {
1261 wxString s, which;
1262 switch ( nWeek < -1 ? -nWeek : nWeek )
1263 {
1264 case 1: which = "first"; break;
1265 case 2: which = "second"; break;
1266 case 3: which = "third"; break;
1267 case 4: which = "fourth"; break;
1268 case 5: which = "fifth"; break;
1269
1270 case -1: which = "last"; break;
1271 }
1272
1273 if ( nWeek < -1 )
1274 {
1275 which += " from end";
1276 }
1277
1278 s.Printf("The %s %s of %s in %d",
1279 which.c_str(),
1280 wxDateTime::GetWeekDayName(wday).c_str(),
1281 wxDateTime::GetMonthName(month).c_str(),
1282 year);
1283
1284 return s;
1285 }
1286 };
1287
1288 // the array data was generated by the following python program
1289 /*
1290from DateTime import *
1291from whrandom import *
1292from string import *
1293
1294monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1295wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1296
1297week = DateTimeDelta(7)
1298
1299for n in range(20):
1300 year = randint(1900, 2100)
1301 month = randint(1, 12)
1302 day = randint(1, 28)
1303 dt = DateTime(year, month, day)
1304 wday = dt.day_of_week
1305
1306 countFromEnd = choice([-1, 1])
1307 weekNum = 0;
1308
1309 while dt.month is month:
1310 dt = dt - countFromEnd * week
1311 weekNum = weekNum + countFromEnd
1312
1313 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
97e0ceea 1314
239446b4
VZ
1315 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
1316 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
97e0ceea 1317 */
239446b4
VZ
1318
1319 static const WeekDateTestData weekDatesTestData[] =
1320 {
1321 { { 20, wxDateTime::Mar, 2045 }, 3, wxDateTime::Mon, wxDateTime::Mar, 2045 },
1322 { { 5, wxDateTime::Jun, 1985 }, -4, wxDateTime::Wed, wxDateTime::Jun, 1985 },
1323 { { 12, wxDateTime::Nov, 1961 }, -3, wxDateTime::Sun, wxDateTime::Nov, 1961 },
1324 { { 27, wxDateTime::Feb, 2093 }, -1, wxDateTime::Fri, wxDateTime::Feb, 2093 },
1325 { { 4, wxDateTime::Jul, 2070 }, -4, wxDateTime::Fri, wxDateTime::Jul, 2070 },
1326 { { 2, wxDateTime::Apr, 1906 }, -5, wxDateTime::Mon, wxDateTime::Apr, 1906 },
1327 { { 19, wxDateTime::Jul, 2023 }, -2, wxDateTime::Wed, wxDateTime::Jul, 2023 },
1328 { { 5, wxDateTime::May, 1958 }, -4, wxDateTime::Mon, wxDateTime::May, 1958 },
1329 { { 11, wxDateTime::Aug, 1900 }, 2, wxDateTime::Sat, wxDateTime::Aug, 1900 },
1330 { { 14, wxDateTime::Feb, 1945 }, 2, wxDateTime::Wed, wxDateTime::Feb, 1945 },
1331 { { 25, wxDateTime::Jul, 1967 }, -1, wxDateTime::Tue, wxDateTime::Jul, 1967 },
1332 { { 9, wxDateTime::May, 1916 }, -4, wxDateTime::Tue, wxDateTime::May, 1916 },
1333 { { 20, wxDateTime::Jun, 1927 }, 3, wxDateTime::Mon, wxDateTime::Jun, 1927 },
1334 { { 2, wxDateTime::Aug, 2000 }, 1, wxDateTime::Wed, wxDateTime::Aug, 2000 },
1335 { { 20, wxDateTime::Apr, 2044 }, 3, wxDateTime::Wed, wxDateTime::Apr, 2044 },
1336 { { 20, wxDateTime::Feb, 1932 }, -2, wxDateTime::Sat, wxDateTime::Feb, 1932 },
1337 { { 25, wxDateTime::Jul, 2069 }, 4, wxDateTime::Thu, wxDateTime::Jul, 2069 },
1338 { { 3, wxDateTime::Apr, 1925 }, 1, wxDateTime::Fri, wxDateTime::Apr, 1925 },
1339 { { 21, wxDateTime::Mar, 2093 }, 3, wxDateTime::Sat, wxDateTime::Mar, 2093 },
1340 { { 3, wxDateTime::Dec, 2074 }, -5, wxDateTime::Mon, wxDateTime::Dec, 2074 },
1341 };
1342
1343 static const char *fmt = "%d-%b-%Y";
1344
1345 wxDateTime dt;
1346 for ( n = 0; n < WXSIZEOF(weekDatesTestData); n++ )
1347 {
1348 const WeekDateTestData& wd = weekDatesTestData[n];
1349
1350 dt.SetToWeekDay(wd.wday, wd.nWeek, wd.month, wd.year);
1351
1352 printf("%s is %s", wd.Format().c_str(), dt.Format(fmt).c_str());
1353
1354 const Date& d = wd.date;
1355 if ( d.SameDay(dt.GetTm()) )
1356 {
1357 puts(" (ok)");
1358 }
1359 else
1360 {
1361 dt.Set(d.day, d.month, d.year);
1362
1363 printf(" (ERROR: should be %s)\n", dt.Format(fmt).c_str());
211c2250
VZ
1364 }
1365 }
1366}
1367
239446b4
VZ
1368// test the computation of (ISO) week numbers
1369static void TestTimeWNumber()
1370{
1371 puts("\n*** wxDateTime week number test ***");
1372
1373 struct WeekNumberTestData
1374 {
1375 Date date; // the date
9d9b7755
VZ
1376 wxDateTime::wxDateTime_t week; // the week number in the year
1377 wxDateTime::wxDateTime_t wmon; // the week number in the month
1378 wxDateTime::wxDateTime_t wmon2; // same but week starts with Sun
239446b4
VZ
1379 wxDateTime::wxDateTime_t dnum; // day number in the year
1380 };
1381
1382 // data generated with the following python script:
1383 /*
1384from DateTime import *
1385from whrandom import *
1386from string import *
1387
1388monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1389wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1390
9d9b7755
VZ
1391def GetMonthWeek(dt):
1392 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
1393 if weekNumMonth < 0:
1394 weekNumMonth = weekNumMonth + 53
1395 return weekNumMonth
7c968cee 1396
9d9b7755
VZ
1397def GetLastSundayBefore(dt):
1398 if dt.iso_week[2] == 7:
1399 return dt
1400 else:
1401 return dt - DateTimeDelta(dt.iso_week[2])
1402
239446b4
VZ
1403for n in range(20):
1404 year = randint(1900, 2100)
1405 month = randint(1, 12)
1406 day = randint(1, 28)
1407 dt = DateTime(year, month, day)
1408 dayNum = dt.day_of_year
1409 weekNum = dt.iso_week[1]
9d9b7755
VZ
1410 weekNumMonth = GetMonthWeek(dt)
1411
1412 weekNumMonth2 = 0
1413 dtSunday = GetLastSundayBefore(dt)
1414
1415 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
1416 weekNumMonth2 = weekNumMonth2 + 1
1417 dtSunday = dtSunday - DateTimeDelta(7)
1418
1419 data = { 'day': rjust(`day`, 2), \
1420 'month': monthNames[month - 1], \
1421 'year': year, \
1422 'weekNum': rjust(`weekNum`, 2), \
1423 'weekNumMonth': weekNumMonth, \
1424 'weekNumMonth2': weekNumMonth2, \
1425 'dayNum': rjust(`dayNum`, 3) }
1426
1427 print " { { %(day)s, "\
1428 "wxDateTime::%(month)s, "\
1429 "%(year)d }, "\
1430 "%(weekNum)s, "\
1431 "%(weekNumMonth)s, "\
1432 "%(weekNumMonth2)s, "\
239446b4 1433 "%(dayNum)s }," % data
9d9b7755 1434
239446b4
VZ
1435 */
1436 static const WeekNumberTestData weekNumberTestDates[] =
1437 {
9d9b7755
VZ
1438 { { 27, wxDateTime::Dec, 1966 }, 52, 5, 5, 361 },
1439 { { 22, wxDateTime::Jul, 1926 }, 29, 4, 4, 203 },
1440 { { 22, wxDateTime::Oct, 2076 }, 43, 4, 4, 296 },
1441 { { 1, wxDateTime::Jul, 1967 }, 26, 1, 1, 182 },
1442 { { 8, wxDateTime::Nov, 2004 }, 46, 2, 2, 313 },
1443 { { 21, wxDateTime::Mar, 1920 }, 12, 3, 4, 81 },
1444 { { 7, wxDateTime::Jan, 1965 }, 1, 2, 2, 7 },
1445 { { 19, wxDateTime::Oct, 1999 }, 42, 4, 4, 292 },
1446 { { 13, wxDateTime::Aug, 1955 }, 32, 2, 2, 225 },
1447 { { 18, wxDateTime::Jul, 2087 }, 29, 3, 3, 199 },
1448 { { 2, wxDateTime::Sep, 2028 }, 35, 1, 1, 246 },
1449 { { 28, wxDateTime::Jul, 1945 }, 30, 5, 4, 209 },
1450 { { 15, wxDateTime::Jun, 1901 }, 24, 3, 3, 166 },
1451 { { 10, wxDateTime::Oct, 1939 }, 41, 3, 2, 283 },
1452 { { 3, wxDateTime::Dec, 1965 }, 48, 1, 1, 337 },
1453 { { 23, wxDateTime::Feb, 1940 }, 8, 4, 4, 54 },
1454 { { 2, wxDateTime::Jan, 1987 }, 1, 1, 1, 2 },
1455 { { 11, wxDateTime::Aug, 2079 }, 32, 2, 2, 223 },
1456 { { 2, wxDateTime::Feb, 2063 }, 5, 1, 1, 33 },
1457 { { 16, wxDateTime::Oct, 1942 }, 42, 3, 3, 289 },
239446b4
VZ
1458 };
1459
1460 for ( size_t n = 0; n < WXSIZEOF(weekNumberTestDates); n++ )
1461 {
1462 const WeekNumberTestData& wn = weekNumberTestDates[n];
1463 const Date& d = wn.date;
1464
1465 wxDateTime dt = d.DT();
1466
9d9b7755
VZ
1467 wxDateTime::wxDateTime_t
1468 week = dt.GetWeekOfYear(wxDateTime::Monday_First),
1469 wmon = dt.GetWeekOfMonth(wxDateTime::Monday_First),
1470 wmon2 = dt.GetWeekOfMonth(wxDateTime::Sunday_First),
1471 dnum = dt.GetDayOfYear();
239446b4
VZ
1472
1473 printf("%s: the day number is %d",
1474 d.FormatDate().c_str(), dnum);
1475 if ( dnum == wn.dnum )
1476 {
1477 printf(" (ok)");
1478 }
1479 else
1480 {
1481 printf(" (ERROR: should be %d)", wn.dnum);
1482 }
1483
9d9b7755
VZ
1484 printf(", week in month is %d", wmon);
1485 if ( wmon == wn.wmon )
1486 {
1487 printf(" (ok)");
1488 }
1489 else
1490 {
1491 printf(" (ERROR: should be %d)", wn.wmon);
1492 }
1493
1494 printf(" or %d", wmon2);
1495 if ( wmon2 == wn.wmon2 )
1496 {
1497 printf(" (ok)");
1498 }
1499 else
1500 {
1501 printf(" (ERROR: should be %d)", wn.wmon2);
1502 }
1503
1504 printf(", week in year is %d", week);
239446b4
VZ
1505 if ( week == wn.week )
1506 {
1507 puts(" (ok)");
1508 }
1509 else
1510 {
1511 printf(" (ERROR: should be %d)\n", wn.week);
1512 }
1513 }
1514}
1515
1516// test DST calculations
1517static void TestTimeDST()
1518{
1519 puts("\n*** wxDateTime DST test ***");
1520
1521 printf("DST is%s in effect now.\n\n",
1522 wxDateTime::Now().IsDST() ? "" : " not");
1523
1524 // taken from http://www.energy.ca.gov/daylightsaving.html
1525 static const Date datesDST[2][2004 - 1900 + 1] =
1526 {
1527 {
1528 { 1, wxDateTime::Apr, 1990 },
1529 { 7, wxDateTime::Apr, 1991 },
1530 { 5, wxDateTime::Apr, 1992 },
1531 { 4, wxDateTime::Apr, 1993 },
1532 { 3, wxDateTime::Apr, 1994 },
1533 { 2, wxDateTime::Apr, 1995 },
1534 { 7, wxDateTime::Apr, 1996 },
1535 { 6, wxDateTime::Apr, 1997 },
1536 { 5, wxDateTime::Apr, 1998 },
1537 { 4, wxDateTime::Apr, 1999 },
1538 { 2, wxDateTime::Apr, 2000 },
1539 { 1, wxDateTime::Apr, 2001 },
1540 { 7, wxDateTime::Apr, 2002 },
1541 { 6, wxDateTime::Apr, 2003 },
1542 { 4, wxDateTime::Apr, 2004 },
1543 },
1544 {
1545 { 28, wxDateTime::Oct, 1990 },
1546 { 27, wxDateTime::Oct, 1991 },
1547 { 25, wxDateTime::Oct, 1992 },
1548 { 31, wxDateTime::Oct, 1993 },
1549 { 30, wxDateTime::Oct, 1994 },
1550 { 29, wxDateTime::Oct, 1995 },
1551 { 27, wxDateTime::Oct, 1996 },
1552 { 26, wxDateTime::Oct, 1997 },
1553 { 25, wxDateTime::Oct, 1998 },
1554 { 31, wxDateTime::Oct, 1999 },
1555 { 29, wxDateTime::Oct, 2000 },
1556 { 28, wxDateTime::Oct, 2001 },
1557 { 27, wxDateTime::Oct, 2002 },
1558 { 26, wxDateTime::Oct, 2003 },
1559 { 31, wxDateTime::Oct, 2004 },
1560 }
1561 };
1562
1563 int year;
1564 for ( year = 1990; year < 2005; year++ )
1565 {
1566 wxDateTime dtBegin = wxDateTime::GetBeginDST(year, wxDateTime::USA),
1567 dtEnd = wxDateTime::GetEndDST(year, wxDateTime::USA);
1568
1569 printf("DST period in the US for year %d: from %s to %s",
1570 year, dtBegin.Format().c_str(), dtEnd.Format().c_str());
1571
1572 size_t n = year - 1990;
1573 const Date& dBegin = datesDST[0][n];
1574 const Date& dEnd = datesDST[1][n];
97e0ceea 1575
239446b4
VZ
1576 if ( dBegin.SameDay(dtBegin.GetTm()) && dEnd.SameDay(dtEnd.GetTm()) )
1577 {
1578 puts(" (ok)");
1579 }
1580 else
1581 {
1582 printf(" (ERROR: should be %s %d to %s %d)\n",
1583 wxDateTime::GetMonthName(dBegin.month).c_str(), dBegin.day,
1584 wxDateTime::GetMonthName(dEnd.month).c_str(), dEnd.day);
1585 }
1586 }
1587
1588 puts("");
1589
1590 for ( year = 1990; year < 2005; year++ )
1591 {
1592 printf("DST period in Europe for year %d: from %s to %s\n",
1593 year,
1594 wxDateTime::GetBeginDST(year, wxDateTime::Country_EEC).Format().c_str(),
1595 wxDateTime::GetEndDST(year, wxDateTime::Country_EEC).Format().c_str());
1596 }
1597}
1598
68ee7c47
VZ
1599// test wxDateTime -> text conversion
1600static void TestTimeFormat()
1601{
1602 puts("\n*** wxDateTime formatting test ***");
1603
b38e2f7d
VZ
1604 // some information may be lost during conversion, so store what kind
1605 // of info should we recover after a round trip
1606 enum CompareKind
68ee7c47 1607 {
b38e2f7d
VZ
1608 CompareNone, // don't try comparing
1609 CompareBoth, // dates and times should be identical
1610 CompareDate, // dates only
1611 CompareTime // time only
1612 };
1613
1614 static const struct
1615 {
1616 CompareKind compareKind;
1617 const char *format;
1618 } formatTestFormats[] =
1619 {
1620 { CompareBoth, "---> %c" },
1621 { CompareDate, "Date is %A, %d of %B, in year %Y" },
1622 { CompareBoth, "Date is %x, time is %X" },
1623 { CompareTime, "Time is %H:%M:%S or %I:%M:%S %p" },
1624 { CompareNone, "The day of year: %j, the week of year: %W" },
68ee7c47
VZ
1625 };
1626
1627 static const Date formatTestDates[] =
1628 {
68ee7c47
VZ
1629 { 29, wxDateTime::May, 1976, 18, 30, 00 },
1630 { 31, wxDateTime::Dec, 1999, 23, 30, 00 },
b38e2f7d
VZ
1631#if 0
1632 // this test can't work for other centuries because it uses two digit
1633 // years in formats, so don't even try it
68ee7c47
VZ
1634 { 29, wxDateTime::May, 2076, 18, 30, 00 },
1635 { 29, wxDateTime::Feb, 2400, 02, 15, 25 },
1636 { 01, wxDateTime::Jan, -52, 03, 16, 47 },
b38e2f7d 1637#endif
68ee7c47
VZ
1638 };
1639
1640 // an extra test (as it doesn't depend on date, don't do it in the loop)
1641 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
1642
b38e2f7d 1643 for ( size_t d = 0; d < WXSIZEOF(formatTestDates) + 1; d++ )
68ee7c47
VZ
1644 {
1645 puts("");
1646
b38e2f7d 1647 wxDateTime dt = d == 0 ? wxDateTime::Now() : formatTestDates[d - 1].DT();
68ee7c47
VZ
1648 for ( size_t n = 0; n < WXSIZEOF(formatTestFormats); n++ )
1649 {
b38e2f7d 1650 wxString s = dt.Format(formatTestFormats[n].format);
f0f951fa
VZ
1651 printf("%s", s.c_str());
1652
b38e2f7d
VZ
1653 // what can we recover?
1654 int kind = formatTestFormats[n].compareKind;
1655
f0f951fa
VZ
1656 // convert back
1657 wxDateTime dt2;
b38e2f7d 1658 const wxChar *result = dt2.ParseFormat(s, formatTestFormats[n].format);
f0f951fa
VZ
1659 if ( !result )
1660 {
b38e2f7d
VZ
1661 // converion failed - should it have?
1662 if ( kind == CompareNone )
1663 puts(" (ok)");
1664 else
1665 puts(" (ERROR: conversion back failed)");
f0f951fa
VZ
1666 }
1667 else if ( *result )
1668 {
1669 // should have parsed the entire string
1670 puts(" (ERROR: conversion back stopped too soon)");
1671 }
f0f951fa
VZ
1672 else
1673 {
b38e2f7d
VZ
1674 bool equal = FALSE; // suppress compilaer warning
1675 switch ( kind )
1676 {
1677 case CompareBoth:
1678 equal = dt2 == dt;
1679 break;
1680
1681 case CompareDate:
1682 equal = dt.IsSameDate(dt2);
1683 break;
1684
1685 case CompareTime:
1686 equal = dt.IsSameTime(dt2);
1687 break;
1688 }
1689
1690 if ( !equal )
1691 {
1692 printf(" (ERROR: got back '%s' instead of '%s')\n",
1693 dt2.Format().c_str(), dt.Format().c_str());
1694 }
1695 else
1696 {
1697 puts(" (ok)");
1698 }
f0f951fa 1699 }
68ee7c47
VZ
1700 }
1701 }
1702}
1703
97e0ceea
VZ
1704// test text -> wxDateTime conversion
1705static void TestTimeParse()
1706{
1707 puts("\n*** wxDateTime parse test ***");
1708
1709 struct ParseTestData
1710 {
1711 const char *format;
1712 Date date;
1713 bool good;
1714 };
1715
1716 static const ParseTestData parseTestDates[] =
1717 {
68ee7c47
VZ
1718 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec, 1999, 00, 46, 40 }, TRUE },
1719 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec, 1999, 03, 17, 20 }, TRUE },
97e0ceea
VZ
1720 };
1721
1722 for ( size_t n = 0; n < WXSIZEOF(parseTestDates); n++ )
1723 {
1724 const char *format = parseTestDates[n].format;
1725
1726 printf("%s => ", format);
1727
1728 wxDateTime dt;
1729 if ( dt.ParseRfc822Date(format) )
1730 {
1731 printf("%s ", dt.Format().c_str());
1732
1733 if ( parseTestDates[n].good )
1734 {
1735 wxDateTime dtReal = parseTestDates[n].date.DT();
1736 if ( dt == dtReal )
1737 {
1738 puts("(ok)");
1739 }
1740 else
1741 {
1742 printf("(ERROR: should be %s)\n", dtReal.Format().c_str());
1743 }
1744 }
1745 else
1746 {
1747 puts("(ERROR: bad format)");
1748 }
1749 }
1750 else
1751 {
1752 printf("bad format (%s)\n",
1753 parseTestDates[n].good ? "ERROR" : "ok");
1754 }
1755 }
1756}
1757
9d9b7755
VZ
1758static void TestInteractive()
1759{
1760 puts("\n*** interactive wxDateTime tests ***");
1761
1762 char buf[128];
1763
1764 for ( ;; )
1765 {
1766 printf("Enter a date: ");
1767 if ( !fgets(buf, WXSIZEOF(buf), stdin) )
1768 break;
1769
1770 wxDateTime dt;
1771 if ( !dt.ParseDate(buf) )
1772 {
1773 puts("failed to parse the date");
1774
1775 continue;
1776 }
1777
1778 printf("%s: day %u, week of month %u/%u, week of year %u\n",
1779 dt.FormatISODate().c_str(),
1780 dt.GetDayOfYear(),
1781 dt.GetWeekOfMonth(wxDateTime::Monday_First),
1782 dt.GetWeekOfMonth(wxDateTime::Sunday_First),
1783 dt.GetWeekOfYear(wxDateTime::Monday_First));
1784 }
1785
1786 puts("\n*** done ***");
1787}
1788
1789static void TestTimeArithmetics()
1790{
1791 puts("\n*** testing arithmetic operations on wxDateTime ***");
1792
1793 static const struct
1794 {
1795 wxDateSpan span;
1796 const char *name;
7c968cee 1797 } testArithmData[] =
9d9b7755
VZ
1798 {
1799 { wxDateSpan::Day(), "day" },
1800 { wxDateSpan::Week(), "week" },
1801 { wxDateSpan::Month(), "month" },
1802 { wxDateSpan::Year(), "year" },
1803 { wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days" },
1804 };
7c968cee 1805
9d9b7755
VZ
1806 wxDateTime dt(29, wxDateTime::Dec, 1999), dt1, dt2;
1807
1808 for ( size_t n = 0; n < WXSIZEOF(testArithmData); n++ )
1809 {
1810 wxDateSpan span = testArithmData[n].span;
1811 dt1 = dt + span;
1812 dt2 = dt - span;
1813
1814 const char *name = testArithmData[n].name;
1815 printf("%s + %s = %s, %s - %s = %s\n",
1816 dt.FormatISODate().c_str(), name, dt1.FormatISODate().c_str(),
1817 dt.FormatISODate().c_str(), name, dt2.FormatISODate().c_str());
1818
1819 printf("Going back: %s", (dt1 - span).FormatISODate().c_str());
1820 if ( dt1 - span == dt )
1821 {
1822 puts(" (ok)");
1823 }
1824 else
1825 {
1826 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
1827 }
1828
1829 printf("Going forward: %s", (dt2 + span).FormatISODate().c_str());
1830 if ( dt2 + span == dt )
1831 {
1832 puts(" (ok)");
1833 }
1834 else
1835 {
1836 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
1837 }
1838
1839 printf("Double increment: %s", (dt2 + 2*span).FormatISODate().c_str());
1840 if ( dt2 + 2*span == dt1 )
1841 {
1842 puts(" (ok)");
1843 }
1844 else
1845 {
1846 printf(" (ERROR: should be %s)\n", dt2.FormatISODate().c_str());
1847 }
1848
1849 puts("");
1850 }
1851}
1852
0de868d9
VZ
1853static void TestTimeHolidays()
1854{
1855 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
1856
1857 wxDateTime::Tm tm = wxDateTime(29, wxDateTime::May, 2000).GetTm();
1858 wxDateTime dtStart(1, tm.mon, tm.year),
1859 dtEnd = dtStart.GetLastMonthDay();
1860
1861 wxDateTimeArray hol;
1862 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart, dtEnd, hol);
1863
1864 const wxChar *format = "%d-%b-%Y (%a)";
1865
1866 printf("All holidays between %s and %s:\n",
1867 dtStart.Format(format).c_str(), dtEnd.Format(format).c_str());
1868
1869 size_t count = hol.GetCount();
1870 for ( size_t n = 0; n < count; n++ )
1871 {
1872 printf("\t%s\n", hol[n].Format(format).c_str());
1873 }
1874
1875 puts("");
1876}
1877
68ee7c47
VZ
1878#if 0
1879
97e0ceea
VZ
1880// test compatibility with the old wxDate/wxTime classes
1881static void TestTimeCompatibility()
1882{
1883 puts("\n*** wxDateTime compatibility test ***");
1884
1885 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
1886 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
1887
1888 double jdnNow = wxDateTime::Now().GetJDN();
1889 long jdnMidnight = (long)(jdnNow - 0.5);
1890 printf("wxDate for today: %s\n", wxDate(jdnMidnight).FormatDate().c_str());
1891
1892 jdnMidnight = wxDate().Set().GetJulianDate();
1893 printf("wxDateTime for today: %s\n",
1894 wxDateTime((double)(jdnMidnight + 0.5)).Format("%c", wxDateTime::GMT0).c_str());
1895
1896 int flags = wxEUROPEAN;//wxFULL;
1897 wxDate date;
1898 date.Set();
1899 printf("Today is %s\n", date.FormatDate(flags).c_str());
1900 for ( int n = 0; n < 7; n++ )
1901 {
1902 printf("Previous %s is %s\n",
1903 wxDateTime::GetWeekDayName((wxDateTime::WeekDay)n),
1904 date.Previous(n + 1).FormatDate(flags).c_str());
1905 }
1906}
1907
68ee7c47
VZ
1908#endif // 0
1909
d31b7b68 1910#endif // TEST_DATETIME
b76b015e 1911
e87271f3
VZ
1912// ----------------------------------------------------------------------------
1913// threads
1914// ----------------------------------------------------------------------------
1915
1916#ifdef TEST_THREADS
1917
bbfa0322 1918#include <wx/thread.h>
37667812 1919
bbfa0322
VZ
1920static size_t gs_counter = (size_t)-1;
1921static wxCriticalSection gs_critsect;
b568d04f 1922static wxCondition gs_cond;
bbfa0322 1923
b568d04f 1924class MyJoinableThread : public wxThread
bbfa0322
VZ
1925{
1926public:
b568d04f
VZ
1927 MyJoinableThread(size_t n) : wxThread(wxTHREAD_JOINABLE)
1928 { m_n = n; Create(); }
bbfa0322
VZ
1929
1930 // thread execution starts here
b568d04f 1931 virtual ExitCode Entry();
bbfa0322 1932
b568d04f
VZ
1933private:
1934 size_t m_n;
bbfa0322
VZ
1935};
1936
b568d04f 1937wxThread::ExitCode MyJoinableThread::Entry()
bbfa0322 1938{
b568d04f
VZ
1939 unsigned long res = 1;
1940 for ( size_t n = 1; n < m_n; n++ )
1941 {
1942 res *= n;
1943
1944 // it's a loooong calculation :-)
1945 Sleep(100);
1946 }
bbfa0322 1947
b568d04f 1948 return (ExitCode)res;
bbfa0322
VZ
1949}
1950
b568d04f
VZ
1951class MyDetachedThread : public wxThread
1952{
1953public:
fcc3d7cb
VZ
1954 MyDetachedThread(size_t n, char ch)
1955 {
1956 m_n = n;
1957 m_ch = ch;
1958 m_cancelled = FALSE;
1959
1960 Create();
1961 }
b568d04f
VZ
1962
1963 // thread execution starts here
1964 virtual ExitCode Entry();
1965
1966 // and stops here
1967 virtual void OnExit();
1968
1969private:
9fc3ad34
VZ
1970 size_t m_n; // number of characters to write
1971 char m_ch; // character to write
fcc3d7cb
VZ
1972
1973 bool m_cancelled; // FALSE if we exit normally
b568d04f
VZ
1974};
1975
1976wxThread::ExitCode MyDetachedThread::Entry()
bbfa0322
VZ
1977{
1978 {
1979 wxCriticalSectionLocker lock(gs_critsect);
1980 if ( gs_counter == (size_t)-1 )
1981 gs_counter = 1;
1982 else
1983 gs_counter++;
1984 }
1985
9fc3ad34 1986 for ( size_t n = 0; n < m_n; n++ )
bbfa0322
VZ
1987 {
1988 if ( TestDestroy() )
fcc3d7cb
VZ
1989 {
1990 m_cancelled = TRUE;
1991
bbfa0322 1992 break;
fcc3d7cb 1993 }
bbfa0322
VZ
1994
1995 putchar(m_ch);
1996 fflush(stdout);
1997
1998 wxThread::Sleep(100);
1999 }
2000
b568d04f 2001 return 0;
bbfa0322
VZ
2002}
2003
b568d04f 2004void MyDetachedThread::OnExit()
bbfa0322 2005{
9fc3ad34
VZ
2006 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
2007
bbfa0322 2008 wxCriticalSectionLocker lock(gs_critsect);
fcc3d7cb 2009 if ( !--gs_counter && !m_cancelled )
b568d04f 2010 gs_cond.Signal();
bbfa0322
VZ
2011}
2012
9fc3ad34
VZ
2013void TestDetachedThreads()
2014{
2f02cb89 2015 puts("\n*** Testing detached threads ***");
9fc3ad34
VZ
2016
2017 static const size_t nThreads = 3;
2018 MyDetachedThread *threads[nThreads];
2019 size_t n;
2020 for ( n = 0; n < nThreads; n++ )
2021 {
2022 threads[n] = new MyDetachedThread(10, 'A' + n);
2023 }
2024
2025 threads[0]->SetPriority(WXTHREAD_MIN_PRIORITY);
2026 threads[1]->SetPriority(WXTHREAD_MAX_PRIORITY);
2027
2028 for ( n = 0; n < nThreads; n++ )
2029 {
2030 threads[n]->Run();
2031 }
2032
2033 // wait until all threads terminate
2034 gs_cond.Wait();
2035
2036 puts("");
2037}
2038
2039void TestJoinableThreads()
2040{
2f02cb89 2041 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
9fc3ad34
VZ
2042
2043 // calc 10! in the background
2044 MyJoinableThread thread(10);
2045 thread.Run();
2046
2047 printf("\nThread terminated with exit code %lu.\n",
2048 (unsigned long)thread.Wait());
2049}
2050
2051void TestThreadSuspend()
2052{
2f02cb89
VZ
2053 puts("\n*** Testing thread suspend/resume functions ***");
2054
2055 MyDetachedThread *thread = new MyDetachedThread(15, 'X');
9fc3ad34
VZ
2056
2057 thread->Run();
2058
2059 // this is for this demo only, in a real life program we'd use another
2060 // condition variable which would be signaled from wxThread::Entry() to
2061 // tell us that the thread really started running - but here just wait a
2062 // bit and hope that it will be enough (the problem is, of course, that
2063 // the thread might still not run when we call Pause() which will result
2064 // in an error)
2065 wxThread::Sleep(300);
2066
2067 for ( size_t n = 0; n < 3; n++ )
2068 {
2069 thread->Pause();
2070
2071 puts("\nThread suspended");
2072 if ( n > 0 )
2073 {
2074 // don't sleep but resume immediately the first time
2075 wxThread::Sleep(300);
2076 }
2077 puts("Going to resume the thread");
2078
2079 thread->Resume();
2080 }
2081
4c460b34
VZ
2082 puts("Waiting until it terminates now");
2083
9fc3ad34
VZ
2084 // wait until the thread terminates
2085 gs_cond.Wait();
2086
2087 puts("");
2088}
2089
2f02cb89
VZ
2090void TestThreadDelete()
2091{
2092 // As above, using Sleep() is only for testing here - we must use some
2093 // synchronisation object instead to ensure that the thread is still
2094 // running when we delete it - deleting a detached thread which already
2095 // terminated will lead to a crash!
2096
2097 puts("\n*** Testing thread delete function ***");
2098
4c460b34
VZ
2099 MyDetachedThread *thread0 = new MyDetachedThread(30, 'W');
2100
2101 thread0->Delete();
2102
2103 puts("\nDeleted a thread which didn't start to run yet.");
2104
2f02cb89
VZ
2105 MyDetachedThread *thread1 = new MyDetachedThread(30, 'Y');
2106
2107 thread1->Run();
2108
2109 wxThread::Sleep(300);
2110
2111 thread1->Delete();
2112
2113 puts("\nDeleted a running thread.");
2114
2115 MyDetachedThread *thread2 = new MyDetachedThread(30, 'Z');
2116
2117 thread2->Run();
2118
2119 wxThread::Sleep(300);
2120
2121 thread2->Pause();
2122
2123 thread2->Delete();
2124
2125 puts("\nDeleted a sleeping thread.");
2126
4c460b34
VZ
2127 MyJoinableThread thread3(20);
2128 thread3.Run();
2f02cb89 2129
4c460b34 2130 thread3.Delete();
2f02cb89
VZ
2131
2132 puts("\nDeleted a joinable thread.");
2133
4c460b34
VZ
2134 MyJoinableThread thread4(2);
2135 thread4.Run();
2f02cb89
VZ
2136
2137 wxThread::Sleep(300);
2138
4c460b34 2139 thread4.Delete();
2f02cb89
VZ
2140
2141 puts("\nDeleted a joinable thread which already terminated.");
2142
2143 puts("");
2144}
2145
e87271f3
VZ
2146#endif // TEST_THREADS
2147
2148// ----------------------------------------------------------------------------
2149// arrays
2150// ----------------------------------------------------------------------------
2151
2152#ifdef TEST_ARRAYS
2153
2154void PrintArray(const char* name, const wxArrayString& array)
2155{
2156 printf("Dump of the array '%s'\n", name);
2157
2158 size_t nCount = array.GetCount();
2159 for ( size_t n = 0; n < nCount; n++ )
2160 {
2161 printf("\t%s[%u] = '%s'\n", name, n, array[n].c_str());
2162 }
2163}
2164
2165#endif // TEST_ARRAYS
2166
9fc3ad34
VZ
2167// ----------------------------------------------------------------------------
2168// strings
2169// ----------------------------------------------------------------------------
2170
2171#ifdef TEST_STRINGS
2172
2173#include "wx/timer.h"
bbf8fc53 2174#include "wx/tokenzr.h"
9fc3ad34 2175
7c968cee
VZ
2176static void TestStringConstruction()
2177{
2178 puts("*** Testing wxString constructores ***");
2179
2180 #define TEST_CTOR(args, res) \
2181 { \
2182 wxString s args ; \
2183 printf("wxString%s = %s ", #args, s.c_str()); \
2184 if ( s == res ) \
2185 { \
2186 puts("(ok)"); \
2187 } \
2188 else \
2189 { \
2190 printf("(ERROR: should be %s)\n", res); \
2191 } \
2192 }
2193
2194 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
2195 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
2196 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
2197 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
2198
2199 static const wxChar *s = _T("?really!");
2200 const wxChar *start = wxStrchr(s, _T('r'));
2201 const wxChar *end = wxStrchr(s, _T('!'));
2202 TEST_CTOR((start, end), _T("really"));
2203
2204 puts("");
2205}
2206
299fcbfe 2207static void TestString()
9fc3ad34
VZ
2208{
2209 wxStopWatch sw;
2210
2211 wxString a, b, c;
2212
2213 a.reserve (128);
2214 b.reserve (128);
2215 c.reserve (128);
2216
2217 for (int i = 0; i < 1000000; ++i)
2218 {
2219 a = "Hello";
2220 b = " world";
2221 c = "! How'ya doin'?";
2222 a += b;
2223 a += c;
2224 c = "Hello world! What's up?";
2225 if (c != a)
2226 c = "Doh!";
2227 }
2228
2229 printf ("TestString elapsed time: %ld\n", sw.Time());
2230}
2231
299fcbfe 2232static void TestPChar()
9fc3ad34
VZ
2233{
2234 wxStopWatch sw;
2235
2236 char a [128];
2237 char b [128];
2238 char c [128];
2239
2240 for (int i = 0; i < 1000000; ++i)
2241 {
2242 strcpy (a, "Hello");
2243 strcpy (b, " world");
2244 strcpy (c, "! How'ya doin'?");
2245 strcat (a, b);
2246 strcat (a, c);
2247 strcpy (c, "Hello world! What's up?");
2248 if (strcmp (c, a) == 0)
2249 strcpy (c, "Doh!");
2250 }
2251
2252 printf ("TestPChar elapsed time: %ld\n", sw.Time());
2253}
2254
299fcbfe
VZ
2255static void TestStringSub()
2256{
2257 wxString s("Hello, world!");
2258
2259 puts("*** Testing wxString substring extraction ***");
2260
2261 printf("String = '%s'\n", s.c_str());
2262 printf("Left(5) = '%s'\n", s.Left(5).c_str());
2263 printf("Right(6) = '%s'\n", s.Right(6).c_str());
2264 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
2265 printf("Mid(3) = '%s'\n", s.Mid(3).c_str());
2266 printf("substr(3, 5) = '%s'\n", s.substr(3, 5).c_str());
2267 printf("substr(3) = '%s'\n", s.substr(3).c_str());
2268
2269 puts("");
2270}
2271
f0f951fa
VZ
2272static void TestStringFormat()
2273{
2274 puts("*** Testing wxString formatting ***");
2275
2276 wxString s;
2277 s.Printf("%03d", 18);
2278
2279 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
2280 printf("Number 18: %s\n", s.c_str());
2281
2282 puts("");
2283}
2284
d71fa6fb
VZ
2285// returns "not found" for npos, value for all others
2286static wxString PosToString(size_t res)
2287{
2288 wxString s = res == wxString::npos ? wxString(_T("not found"))
2289 : wxString::Format(_T("%u"), res);
2290 return s;
2291}
2292
2293static void TestStringFind()
2294{
2295 puts("*** Testing wxString find() functions ***");
2296
2297 static const wxChar *strToFind = _T("ell");
2298 static const struct StringFindTest
2299 {
2300 const wxChar *str;
2301 size_t start,
2302 result; // of searching "ell" in str
2303 } findTestData[] =
2304 {
2305 { _T("Well, hello world"), 0, 1 },
2306 { _T("Well, hello world"), 6, 7 },
2307 { _T("Well, hello world"), 9, wxString::npos },
2308 };
2309
2310 for ( size_t n = 0; n < WXSIZEOF(findTestData); n++ )
2311 {
2312 const StringFindTest& ft = findTestData[n];
2313 size_t res = wxString(ft.str).find(strToFind, ft.start);
2314
2315 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
2316 strToFind, ft.str, ft.start, PosToString(res).c_str());
2317
2318 size_t resTrue = ft.result;
2319 if ( res == resTrue )
2320 {
2321 puts(_T("(ok)"));
2322 }
2323 else
2324 {
2325 printf(_T("(ERROR: should be %s)\n"),
2326 PosToString(resTrue).c_str());
2327 }
2328 }
2329
2330 puts("");
2331}
2332
bbf8fc53
VZ
2333static void TestStringTokenizer()
2334{
2335 puts("*** Testing wxStringTokenizer ***");
2336
7c968cee
VZ
2337 static const wxChar *modeNames[] =
2338 {
2339 _T("default"),
2340 _T("return empty"),
2341 _T("return all empty"),
2342 _T("with delims"),
2343 _T("like strtok"),
2344 };
2345
bbf8fc53
VZ
2346 static const struct StringTokenizerTest
2347 {
7c968cee
VZ
2348 const wxChar *str; // string to tokenize
2349 const wxChar *delims; // delimiters to use
2350 size_t count; // count of token
2351 wxStringTokenizerMode mode; // how should we tokenize it
2352 } tokenizerTestData[] =
2353 {
2354 { _T(""), _T(" "), 0 },
2355 { _T("Hello, world"), _T(" "), 2 },
2356 { _T("Hello, world "), _T(" "), 2 },
2357 { _T("Hello, world"), _T(","), 2 },
2358 { _T("Hello, world!"), _T(",!"), 2 },
2359 { _T("Hello,, world!"), _T(",!"), 3 },
2360 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL },
2361 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
2362 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 4 },
2363 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 6, wxTOKEN_RET_EMPTY },
2364 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 9, wxTOKEN_RET_EMPTY_ALL },
2365 { _T("01/02/99"), _T("/-"), 3 },
2366 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS },
bbf8fc53
VZ
2367 };
2368
2369 for ( size_t n = 0; n < WXSIZEOF(tokenizerTestData); n++ )
2370 {
2371 const StringTokenizerTest& tt = tokenizerTestData[n];
7c968cee 2372 wxStringTokenizer tkz(tt.str, tt.delims, tt.mode);
bbf8fc53
VZ
2373
2374 size_t count = tkz.CountTokens();
7c968cee
VZ
2375 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
2376 MakePrintable(tt.str).c_str(),
bbf8fc53 2377 count,
7c968cee
VZ
2378 MakePrintable(tt.delims).c_str(),
2379 modeNames[tkz.GetMode()]);
bbf8fc53
VZ
2380 if ( count == tt.count )
2381 {
2382 puts(_T("(ok)"));
2383 }
2384 else
2385 {
2386 printf(_T("(ERROR: should be %u)\n"), tt.count);
2387
2388 continue;
2389 }
2390
7c968cee
VZ
2391 // if we emulate strtok(), check that we do it correctly
2392 wxChar *buf, *s, *last;
2393
2394 if ( tkz.GetMode() == wxTOKEN_STRTOK )
2395 {
2396 buf = new wxChar[wxStrlen(tt.str) + 1];
2397 wxStrcpy(buf, tt.str);
2398
2399 s = wxStrtok(buf, tt.delims, &last);
2400 }
2401 else
2402 {
2403 buf = NULL;
2404 }
2405
bbf8fc53
VZ
2406 // now show the tokens themselves
2407 size_t count2 = 0;
2408 while ( tkz.HasMoreTokens() )
2409 {
7c968cee
VZ
2410 wxString token = tkz.GetNextToken();
2411
2412 printf(_T("\ttoken %u: '%s'"),
bbf8fc53 2413 ++count2,
7c968cee
VZ
2414 MakePrintable(token).c_str());
2415
2416 if ( buf )
2417 {
2418 if ( token == s )
2419 {
2420 puts(" (ok)");
2421 }
2422 else
2423 {
2424 printf(" (ERROR: should be %s)\n", s);
2425 }
2426
2427 s = wxStrtok(NULL, tt.delims, &last);
2428 }
2429 else
2430 {
2431 // nothing to compare with
2432 puts("");
2433 }
bbf8fc53
VZ
2434 }
2435
2436 if ( count2 != count )
2437 {
7c968cee 2438 puts(_T("\tERROR: token count mismatch"));
bbf8fc53 2439 }
7c968cee
VZ
2440
2441 delete [] buf;
bbf8fc53
VZ
2442 }
2443
2444 puts("");
2445}
2446
9fc3ad34
VZ
2447#endif // TEST_STRINGS
2448
e87271f3
VZ
2449// ----------------------------------------------------------------------------
2450// entry point
2451// ----------------------------------------------------------------------------
2452
bbfa0322 2453int main(int argc, char **argv)
37667812
VZ
2454{
2455 if ( !wxInitialize() )
2456 {
2457 fprintf(stderr, "Failed to initialize the wxWindows library, aborting.");
2458 }
2459
0de868d9
VZ
2460#ifdef TEST_USLEEP
2461 puts("Sleeping for 3 seconds... z-z-z-z-z...");
2462 wxUsleep(3000);
2463#endif // TEST_USLEEP
2464
d34bce84
VZ
2465#ifdef TEST_CMDLINE
2466 static const wxCmdLineEntryDesc cmdLineDesc[] =
2467 {
2468 { wxCMD_LINE_SWITCH, "v", "verbose", "be verbose" },
2469 { wxCMD_LINE_SWITCH, "q", "quiet", "be quiet" },
2470
2471 { wxCMD_LINE_OPTION, "o", "output", "output file" },
2472 { wxCMD_LINE_OPTION, "i", "input", "input dir" },
2473 { wxCMD_LINE_OPTION, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER },
1e245dc2 2474 { wxCMD_LINE_OPTION, "d", "date", "output file date", wxCMD_LINE_VAL_DATE },
d34bce84
VZ
2475
2476 { wxCMD_LINE_PARAM, NULL, NULL, "input file",
2477 wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_MULTIPLE },
2478
2479 { wxCMD_LINE_NONE }
2480 };
2481
2482 wxCmdLineParser parser(cmdLineDesc, argc, argv);
2483
2484 switch ( parser.Parse() )
2485 {
2486 case -1:
2487 wxLogMessage("Help was given, terminating.");
2488 break;
2489
2490 case 0:
2491 ShowCmdLine(parser);
2492 break;
2493
2494 default:
2495 wxLogMessage("Syntax error detected, aborting.");
2496 break;
2497 }
2498#endif // TEST_CMDLINE
2499
9fc3ad34 2500#ifdef TEST_STRINGS
299fcbfe
VZ
2501 if ( 0 )
2502 {
2503 TestPChar();
2504 TestString();
2505 }
f0f951fa
VZ
2506 if ( 0 )
2507 {
7c968cee 2508 TestStringConstruction();
f0f951fa 2509 TestStringSub();
d71fa6fb 2510 TestStringFormat();
bbf8fc53 2511 TestStringFind();
7c968cee 2512 TestStringTokenizer();
ee6e1b1d 2513 }
9fc3ad34
VZ
2514#endif // TEST_STRINGS
2515
e87271f3
VZ
2516#ifdef TEST_ARRAYS
2517 wxArrayString a1;
2518 a1.Add("tiger");
2519 a1.Add("cat");
2520 a1.Add("lion");
2521 a1.Add("dog");
2522 a1.Add("human");
2523 a1.Add("ape");
2524
2525 puts("*** Initially:");
2526
2527 PrintArray("a1", a1);
2528
2529 wxArrayString a2(a1);
2530 PrintArray("a2", a2);
2531
2532 wxSortedArrayString a3(a1);
2533 PrintArray("a3", a3);
2534
2535 puts("*** After deleting a string from a1");
2536 a1.Remove(2);
2537
2538 PrintArray("a1", a1);
2539 PrintArray("a2", a2);
2540 PrintArray("a3", a3);
2541
2542 puts("*** After reassigning a1 to a2 and a3");
2543 a3 = a2 = a1;
2544 PrintArray("a2", a2);
2545 PrintArray("a3", a3);
2546#endif // TEST_ARRAYS
2547
1944c6bd
VZ
2548#ifdef TEST_DIR
2549 TestDirEnum();
2550#endif // TEST_DIR
2551
d93c719a
VZ
2552#ifdef TEST_EXECUTE
2553 TestExecute();
2554#endif // TEST_EXECUTE
2555
ee6e1b1d
VZ
2556#ifdef TEST_FILECONF
2557 TestFileConfRead();
2558#endif // TEST_FILECONF
2559
378b05f7
VZ
2560#ifdef TEST_LOG
2561 wxString s;
2562 for ( size_t n = 0; n < 8000; n++ )
2563 {
2564 s << (char)('A' + (n % 26));
2565 }
2566
2567 wxString msg;
2568 msg.Printf("A very very long message: '%s', the end!\n", s.c_str());
2569
2570 // this one shouldn't be truncated
2571 printf(msg);
2572
2573 // but this one will because log functions use fixed size buffer
b568d04f
VZ
2574 // (note that it doesn't need '\n' at the end neither - will be added
2575 // by wxLog anyhow)
2576 wxLogMessage("A very very long message 2: '%s', the end!", s.c_str());
378b05f7
VZ
2577#endif // TEST_LOG
2578
e87271f3 2579#ifdef TEST_THREADS
696e1ea0
VZ
2580 int nCPUs = wxThread::GetCPUCount();
2581 printf("This system has %d CPUs\n", nCPUs);
2582 if ( nCPUs != -1 )
2583 wxThread::SetConcurrency(nCPUs);
ef8d96c2 2584
9fc3ad34
VZ
2585 if ( argc > 1 && argv[1][0] == 't' )
2586 wxLog::AddTraceMask("thread");
b568d04f 2587
4c460b34 2588 if ( 1 )
2f02cb89 2589 TestDetachedThreads();
4c460b34 2590 if ( 1 )
2f02cb89 2591 TestJoinableThreads();
4c460b34 2592 if ( 1 )
2f02cb89
VZ
2593 TestThreadSuspend();
2594 if ( 1 )
2595 TestThreadDelete();
2596
e87271f3 2597#endif // TEST_THREADS
37667812 2598
b76b015e 2599#ifdef TEST_LONGLONG
2a310492
VZ
2600 // seed pseudo random generator
2601 srand((unsigned)time(NULL));
2602
b76b015e 2603 if ( 0 )
2a310492 2604 {
b76b015e 2605 TestSpeed();
2a310492
VZ
2606 }
2607 TestMultiplication();
2608 if ( 0 )
2609 {
b76b015e 2610 TestDivision();
2a310492
VZ
2611 TestAddition();
2612 TestLongLongConversion();
2613 TestBitOperations();
2614 }
b76b015e
VZ
2615#endif // TEST_LONGLONG
2616
2c8e4738
VZ
2617#ifdef TEST_HASH
2618 TestHash();
2619#endif // TEST_HASH
2620
696e1ea0
VZ
2621#ifdef TEST_MIME
2622 TestMimeEnum();
2623#endif // TEST_MIME
2624
2c8e4738 2625#ifdef TEST_SOCKETS
9fc3cba7 2626 if ( 1 )
ccdb23df
VZ
2627 TestSocketServer();
2628 if ( 0 )
8e907a13 2629 {
8e907a13 2630 TestSocketClient();
8e907a13 2631 TestProtocolFtp();
8dfea369 2632 }
2c8e4738
VZ
2633#endif // TEST_SOCKETS
2634
d31b7b68
VZ
2635#ifdef TEST_TIMER
2636 TestStopWatch();
2637#endif // TEST_TIMER
2638
2639#ifdef TEST_DATETIME
0de868d9 2640 if ( 0 )
299fcbfe 2641 {
9d9b7755
VZ
2642 TestTimeSet();
2643 TestTimeStatic();
2644 TestTimeRange();
2645 TestTimeZones();
2646 TestTimeTicks();
2647 TestTimeJDN();
2648 TestTimeDST();
2649 TestTimeWDays();
2650 TestTimeWNumber();
2651 TestTimeParse();
2652 TestTimeFormat();
2653 TestTimeArithmetics();
41acf5c0 2654 }
0de868d9 2655 TestTimeHolidays();
9d9b7755
VZ
2656 if ( 0 )
2657 TestInteractive();
d31b7b68 2658#endif // TEST_DATETIME
b76b015e 2659
37667812
VZ
2660 wxUninitialize();
2661
2662 return 0;
2663}