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