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