]> git.saurik.com Git - wxWidgets.git/blob - samples/console/console.cpp
Better behaviour on NT (no dialogs when searching drives)
[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_DLLLOADER
43 //#define TEST_EXECUTE
44 //#define TEST_FILE
45 //#define TEST_FILECONF
46 //#define TEST_HASH
47 //#define TEST_LIST
48 //#define TEST_LOG
49 //#define TEST_LONGLONG
50 //#define TEST_MIME
51 //#define TEST_INFO_FUNCTIONS
52 //#define TEST_SOCKETS
53 //#define TEST_STRINGS
54 //#define TEST_THREADS
55 //#define TEST_TIMER
56 //#define TEST_VCARD
57 //#define TEST_WCHAR
58 //#define TEST_ZIP
59
60 // ----------------------------------------------------------------------------
61 // test class for container objects
62 // ----------------------------------------------------------------------------
63
64 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
65
66 class Bar // Foo is already taken in the hash test
67 {
68 public:
69 Bar(const wxString& name) : m_name(name) { ms_bars++; }
70 ~Bar() { ms_bars--; }
71
72 static size_t GetNumber() { return ms_bars; }
73
74 const char *GetName() const { return m_name; }
75
76 private:
77 wxString m_name;
78
79 static size_t ms_bars;
80 };
81
82 size_t Bar::ms_bars = 0;
83
84 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
85
86 // ============================================================================
87 // implementation
88 // ============================================================================
89
90 // ----------------------------------------------------------------------------
91 // helper functions
92 // ----------------------------------------------------------------------------
93
94 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
95
96 // replace TABs with \t and CRs with \n
97 static wxString MakePrintable(const wxChar *s)
98 {
99 wxString str(s);
100 (void)str.Replace(_T("\t"), _T("\\t"));
101 (void)str.Replace(_T("\n"), _T("\\n"));
102 (void)str.Replace(_T("\r"), _T("\\r"));
103
104 return str;
105 }
106
107 #endif // MakePrintable() is used
108
109 // ----------------------------------------------------------------------------
110 // wxCmdLineParser
111 // ----------------------------------------------------------------------------
112
113 #ifdef TEST_CMDLINE
114
115 #include <wx/cmdline.h>
116 #include <wx/datetime.h>
117
118 static void ShowCmdLine(const wxCmdLineParser& parser)
119 {
120 wxString s = "Input files: ";
121
122 size_t count = parser.GetParamCount();
123 for ( size_t param = 0; param < count; param++ )
124 {
125 s << parser.GetParam(param) << ' ';
126 }
127
128 s << '\n'
129 << "Verbose:\t" << (parser.Found("v") ? "yes" : "no") << '\n'
130 << "Quiet:\t" << (parser.Found("q") ? "yes" : "no") << '\n';
131
132 wxString strVal;
133 long lVal;
134 wxDateTime dt;
135 if ( parser.Found("o", &strVal) )
136 s << "Output file:\t" << strVal << '\n';
137 if ( parser.Found("i", &strVal) )
138 s << "Input dir:\t" << strVal << '\n';
139 if ( parser.Found("s", &lVal) )
140 s << "Size:\t" << lVal << '\n';
141 if ( parser.Found("d", &dt) )
142 s << "Date:\t" << dt.FormatISODate() << '\n';
143 if ( parser.Found("project_name", &strVal) )
144 s << "Project:\t" << strVal << '\n';
145
146 wxLogMessage(s);
147 }
148
149 #endif // TEST_CMDLINE
150
151 // ----------------------------------------------------------------------------
152 // wxDir
153 // ----------------------------------------------------------------------------
154
155 #ifdef TEST_DIR
156
157 #include <wx/dir.h>
158
159 static void TestDirEnumHelper(wxDir& dir,
160 int flags = wxDIR_DEFAULT,
161 const wxString& filespec = wxEmptyString)
162 {
163 wxString filename;
164
165 if ( !dir.IsOpened() )
166 return;
167
168 bool cont = dir.GetFirst(&filename, filespec, flags);
169 while ( cont )
170 {
171 printf("\t%s\n", filename.c_str());
172
173 cont = dir.GetNext(&filename);
174 }
175
176 puts("");
177 }
178
179 static void TestDirEnum()
180 {
181 wxDir dir(wxGetCwd());
182
183 puts("Enumerating everything in current directory:");
184 TestDirEnumHelper(dir);
185
186 puts("Enumerating really everything in current directory:");
187 TestDirEnumHelper(dir, wxDIR_DEFAULT | wxDIR_DOTDOT);
188
189 puts("Enumerating object files in current directory:");
190 TestDirEnumHelper(dir, wxDIR_DEFAULT, "*.o");
191
192 puts("Enumerating directories in current directory:");
193 TestDirEnumHelper(dir, wxDIR_DIRS);
194
195 puts("Enumerating files in current directory:");
196 TestDirEnumHelper(dir, wxDIR_FILES);
197
198 puts("Enumerating files including hidden in current directory:");
199 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
200
201 #ifdef __UNIX__
202 dir.Open("/");
203 #elif defined(__WXMSW__)
204 dir.Open("c:\\");
205 #else
206 #error "don't know where the root directory is"
207 #endif
208
209 puts("Enumerating everything in root directory:");
210 TestDirEnumHelper(dir, wxDIR_DEFAULT);
211
212 puts("Enumerating directories in root directory:");
213 TestDirEnumHelper(dir, wxDIR_DIRS);
214
215 puts("Enumerating files in root directory:");
216 TestDirEnumHelper(dir, wxDIR_FILES);
217
218 puts("Enumerating files including hidden in root directory:");
219 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
220
221 puts("Enumerating files in non existing directory:");
222 wxDir dirNo("nosuchdir");
223 TestDirEnumHelper(dirNo);
224 }
225
226 #endif // TEST_DIR
227
228 // ----------------------------------------------------------------------------
229 // wxDllLoader
230 // ----------------------------------------------------------------------------
231
232 #ifdef TEST_DLLLOADER
233
234 #include <wx/dynlib.h>
235
236 static void TestDllLoad()
237 {
238 #if defined(__WXMSW__)
239 static const wxChar *LIB_NAME = _T("kernel32.dll");
240 static const wxChar *FUNC_NAME = _T("lstrlenA");
241 #elif defined(__UNIX__)
242 // weird: using just libc.so does *not* work!
243 static const wxChar *LIB_NAME = _T("/lib/libc-2.0.7.so");
244 static const wxChar *FUNC_NAME = _T("strlen");
245 #else
246 #error "don't know how to test wxDllLoader on this platform"
247 #endif
248
249 puts("*** testing wxDllLoader ***\n");
250
251 wxDllType dllHandle = wxDllLoader::LoadLibrary(LIB_NAME);
252 if ( !dllHandle )
253 {
254 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME);
255 }
256 else
257 {
258 typedef int (*strlenType)(char *);
259 strlenType pfnStrlen = (strlenType)wxDllLoader::GetSymbol(dllHandle, FUNC_NAME);
260 if ( !pfnStrlen )
261 {
262 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
263 FUNC_NAME, LIB_NAME);
264 }
265 else
266 {
267 if ( pfnStrlen("foo") != 3 )
268 {
269 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
270 }
271 else
272 {
273 puts("... ok");
274 }
275 }
276
277 wxDllLoader::UnloadLibrary(dllHandle);
278 }
279 }
280
281 #endif // TEST_DLLLOADER
282
283 // ----------------------------------------------------------------------------
284 // wxExecute
285 // ----------------------------------------------------------------------------
286
287 #ifdef TEST_EXECUTE
288
289 #include <wx/utils.h>
290
291 static void TestExecute()
292 {
293 puts("*** testing wxExecute ***");
294
295 #ifdef __UNIX__
296 #define COMMAND "echo hi"
297 #define SHELL_COMMAND "echo hi from shell"
298 #define REDIRECT_COMMAND "date"
299 #elif defined(__WXMSW__)
300 #define COMMAND "command.com -c 'echo hi'"
301 #define SHELL_COMMAND "echo hi"
302 #define REDIRECT_COMMAND COMMAND
303 #else
304 #error "no command to exec"
305 #endif // OS
306
307 printf("Testing wxShell: ");
308 fflush(stdout);
309 if ( wxShell(SHELL_COMMAND) )
310 puts("Ok.");
311 else
312 puts("ERROR.");
313
314 printf("Testing wxExecute: ");
315 fflush(stdout);
316 if ( wxExecute(COMMAND, TRUE /* sync */) == 0 )
317 puts("Ok.");
318 else
319 puts("ERROR.");
320
321 #if 0 // no, it doesn't work (yet?)
322 printf("Testing async wxExecute: ");
323 fflush(stdout);
324 if ( wxExecute(COMMAND) != 0 )
325 puts("Ok (command launched).");
326 else
327 puts("ERROR.");
328 #endif // 0
329
330 printf("Testing wxExecute with redirection:\n");
331 wxArrayString output;
332 if ( wxExecute(REDIRECT_COMMAND, output) != 0 )
333 {
334 puts("ERROR.");
335 }
336 else
337 {
338 size_t count = output.GetCount();
339 for ( size_t n = 0; n < count; n++ )
340 {
341 printf("\t%s\n", output[n].c_str());
342 }
343
344 puts("Ok.");
345 }
346 }
347
348 #endif // TEST_EXECUTE
349
350 // ----------------------------------------------------------------------------
351 // file
352 // ----------------------------------------------------------------------------
353
354 #ifdef TEST_FILE
355
356 #include <wx/file.h>
357 #include <wx/textfile.h>
358
359 static void TestFileRead()
360 {
361 puts("*** wxFile read test ***");
362
363 wxFile file(_T("testdata.fc"));
364 if ( file.IsOpened() )
365 {
366 printf("File length: %lu\n", file.Length());
367
368 puts("File dump:\n----------");
369
370 static const size_t len = 1024;
371 char buf[len];
372 for ( ;; )
373 {
374 off_t nRead = file.Read(buf, len);
375 if ( nRead == wxInvalidOffset )
376 {
377 printf("Failed to read the file.");
378 break;
379 }
380
381 fwrite(buf, nRead, 1, stdout);
382
383 if ( nRead < len )
384 break;
385 }
386
387 puts("----------");
388 }
389 else
390 {
391 printf("ERROR: can't open test file.\n");
392 }
393
394 puts("");
395 }
396
397 static void TestTextFileRead()
398 {
399 puts("*** wxTextFile read test ***");
400
401 wxTextFile file(_T("testdata.fc"));
402 if ( file.Open() )
403 {
404 printf("Number of lines: %u\n", file.GetLineCount());
405 printf("Last line: '%s'\n", file.GetLastLine().c_str());
406 }
407 else
408 {
409 printf("ERROR: can't open '%s'\n", file.GetName());
410 }
411
412 puts("");
413 }
414
415 #endif // TEST_FILE
416
417 // ----------------------------------------------------------------------------
418 // wxFileConfig
419 // ----------------------------------------------------------------------------
420
421 #ifdef TEST_FILECONF
422
423 #include <wx/confbase.h>
424 #include <wx/fileconf.h>
425
426 static const struct FileConfTestData
427 {
428 const wxChar *name; // value name
429 const wxChar *value; // the value from the file
430 } fcTestData[] =
431 {
432 { _T("value1"), _T("one") },
433 { _T("value2"), _T("two") },
434 { _T("novalue"), _T("default") },
435 };
436
437 static void TestFileConfRead()
438 {
439 puts("*** testing wxFileConfig loading/reading ***");
440
441 wxFileConfig fileconf(_T("test"), wxEmptyString,
442 _T("testdata.fc"), wxEmptyString,
443 wxCONFIG_USE_RELATIVE_PATH);
444
445 // test simple reading
446 puts("\nReading config file:");
447 wxString defValue(_T("default")), value;
448 for ( size_t n = 0; n < WXSIZEOF(fcTestData); n++ )
449 {
450 const FileConfTestData& data = fcTestData[n];
451 value = fileconf.Read(data.name, defValue);
452 printf("\t%s = %s ", data.name, value.c_str());
453 if ( value == data.value )
454 {
455 puts("(ok)");
456 }
457 else
458 {
459 printf("(ERROR: should be %s)\n", data.value);
460 }
461 }
462
463 // test enumerating the entries
464 puts("\nEnumerating all root entries:");
465 long dummy;
466 wxString name;
467 bool cont = fileconf.GetFirstEntry(name, dummy);
468 while ( cont )
469 {
470 printf("\t%s = %s\n",
471 name.c_str(),
472 fileconf.Read(name.c_str(), _T("ERROR")).c_str());
473
474 cont = fileconf.GetNextEntry(name, dummy);
475 }
476 }
477
478 #endif // TEST_FILECONF
479
480 // ----------------------------------------------------------------------------
481 // wxHashTable
482 // ----------------------------------------------------------------------------
483
484 #ifdef TEST_HASH
485
486 #include <wx/hash.h>
487
488 struct Foo
489 {
490 Foo(int n_) { n = n_; count++; }
491 ~Foo() { count--; }
492
493 int n;
494
495 static size_t count;
496 };
497
498 size_t Foo::count = 0;
499
500 WX_DECLARE_LIST(Foo, wxListFoos);
501 WX_DECLARE_HASH(Foo, wxListFoos, wxHashFoos);
502
503 #include <wx/listimpl.cpp>
504
505 WX_DEFINE_LIST(wxListFoos);
506
507 static void TestHash()
508 {
509 puts("*** Testing wxHashTable ***\n");
510
511 {
512 wxHashFoos hash;
513 hash.DeleteContents(TRUE);
514
515 printf("Hash created: %u foos in hash, %u foos totally\n",
516 hash.GetCount(), Foo::count);
517
518 static const int hashTestData[] =
519 {
520 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
521 };
522
523 size_t n;
524 for ( n = 0; n < WXSIZEOF(hashTestData); n++ )
525 {
526 hash.Put(hashTestData[n], n, new Foo(n));
527 }
528
529 printf("Hash filled: %u foos in hash, %u foos totally\n",
530 hash.GetCount(), Foo::count);
531
532 puts("Hash access test:");
533 for ( n = 0; n < WXSIZEOF(hashTestData); n++ )
534 {
535 printf("\tGetting element with key %d, value %d: ",
536 hashTestData[n], n);
537 Foo *foo = hash.Get(hashTestData[n], n);
538 if ( !foo )
539 {
540 printf("ERROR, not found.\n");
541 }
542 else
543 {
544 printf("%d (%s)\n", foo->n,
545 (size_t)foo->n == n ? "ok" : "ERROR");
546 }
547 }
548
549 printf("\nTrying to get an element not in hash: ");
550
551 if ( hash.Get(1234) || hash.Get(1, 0) )
552 {
553 puts("ERROR: found!");
554 }
555 else
556 {
557 puts("ok (not found)");
558 }
559 }
560
561 printf("Hash destroyed: %u foos left\n", Foo::count);
562 }
563
564 #endif // TEST_HASH
565
566 // ----------------------------------------------------------------------------
567 // wxList
568 // ----------------------------------------------------------------------------
569
570 #ifdef TEST_LIST
571
572 #include <wx/list.h>
573
574 WX_DECLARE_LIST(Bar, wxListBars);
575 #include <wx/listimpl.cpp>
576 WX_DEFINE_LIST(wxListBars);
577
578 static void TestListCtor()
579 {
580 puts("*** Testing wxList construction ***\n");
581
582 {
583 wxListBars list1;
584 list1.Append(new Bar(_T("first")));
585 list1.Append(new Bar(_T("second")));
586
587 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
588 list1.GetCount(), Bar::GetNumber());
589
590 wxListBars list2;
591 list2 = list1;
592
593 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
594 list1.GetCount(), list2.GetCount(), Bar::GetNumber());
595
596 list1.DeleteContents(TRUE);
597 }
598
599 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
600 }
601
602 #endif // TEST_LIST
603
604 // ----------------------------------------------------------------------------
605 // MIME types
606 // ----------------------------------------------------------------------------
607
608 #ifdef TEST_MIME
609
610 #include <wx/mimetype.h>
611
612 static wxMimeTypesManager g_mimeManager;
613
614 static void TestMimeEnum()
615 {
616 wxArrayString mimetypes;
617
618 size_t count = g_mimeManager.EnumAllFileTypes(mimetypes);
619
620 printf("*** All %u known filetypes: ***\n", count);
621
622 wxArrayString exts;
623 wxString desc;
624
625 for ( size_t n = 0; n < count; n++ )
626 {
627 wxFileType *filetype = g_mimeManager.GetFileTypeFromMimeType(mimetypes[n]);
628 if ( !filetype )
629 {
630 printf("nothing known about the filetype '%s'!\n",
631 mimetypes[n].c_str());
632 continue;
633 }
634
635 filetype->GetDescription(&desc);
636 filetype->GetExtensions(exts);
637
638 filetype->GetIcon(NULL);
639
640 wxString extsAll;
641 for ( size_t e = 0; e < exts.GetCount(); e++ )
642 {
643 if ( e > 0 )
644 extsAll << _T(", ");
645 extsAll += exts[e];
646 }
647
648 printf("\t%s: %s (%s)\n",
649 mimetypes[n].c_str(), desc.c_str(), extsAll.c_str());
650 }
651 }
652
653 static void TestMimeOverride()
654 {
655 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
656
657 wxString mailcap = _T("/tmp/mailcap"),
658 mimetypes = _T("/tmp/mime.types");
659
660 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
661 mailcap.c_str(),
662 g_mimeManager.ReadMailcap(mailcap) ? _T("ok") : _T("ERROR"));
663 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
664 mimetypes.c_str(),
665 g_mimeManager.ReadMimeTypes(mimetypes) ? _T("ok") : _T("ERROR"));
666 }
667
668 static void TestMimeFilename()
669 {
670 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
671
672 static const wxChar *filenames[] =
673 {
674 _T("readme.txt"),
675 _T("document.pdf"),
676 _T("image.gif"),
677 };
678
679 for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
680 {
681 const wxString fname = filenames[n];
682 wxString ext = fname.AfterLast(_T('.'));
683 wxFileType *ft = g_mimeManager.GetFileTypeFromExtension(ext);
684 if ( !ft )
685 {
686 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext.c_str());
687 }
688 else
689 {
690 wxString desc;
691 if ( !ft->GetDescription(&desc) )
692 desc = _T("<no description>");
693
694 wxString cmd;
695 if ( !ft->GetOpenCommand(&cmd,
696 wxFileType::MessageParameters(fname, _T(""))) )
697 cmd = _T("<no command available>");
698
699 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
700 fname.c_str(), desc.c_str(), cmd.c_str());
701
702 delete ft;
703 }
704 }
705 }
706
707 #endif // TEST_MIME
708
709 // ----------------------------------------------------------------------------
710 // misc information functions
711 // ----------------------------------------------------------------------------
712
713 #ifdef TEST_INFO_FUNCTIONS
714
715 #include <wx/utils.h>
716
717 static void TestOsInfo()
718 {
719 puts("*** Testing OS info functions ***\n");
720
721 int major, minor;
722 wxGetOsVersion(&major, &minor);
723 printf("Running under: %s, version %d.%d\n",
724 wxGetOsDescription().c_str(), major, minor);
725
726 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
727
728 printf("Host name is %s (%s).\n",
729 wxGetHostName().c_str(), wxGetFullHostName().c_str());
730
731 puts("");
732 }
733
734 static void TestUserInfo()
735 {
736 puts("*** Testing user info functions ***\n");
737
738 printf("User id is:\t%s\n", wxGetUserId().c_str());
739 printf("User name is:\t%s\n", wxGetUserName().c_str());
740 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
741 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
742
743 puts("");
744 }
745
746 #endif // TEST_INFO_FUNCTIONS
747
748 // ----------------------------------------------------------------------------
749 // long long
750 // ----------------------------------------------------------------------------
751
752 #ifdef TEST_LONGLONG
753
754 #include <wx/longlong.h>
755 #include <wx/timer.h>
756
757 // make a 64 bit number from 4 16 bit ones
758 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
759
760 // get a random 64 bit number
761 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
762
763 #if wxUSE_LONGLONG_WX
764 inline bool operator==(const wxLongLongWx& a, const wxLongLongNative& b)
765 { return a.GetHi() == b.GetHi() && a.GetLo() == b.GetLo(); }
766 inline bool operator==(const wxLongLongNative& a, const wxLongLongWx& b)
767 { return a.GetHi() == b.GetHi() && a.GetLo() == b.GetLo(); }
768 #endif // wxUSE_LONGLONG_WX
769
770 static void TestSpeed()
771 {
772 static const long max = 100000000;
773 long n;
774
775 {
776 wxStopWatch sw;
777
778 long l = 0;
779 for ( n = 0; n < max; n++ )
780 {
781 l += n;
782 }
783
784 printf("Summing longs took %ld milliseconds.\n", sw.Time());
785 }
786
787 #if wxUSE_LONGLONG_NATIVE
788 {
789 wxStopWatch sw;
790
791 wxLongLong_t l = 0;
792 for ( n = 0; n < max; n++ )
793 {
794 l += n;
795 }
796
797 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw.Time());
798 }
799 #endif // wxUSE_LONGLONG_NATIVE
800
801 {
802 wxStopWatch sw;
803
804 wxLongLong l;
805 for ( n = 0; n < max; n++ )
806 {
807 l += n;
808 }
809
810 printf("Summing wxLongLongs took %ld milliseconds.\n", sw.Time());
811 }
812 }
813
814 static void TestLongLongConversion()
815 {
816 puts("*** Testing wxLongLong conversions ***\n");
817
818 wxLongLong a;
819 size_t nTested = 0;
820 for ( size_t n = 0; n < 100000; n++ )
821 {
822 a = RAND_LL();
823
824 #if wxUSE_LONGLONG_NATIVE
825 wxLongLongNative b(a.GetHi(), a.GetLo());
826
827 wxASSERT_MSG( a == b, "conversions failure" );
828 #else
829 puts("Can't do it without native long long type, test skipped.");
830
831 return;
832 #endif // wxUSE_LONGLONG_NATIVE
833
834 if ( !(nTested % 1000) )
835 {
836 putchar('.');
837 fflush(stdout);
838 }
839
840 nTested++;
841 }
842
843 puts(" done!");
844 }
845
846 static void TestMultiplication()
847 {
848 puts("*** Testing wxLongLong multiplication ***\n");
849
850 wxLongLong a, b;
851 size_t nTested = 0;
852 for ( size_t n = 0; n < 100000; n++ )
853 {
854 a = RAND_LL();
855 b = RAND_LL();
856
857 #if wxUSE_LONGLONG_NATIVE
858 wxLongLongNative aa(a.GetHi(), a.GetLo());
859 wxLongLongNative bb(b.GetHi(), b.GetLo());
860
861 wxASSERT_MSG( a*b == aa*bb, "multiplication failure" );
862 #else // !wxUSE_LONGLONG_NATIVE
863 puts("Can't do it without native long long type, test skipped.");
864
865 return;
866 #endif // wxUSE_LONGLONG_NATIVE
867
868 if ( !(nTested % 1000) )
869 {
870 putchar('.');
871 fflush(stdout);
872 }
873
874 nTested++;
875 }
876
877 puts(" done!");
878 }
879
880 static void TestDivision()
881 {
882 puts("*** Testing wxLongLong division ***\n");
883
884 wxLongLong q, r;
885 size_t nTested = 0;
886 for ( size_t n = 0; n < 100000; n++ )
887 {
888 // get a random wxLongLong (shifting by 12 the MSB ensures that the
889 // multiplication will not overflow)
890 wxLongLong ll = MAKE_LL((rand() >> 12), rand(), rand(), rand());
891
892 // get a random long (not wxLongLong for now) to divide it with
893 long l = rand();
894 q = ll / l;
895 r = ll % l;
896
897 #if wxUSE_LONGLONG_NATIVE
898 wxLongLongNative m(ll.GetHi(), ll.GetLo());
899
900 wxLongLongNative p = m / l, s = m % l;
901 wxASSERT_MSG( q == p && r == s, "division failure" );
902 #else // !wxUSE_LONGLONG_NATIVE
903 // verify the result
904 wxASSERT_MSG( ll == q*l + r, "division failure" );
905 #endif // wxUSE_LONGLONG_NATIVE
906
907 if ( !(nTested % 1000) )
908 {
909 putchar('.');
910 fflush(stdout);
911 }
912
913 nTested++;
914 }
915
916 puts(" done!");
917 }
918
919 static void TestAddition()
920 {
921 puts("*** Testing wxLongLong addition ***\n");
922
923 wxLongLong a, b, c;
924 size_t nTested = 0;
925 for ( size_t n = 0; n < 100000; n++ )
926 {
927 a = RAND_LL();
928 b = RAND_LL();
929 c = a + b;
930
931 #if wxUSE_LONGLONG_NATIVE
932 wxASSERT_MSG( c == wxLongLongNative(a.GetHi(), a.GetLo()) +
933 wxLongLongNative(b.GetHi(), b.GetLo()),
934 "addition failure" );
935 #else // !wxUSE_LONGLONG_NATIVE
936 wxASSERT_MSG( c - b == a, "addition failure" );
937 #endif // wxUSE_LONGLONG_NATIVE
938
939 if ( !(nTested % 1000) )
940 {
941 putchar('.');
942 fflush(stdout);
943 }
944
945 nTested++;
946 }
947
948 puts(" done!");
949 }
950
951 static void TestBitOperations()
952 {
953 puts("*** Testing wxLongLong bit operation ***\n");
954
955 wxLongLong ll;
956 size_t nTested = 0;
957 for ( size_t n = 0; n < 100000; n++ )
958 {
959 ll = RAND_LL();
960
961 #if wxUSE_LONGLONG_NATIVE
962 for ( size_t n = 0; n < 33; n++ )
963 {
964 }
965 #else // !wxUSE_LONGLONG_NATIVE
966 puts("Can't do it without native long long type, test skipped.");
967
968 return;
969 #endif // wxUSE_LONGLONG_NATIVE
970
971 if ( !(nTested % 1000) )
972 {
973 putchar('.');
974 fflush(stdout);
975 }
976
977 nTested++;
978 }
979
980 puts(" done!");
981 }
982
983 static void TestLongLongComparison()
984 {
985 puts("*** Testing wxLongLong comparison ***\n");
986
987 static const long testLongs[] =
988 {
989 0,
990 1,
991 -1,
992 LONG_MAX,
993 LONG_MIN,
994 0x1234,
995 -0x1234
996 };
997
998 static const long ls[2] =
999 {
1000 0x1234,
1001 -0x1234,
1002 };
1003
1004 wxLongLongWx lls[2];
1005 lls[0] = ls[0];
1006 lls[1] = ls[1];
1007
1008 for ( size_t n = 0; n < WXSIZEOF(testLongs); n++ )
1009 {
1010 bool res;
1011
1012 for ( size_t m = 0; m < WXSIZEOF(lls); m++ )
1013 {
1014 res = lls[m] > testLongs[n];
1015 printf("0x%lx > 0x%lx is %s (%s)\n",
1016 ls[m], testLongs[n], res ? "true" : "false",
1017 res == (ls[m] > testLongs[n]) ? "ok" : "ERROR");
1018
1019 res = lls[m] < testLongs[n];
1020 printf("0x%lx < 0x%lx is %s (%s)\n",
1021 ls[m], testLongs[n], res ? "true" : "false",
1022 res == (ls[m] < testLongs[n]) ? "ok" : "ERROR");
1023
1024 res = lls[m] == testLongs[n];
1025 printf("0x%lx == 0x%lx is %s (%s)\n",
1026 ls[m], testLongs[n], res ? "true" : "false",
1027 res == (ls[m] == testLongs[n]) ? "ok" : "ERROR");
1028 }
1029 }
1030 }
1031
1032 #undef MAKE_LL
1033 #undef RAND_LL
1034
1035 #endif // TEST_LONGLONG
1036
1037 // ----------------------------------------------------------------------------
1038 // sockets
1039 // ----------------------------------------------------------------------------
1040
1041 #ifdef TEST_SOCKETS
1042
1043 #include <wx/socket.h>
1044 #include <wx/protocol/protocol.h>
1045 #include <wx/protocol/ftp.h>
1046 #include <wx/protocol/http.h>
1047
1048 static void TestSocketServer()
1049 {
1050 puts("*** Testing wxSocketServer ***\n");
1051
1052 static const int PORT = 3000;
1053
1054 wxIPV4address addr;
1055 addr.Service(PORT);
1056
1057 wxSocketServer *server = new wxSocketServer(addr);
1058 if ( !server->Ok() )
1059 {
1060 puts("ERROR: failed to bind");
1061
1062 return;
1063 }
1064
1065 for ( ;; )
1066 {
1067 printf("Server: waiting for connection on port %d...\n", PORT);
1068
1069 wxSocketBase *socket = server->Accept();
1070 if ( !socket )
1071 {
1072 puts("ERROR: wxSocketServer::Accept() failed.");
1073 break;
1074 }
1075
1076 puts("Server: got a client.");
1077
1078 server->SetTimeout(60); // 1 min
1079
1080 while ( socket->IsConnected() )
1081 {
1082 wxString s;
1083 char ch = '\0';
1084 for ( ;; )
1085 {
1086 if ( socket->Read(&ch, sizeof(ch)).Error() )
1087 {
1088 // don't log error if the client just close the connection
1089 if ( socket->IsConnected() )
1090 {
1091 puts("ERROR: in wxSocket::Read.");
1092 }
1093
1094 break;
1095 }
1096
1097 if ( ch == '\r' )
1098 continue;
1099
1100 if ( ch == '\n' )
1101 break;
1102
1103 s += ch;
1104 }
1105
1106 if ( ch != '\n' )
1107 {
1108 break;
1109 }
1110
1111 printf("Server: got '%s'.\n", s.c_str());
1112 if ( s == _T("bye") )
1113 {
1114 delete socket;
1115
1116 break;
1117 }
1118
1119 socket->Write(s.MakeUpper().c_str(), s.length());
1120 socket->Write("\r\n", 2);
1121 printf("Server: wrote '%s'.\n", s.c_str());
1122 }
1123
1124 puts("Server: lost a client.");
1125
1126 socket->Destroy();
1127 }
1128
1129 // same as "delete server" but is consistent with GUI programs
1130 server->Destroy();
1131 }
1132
1133 static void TestSocketClient()
1134 {
1135 puts("*** Testing wxSocketClient ***\n");
1136
1137 static const char *hostname = "www.wxwindows.org";
1138
1139 wxIPV4address addr;
1140 addr.Hostname(hostname);
1141 addr.Service(80);
1142
1143 printf("--- Attempting to connect to %s:80...\n", hostname);
1144
1145 wxSocketClient client;
1146 if ( !client.Connect(addr) )
1147 {
1148 printf("ERROR: failed to connect to %s\n", hostname);
1149 }
1150 else
1151 {
1152 printf("--- Connected to %s:%u...\n",
1153 addr.Hostname().c_str(), addr.Service());
1154
1155 char buf[8192];
1156
1157 // could use simply "GET" here I suppose
1158 wxString cmdGet =
1159 wxString::Format("GET http://%s/\r\n", hostname);
1160 client.Write(cmdGet, cmdGet.length());
1161 printf("--- Sent command '%s' to the server\n",
1162 MakePrintable(cmdGet).c_str());
1163 client.Read(buf, WXSIZEOF(buf));
1164 printf("--- Server replied:\n%s", buf);
1165 }
1166 }
1167
1168 static void TestProtocolFtp()
1169 {
1170 puts("*** Testing wxFTP download ***\n");
1171
1172 wxLog::AddTraceMask(_T("ftp"));
1173
1174 static const char *hostname = "ftp.wxwindows.org";
1175
1176 printf("--- Attempting to connect to %s:21...\n", hostname);
1177
1178 wxFTP ftp;
1179 if ( !ftp.Connect(hostname) )
1180 {
1181 printf("ERROR: failed to connect to %s\n", hostname);
1182 }
1183 else
1184 {
1185 printf("--- Connected to %s, current directory is '%s'\n",
1186 hostname, ftp.Pwd().c_str());
1187 if ( !ftp.ChDir(_T("pub")) )
1188 {
1189 puts("ERROR: failed to cd to pub");
1190 }
1191
1192 wxArrayString files;
1193 if ( !ftp.GetList(files) )
1194 {
1195 puts("ERROR: failed to get list of files");
1196 }
1197 else
1198 {
1199 printf("List of files under '%s':\n", ftp.Pwd().c_str());
1200 size_t count = files.GetCount();
1201 for ( size_t n = 0; n < count; n++ )
1202 {
1203 printf("\t%s\n", files[n].c_str());
1204 }
1205 puts("End of the file list");
1206 }
1207
1208 if ( !ftp.ChDir(_T("..")) )
1209 {
1210 puts("ERROR: failed to cd to ..");
1211 }
1212
1213 static const char *filename = "welcome.msg";
1214 wxInputStream *in = ftp.GetInputStream(filename);
1215 if ( !in )
1216 {
1217 puts("ERROR: couldn't get input stream");
1218 }
1219 else
1220 {
1221 size_t size = in->StreamSize();
1222 printf("Reading file %s (%u bytes)...", filename, size);
1223
1224 char *data = new char[size];
1225 if ( !in->Read(data, size) )
1226 {
1227 puts("ERROR: read error");
1228 }
1229 else
1230 {
1231 printf("\nContents of %s:\n%s\n", filename, data);
1232 }
1233
1234 delete [] data;
1235 delete in;
1236 }
1237 }
1238 }
1239
1240 static void TestProtocolFtpUpload()
1241 {
1242 puts("*** Testing wxFTP uploading ***\n");
1243
1244 wxLog::AddTraceMask(_T("ftp"));
1245
1246 static const char *hostname = "localhost";
1247
1248 printf("--- Attempting to connect to %s:21...\n", hostname);
1249
1250 wxFTP ftp;
1251 ftp.SetUser("zeitlin");
1252 ftp.SetPassword("insert your password here");
1253 if ( !ftp.Connect(hostname) )
1254 {
1255 printf("ERROR: failed to connect to %s\n", hostname);
1256 }
1257 else
1258 {
1259 printf("--- Connected to %s, current directory is '%s'\n",
1260 hostname, ftp.Pwd().c_str());
1261
1262 // upload a file
1263 static const char *file1 = "test1";
1264 static const char *file2 = "test2";
1265 wxOutputStream *out = ftp.GetOutputStream(file1);
1266 if ( out )
1267 {
1268 printf("--- Uploading to %s ---\n", file1);
1269 out->Write("First hello", 11);
1270 delete out;
1271 }
1272
1273 out = ftp.GetOutputStream(file2);
1274 if ( out )
1275 {
1276 printf("--- Uploading to %s ---\n", file1);
1277 out->Write("Second hello", 12);
1278 delete out;
1279 }
1280 }
1281 }
1282
1283 #endif // TEST_SOCKETS
1284
1285 // ----------------------------------------------------------------------------
1286 // timers
1287 // ----------------------------------------------------------------------------
1288
1289 #ifdef TEST_TIMER
1290
1291 #include <wx/timer.h>
1292 #include <wx/utils.h>
1293
1294 static void TestStopWatch()
1295 {
1296 puts("*** Testing wxStopWatch ***\n");
1297
1298 wxStopWatch sw;
1299 printf("Sleeping 3 seconds...");
1300 wxSleep(3);
1301 printf("\telapsed time: %ldms\n", sw.Time());
1302
1303 sw.Pause();
1304 printf("Sleeping 2 more seconds...");
1305 wxSleep(2);
1306 printf("\telapsed time: %ldms\n", sw.Time());
1307
1308 sw.Resume();
1309 printf("And 3 more seconds...");
1310 wxSleep(3);
1311 printf("\telapsed time: %ldms\n", sw.Time());
1312
1313 wxStopWatch sw2;
1314 puts("\nChecking for 'backwards clock' bug...");
1315 for ( size_t n = 0; n < 70; n++ )
1316 {
1317 sw2.Start();
1318
1319 for ( size_t m = 0; m < 100000; m++ )
1320 {
1321 if ( sw.Time() < 0 || sw2.Time() < 0 )
1322 {
1323 puts("\ntime is negative - ERROR!");
1324 }
1325 }
1326
1327 putchar('.');
1328 }
1329
1330 puts(", ok.");
1331 }
1332
1333 #endif // TEST_TIMER
1334
1335 // ----------------------------------------------------------------------------
1336 // vCard support
1337 // ----------------------------------------------------------------------------
1338
1339 #ifdef TEST_VCARD
1340
1341 #include <wx/vcard.h>
1342
1343 static void DumpVObject(size_t level, const wxVCardObject& vcard)
1344 {
1345 void *cookie;
1346 wxVCardObject *vcObj = vcard.GetFirstProp(&cookie);
1347 while ( vcObj )
1348 {
1349 printf("%s%s",
1350 wxString(_T('\t'), level).c_str(),
1351 vcObj->GetName().c_str());
1352
1353 wxString value;
1354 switch ( vcObj->GetType() )
1355 {
1356 case wxVCardObject::String:
1357 case wxVCardObject::UString:
1358 {
1359 wxString val;
1360 vcObj->GetValue(&val);
1361 value << _T('"') << val << _T('"');
1362 }
1363 break;
1364
1365 case wxVCardObject::Int:
1366 {
1367 unsigned int i;
1368 vcObj->GetValue(&i);
1369 value.Printf(_T("%u"), i);
1370 }
1371 break;
1372
1373 case wxVCardObject::Long:
1374 {
1375 unsigned long l;
1376 vcObj->GetValue(&l);
1377 value.Printf(_T("%lu"), l);
1378 }
1379 break;
1380
1381 case wxVCardObject::None:
1382 break;
1383
1384 case wxVCardObject::Object:
1385 value = _T("<node>");
1386 break;
1387
1388 default:
1389 value = _T("<unknown value type>");
1390 }
1391
1392 if ( !!value )
1393 printf(" = %s", value.c_str());
1394 putchar('\n');
1395
1396 DumpVObject(level + 1, *vcObj);
1397
1398 delete vcObj;
1399 vcObj = vcard.GetNextProp(&cookie);
1400 }
1401 }
1402
1403 static void DumpVCardAddresses(const wxVCard& vcard)
1404 {
1405 puts("\nShowing all addresses from vCard:\n");
1406
1407 size_t nAdr = 0;
1408 void *cookie;
1409 wxVCardAddress *addr = vcard.GetFirstAddress(&cookie);
1410 while ( addr )
1411 {
1412 wxString flagsStr;
1413 int flags = addr->GetFlags();
1414 if ( flags & wxVCardAddress::Domestic )
1415 {
1416 flagsStr << _T("domestic ");
1417 }
1418 if ( flags & wxVCardAddress::Intl )
1419 {
1420 flagsStr << _T("international ");
1421 }
1422 if ( flags & wxVCardAddress::Postal )
1423 {
1424 flagsStr << _T("postal ");
1425 }
1426 if ( flags & wxVCardAddress::Parcel )
1427 {
1428 flagsStr << _T("parcel ");
1429 }
1430 if ( flags & wxVCardAddress::Home )
1431 {
1432 flagsStr << _T("home ");
1433 }
1434 if ( flags & wxVCardAddress::Work )
1435 {
1436 flagsStr << _T("work ");
1437 }
1438
1439 printf("Address %u:\n"
1440 "\tflags = %s\n"
1441 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
1442 ++nAdr,
1443 flagsStr.c_str(),
1444 addr->GetPostOffice().c_str(),
1445 addr->GetExtAddress().c_str(),
1446 addr->GetStreet().c_str(),
1447 addr->GetLocality().c_str(),
1448 addr->GetRegion().c_str(),
1449 addr->GetPostalCode().c_str(),
1450 addr->GetCountry().c_str()
1451 );
1452
1453 delete addr;
1454 addr = vcard.GetNextAddress(&cookie);
1455 }
1456 }
1457
1458 static void DumpVCardPhoneNumbers(const wxVCard& vcard)
1459 {
1460 puts("\nShowing all phone numbers from vCard:\n");
1461
1462 size_t nPhone = 0;
1463 void *cookie;
1464 wxVCardPhoneNumber *phone = vcard.GetFirstPhoneNumber(&cookie);
1465 while ( phone )
1466 {
1467 wxString flagsStr;
1468 int flags = phone->GetFlags();
1469 if ( flags & wxVCardPhoneNumber::Voice )
1470 {
1471 flagsStr << _T("voice ");
1472 }
1473 if ( flags & wxVCardPhoneNumber::Fax )
1474 {
1475 flagsStr << _T("fax ");
1476 }
1477 if ( flags & wxVCardPhoneNumber::Cellular )
1478 {
1479 flagsStr << _T("cellular ");
1480 }
1481 if ( flags & wxVCardPhoneNumber::Modem )
1482 {
1483 flagsStr << _T("modem ");
1484 }
1485 if ( flags & wxVCardPhoneNumber::Home )
1486 {
1487 flagsStr << _T("home ");
1488 }
1489 if ( flags & wxVCardPhoneNumber::Work )
1490 {
1491 flagsStr << _T("work ");
1492 }
1493
1494 printf("Phone number %u:\n"
1495 "\tflags = %s\n"
1496 "\tvalue = %s\n",
1497 ++nPhone,
1498 flagsStr.c_str(),
1499 phone->GetNumber().c_str()
1500 );
1501
1502 delete phone;
1503 phone = vcard.GetNextPhoneNumber(&cookie);
1504 }
1505 }
1506
1507 static void TestVCardRead()
1508 {
1509 puts("*** Testing wxVCard reading ***\n");
1510
1511 wxVCard vcard(_T("vcard.vcf"));
1512 if ( !vcard.IsOk() )
1513 {
1514 puts("ERROR: couldn't load vCard.");
1515 }
1516 else
1517 {
1518 // read individual vCard properties
1519 wxVCardObject *vcObj = vcard.GetProperty("FN");
1520 wxString value;
1521 if ( vcObj )
1522 {
1523 vcObj->GetValue(&value);
1524 delete vcObj;
1525 }
1526 else
1527 {
1528 value = _T("<none>");
1529 }
1530
1531 printf("Full name retrieved directly: %s\n", value.c_str());
1532
1533
1534 if ( !vcard.GetFullName(&value) )
1535 {
1536 value = _T("<none>");
1537 }
1538
1539 printf("Full name from wxVCard API: %s\n", value.c_str());
1540
1541 // now show how to deal with multiply occuring properties
1542 DumpVCardAddresses(vcard);
1543 DumpVCardPhoneNumbers(vcard);
1544
1545 // and finally show all
1546 puts("\nNow dumping the entire vCard:\n"
1547 "-----------------------------\n");
1548
1549 DumpVObject(0, vcard);
1550 }
1551 }
1552
1553 static void TestVCardWrite()
1554 {
1555 puts("*** Testing wxVCard writing ***\n");
1556
1557 wxVCard vcard;
1558 if ( !vcard.IsOk() )
1559 {
1560 puts("ERROR: couldn't create vCard.");
1561 }
1562 else
1563 {
1564 // set some fields
1565 vcard.SetName("Zeitlin", "Vadim");
1566 vcard.SetFullName("Vadim Zeitlin");
1567 vcard.SetOrganization("wxWindows", "R&D");
1568
1569 // just dump the vCard back
1570 puts("Entire vCard follows:\n");
1571 puts(vcard.Write());
1572 }
1573 }
1574
1575 #endif // TEST_VCARD
1576
1577 // ----------------------------------------------------------------------------
1578 // wide char (Unicode) support
1579 // ----------------------------------------------------------------------------
1580
1581 #ifdef TEST_WCHAR
1582
1583 #include <wx/strconv.h>
1584 #include <wx/buffer.h>
1585
1586 static void TestUtf8()
1587 {
1588 puts("*** Testing UTF8 support ***\n");
1589
1590 wxString testString = "français";
1591 #if 0
1592 "************ French - Français ****************"
1593 "Juste un petit exemple pour dire que les français aussi"
1594 "ont à cœur de pouvoir utiliser tous leurs caractères ! :)";
1595 #endif
1596
1597 wxWCharBuffer wchBuf = testString.wc_str(wxConvUTF8);
1598 const wchar_t *pwz = (const wchar_t *)wchBuf;
1599 wxString testString2(pwz, wxConvLocal);
1600
1601 printf("Decoding '%s' => '%s'\n", testString.c_str(), testString2.c_str());
1602
1603 char *psz = "fran" "\xe7" "ais";
1604 size_t len = strlen(psz);
1605 wchar_t *pwz2 = new wchar_t[len + 1];
1606 for ( size_t n = 0; n <= len; n++ )
1607 {
1608 pwz2[n] = (wchar_t)(unsigned char)psz[n];
1609 }
1610
1611 wxString testString3(pwz2, wxConvUTF8);
1612 delete [] pwz2;
1613
1614 printf("Encoding '%s' -> '%s'\n", psz, testString3.c_str());
1615 }
1616
1617 #endif // TEST_WCHAR
1618
1619 // ----------------------------------------------------------------------------
1620 // ZIP stream
1621 // ----------------------------------------------------------------------------
1622
1623 #ifdef TEST_ZIP
1624
1625 #include "wx/zipstrm.h"
1626
1627 static void TestZipStreamRead()
1628 {
1629 puts("*** Testing ZIP reading ***\n");
1630
1631 wxZipInputStream istr(_T("idx.zip"), _T("IDX.txt"));
1632 printf("Archive size: %u\n", istr.GetSize());
1633
1634 puts("Dumping the file:");
1635 while ( !istr.Eof() )
1636 {
1637 putchar(istr.GetC());
1638 fflush(stdout);
1639 }
1640
1641 puts("\n----- done ------");
1642 }
1643
1644 #endif // TEST_ZIP
1645
1646 // ----------------------------------------------------------------------------
1647 // date time
1648 // ----------------------------------------------------------------------------
1649
1650 #ifdef TEST_DATETIME
1651
1652 #include <wx/date.h>
1653
1654 #include <wx/datetime.h>
1655
1656 // the test data
1657 struct Date
1658 {
1659 wxDateTime::wxDateTime_t day;
1660 wxDateTime::Month month;
1661 int year;
1662 wxDateTime::wxDateTime_t hour, min, sec;
1663 double jdn;
1664 wxDateTime::WeekDay wday;
1665 time_t gmticks, ticks;
1666
1667 void Init(const wxDateTime::Tm& tm)
1668 {
1669 day = tm.mday;
1670 month = tm.mon;
1671 year = tm.year;
1672 hour = tm.hour;
1673 min = tm.min;
1674 sec = tm.sec;
1675 jdn = 0.0;
1676 gmticks = ticks = -1;
1677 }
1678
1679 wxDateTime DT() const
1680 { return wxDateTime(day, month, year, hour, min, sec); }
1681
1682 bool SameDay(const wxDateTime::Tm& tm) const
1683 {
1684 return day == tm.mday && month == tm.mon && year == tm.year;
1685 }
1686
1687 wxString Format() const
1688 {
1689 wxString s;
1690 s.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
1691 hour, min, sec,
1692 wxDateTime::GetMonthName(month).c_str(),
1693 day,
1694 abs(wxDateTime::ConvertYearToBC(year)),
1695 year > 0 ? "AD" : "BC");
1696 return s;
1697 }
1698
1699 wxString FormatDate() const
1700 {
1701 wxString s;
1702 s.Printf("%02d-%s-%4d%s",
1703 day,
1704 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
1705 abs(wxDateTime::ConvertYearToBC(year)),
1706 year > 0 ? "AD" : "BC");
1707 return s;
1708 }
1709 };
1710
1711 static const Date testDates[] =
1712 {
1713 { 1, wxDateTime::Jan, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu, 0, -3600 },
1714 { 21, wxDateTime::Jan, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon, -1, -1 },
1715 { 29, wxDateTime::May, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat, 202219200, 202212000 },
1716 { 29, wxDateTime::Feb, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun, 194400000, 194396400 },
1717 { 1, wxDateTime::Jan, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon, -1, -1 },
1718 { 1, wxDateTime::Jan, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon, -1, -1 },
1719 { 15, wxDateTime::Oct, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri, -1, -1 },
1720 { 4, wxDateTime::Oct, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon, -1, -1 },
1721 { 1, wxDateTime::Mar, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu, -1, -1 },
1722 { 1, wxDateTime::Jan, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon, -1, -1 },
1723 { 31, wxDateTime::Dec, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun, -1, -1 },
1724 { 1, wxDateTime::Jan, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat, -1, -1 },
1725 { 12, wxDateTime::Aug, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri, -1, -1 },
1726 { 12, wxDateTime::Aug, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat, -1, -1 },
1727 { 24, wxDateTime::Nov, -4713, 00, 00, 00, -0.5, wxDateTime::Mon, -1, -1 },
1728 };
1729
1730 // this test miscellaneous static wxDateTime functions
1731 static void TestTimeStatic()
1732 {
1733 puts("\n*** wxDateTime static methods test ***");
1734
1735 // some info about the current date
1736 int year = wxDateTime::GetCurrentYear();
1737 printf("Current year %d is %sa leap one and has %d days.\n",
1738 year,
1739 wxDateTime::IsLeapYear(year) ? "" : "not ",
1740 wxDateTime::GetNumberOfDays(year));
1741
1742 wxDateTime::Month month = wxDateTime::GetCurrentMonth();
1743 printf("Current month is '%s' ('%s') and it has %d days\n",
1744 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
1745 wxDateTime::GetMonthName(month).c_str(),
1746 wxDateTime::GetNumberOfDays(month));
1747
1748 // leap year logic
1749 static const size_t nYears = 5;
1750 static const size_t years[2][nYears] =
1751 {
1752 // first line: the years to test
1753 { 1990, 1976, 2000, 2030, 1984, },
1754
1755 // second line: TRUE if leap, FALSE otherwise
1756 { FALSE, TRUE, TRUE, FALSE, TRUE }
1757 };
1758
1759 for ( size_t n = 0; n < nYears; n++ )
1760 {
1761 int year = years[0][n];
1762 bool should = years[1][n] != 0,
1763 is = wxDateTime::IsLeapYear(year);
1764
1765 printf("Year %d is %sa leap year (%s)\n",
1766 year,
1767 is ? "" : "not ",
1768 should == is ? "ok" : "ERROR");
1769
1770 wxASSERT( should == wxDateTime::IsLeapYear(year) );
1771 }
1772 }
1773
1774 // test constructing wxDateTime objects
1775 static void TestTimeSet()
1776 {
1777 puts("\n*** wxDateTime construction test ***");
1778
1779 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
1780 {
1781 const Date& d1 = testDates[n];
1782 wxDateTime dt = d1.DT();
1783
1784 Date d2;
1785 d2.Init(dt.GetTm());
1786
1787 wxString s1 = d1.Format(),
1788 s2 = d2.Format();
1789
1790 printf("Date: %s == %s (%s)\n",
1791 s1.c_str(), s2.c_str(),
1792 s1 == s2 ? "ok" : "ERROR");
1793 }
1794 }
1795
1796 // test time zones stuff
1797 static void TestTimeZones()
1798 {
1799 puts("\n*** wxDateTime timezone test ***");
1800
1801 wxDateTime now = wxDateTime::Now();
1802
1803 printf("Current GMT time:\t%s\n", now.Format("%c", wxDateTime::GMT0).c_str());
1804 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0).c_str());
1805 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST).c_str());
1806 printf("Current time in Paris:\t%s\n", now.Format("%c", wxDateTime::CET).c_str());
1807 printf(" Moscow:\t%s\n", now.Format("%c", wxDateTime::MSK).c_str());
1808 printf(" New York:\t%s\n", now.Format("%c", wxDateTime::EST).c_str());
1809
1810 wxDateTime::Tm tm = now.GetTm();
1811 if ( wxDateTime(tm) != now )
1812 {
1813 printf("ERROR: got %s instead of %s\n",
1814 wxDateTime(tm).Format().c_str(), now.Format().c_str());
1815 }
1816 }
1817
1818 // test some minimal support for the dates outside the standard range
1819 static void TestTimeRange()
1820 {
1821 puts("\n*** wxDateTime out-of-standard-range dates test ***");
1822
1823 static const char *fmt = "%d-%b-%Y %H:%M:%S";
1824
1825 printf("Unix epoch:\t%s\n",
1826 wxDateTime(2440587.5).Format(fmt).c_str());
1827 printf("Feb 29, 0: \t%s\n",
1828 wxDateTime(29, wxDateTime::Feb, 0).Format(fmt).c_str());
1829 printf("JDN 0: \t%s\n",
1830 wxDateTime(0.0).Format(fmt).c_str());
1831 printf("Jan 1, 1AD:\t%s\n",
1832 wxDateTime(1, wxDateTime::Jan, 1).Format(fmt).c_str());
1833 printf("May 29, 2099:\t%s\n",
1834 wxDateTime(29, wxDateTime::May, 2099).Format(fmt).c_str());
1835 }
1836
1837 static void TestTimeTicks()
1838 {
1839 puts("\n*** wxDateTime ticks test ***");
1840
1841 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
1842 {
1843 const Date& d = testDates[n];
1844 if ( d.ticks == -1 )
1845 continue;
1846
1847 wxDateTime dt = d.DT();
1848 long ticks = (dt.GetValue() / 1000).ToLong();
1849 printf("Ticks of %s:\t% 10ld", d.Format().c_str(), ticks);
1850 if ( ticks == d.ticks )
1851 {
1852 puts(" (ok)");
1853 }
1854 else
1855 {
1856 printf(" (ERROR: should be %ld, delta = %ld)\n",
1857 d.ticks, ticks - d.ticks);
1858 }
1859
1860 dt = d.DT().ToTimezone(wxDateTime::GMT0);
1861 ticks = (dt.GetValue() / 1000).ToLong();
1862 printf("GMtks of %s:\t% 10ld", d.Format().c_str(), ticks);
1863 if ( ticks == d.gmticks )
1864 {
1865 puts(" (ok)");
1866 }
1867 else
1868 {
1869 printf(" (ERROR: should be %ld, delta = %ld)\n",
1870 d.gmticks, ticks - d.gmticks);
1871 }
1872 }
1873
1874 puts("");
1875 }
1876
1877 // test conversions to JDN &c
1878 static void TestTimeJDN()
1879 {
1880 puts("\n*** wxDateTime to JDN test ***");
1881
1882 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
1883 {
1884 const Date& d = testDates[n];
1885 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
1886 double jdn = dt.GetJulianDayNumber();
1887
1888 printf("JDN of %s is:\t% 15.6f", d.Format().c_str(), jdn);
1889 if ( jdn == d.jdn )
1890 {
1891 puts(" (ok)");
1892 }
1893 else
1894 {
1895 printf(" (ERROR: should be %f, delta = %f)\n",
1896 d.jdn, jdn - d.jdn);
1897 }
1898 }
1899 }
1900
1901 // test week days computation
1902 static void TestTimeWDays()
1903 {
1904 puts("\n*** wxDateTime weekday test ***");
1905
1906 // test GetWeekDay()
1907 size_t n;
1908 for ( n = 0; n < WXSIZEOF(testDates); n++ )
1909 {
1910 const Date& d = testDates[n];
1911 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
1912
1913 wxDateTime::WeekDay wday = dt.GetWeekDay();
1914 printf("%s is: %s",
1915 d.Format().c_str(),
1916 wxDateTime::GetWeekDayName(wday).c_str());
1917 if ( wday == d.wday )
1918 {
1919 puts(" (ok)");
1920 }
1921 else
1922 {
1923 printf(" (ERROR: should be %s)\n",
1924 wxDateTime::GetWeekDayName(d.wday).c_str());
1925 }
1926 }
1927
1928 puts("");
1929
1930 // test SetToWeekDay()
1931 struct WeekDateTestData
1932 {
1933 Date date; // the real date (precomputed)
1934 int nWeek; // its week index in the month
1935 wxDateTime::WeekDay wday; // the weekday
1936 wxDateTime::Month month; // the month
1937 int year; // and the year
1938
1939 wxString Format() const
1940 {
1941 wxString s, which;
1942 switch ( nWeek < -1 ? -nWeek : nWeek )
1943 {
1944 case 1: which = "first"; break;
1945 case 2: which = "second"; break;
1946 case 3: which = "third"; break;
1947 case 4: which = "fourth"; break;
1948 case 5: which = "fifth"; break;
1949
1950 case -1: which = "last"; break;
1951 }
1952
1953 if ( nWeek < -1 )
1954 {
1955 which += " from end";
1956 }
1957
1958 s.Printf("The %s %s of %s in %d",
1959 which.c_str(),
1960 wxDateTime::GetWeekDayName(wday).c_str(),
1961 wxDateTime::GetMonthName(month).c_str(),
1962 year);
1963
1964 return s;
1965 }
1966 };
1967
1968 // the array data was generated by the following python program
1969 /*
1970 from DateTime import *
1971 from whrandom import *
1972 from string import *
1973
1974 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1975 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1976
1977 week = DateTimeDelta(7)
1978
1979 for n in range(20):
1980 year = randint(1900, 2100)
1981 month = randint(1, 12)
1982 day = randint(1, 28)
1983 dt = DateTime(year, month, day)
1984 wday = dt.day_of_week
1985
1986 countFromEnd = choice([-1, 1])
1987 weekNum = 0;
1988
1989 while dt.month is month:
1990 dt = dt - countFromEnd * week
1991 weekNum = weekNum + countFromEnd
1992
1993 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
1994
1995 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
1996 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
1997 */
1998
1999 static const WeekDateTestData weekDatesTestData[] =
2000 {
2001 { { 20, wxDateTime::Mar, 2045 }, 3, wxDateTime::Mon, wxDateTime::Mar, 2045 },
2002 { { 5, wxDateTime::Jun, 1985 }, -4, wxDateTime::Wed, wxDateTime::Jun, 1985 },
2003 { { 12, wxDateTime::Nov, 1961 }, -3, wxDateTime::Sun, wxDateTime::Nov, 1961 },
2004 { { 27, wxDateTime::Feb, 2093 }, -1, wxDateTime::Fri, wxDateTime::Feb, 2093 },
2005 { { 4, wxDateTime::Jul, 2070 }, -4, wxDateTime::Fri, wxDateTime::Jul, 2070 },
2006 { { 2, wxDateTime::Apr, 1906 }, -5, wxDateTime::Mon, wxDateTime::Apr, 1906 },
2007 { { 19, wxDateTime::Jul, 2023 }, -2, wxDateTime::Wed, wxDateTime::Jul, 2023 },
2008 { { 5, wxDateTime::May, 1958 }, -4, wxDateTime::Mon, wxDateTime::May, 1958 },
2009 { { 11, wxDateTime::Aug, 1900 }, 2, wxDateTime::Sat, wxDateTime::Aug, 1900 },
2010 { { 14, wxDateTime::Feb, 1945 }, 2, wxDateTime::Wed, wxDateTime::Feb, 1945 },
2011 { { 25, wxDateTime::Jul, 1967 }, -1, wxDateTime::Tue, wxDateTime::Jul, 1967 },
2012 { { 9, wxDateTime::May, 1916 }, -4, wxDateTime::Tue, wxDateTime::May, 1916 },
2013 { { 20, wxDateTime::Jun, 1927 }, 3, wxDateTime::Mon, wxDateTime::Jun, 1927 },
2014 { { 2, wxDateTime::Aug, 2000 }, 1, wxDateTime::Wed, wxDateTime::Aug, 2000 },
2015 { { 20, wxDateTime::Apr, 2044 }, 3, wxDateTime::Wed, wxDateTime::Apr, 2044 },
2016 { { 20, wxDateTime::Feb, 1932 }, -2, wxDateTime::Sat, wxDateTime::Feb, 1932 },
2017 { { 25, wxDateTime::Jul, 2069 }, 4, wxDateTime::Thu, wxDateTime::Jul, 2069 },
2018 { { 3, wxDateTime::Apr, 1925 }, 1, wxDateTime::Fri, wxDateTime::Apr, 1925 },
2019 { { 21, wxDateTime::Mar, 2093 }, 3, wxDateTime::Sat, wxDateTime::Mar, 2093 },
2020 { { 3, wxDateTime::Dec, 2074 }, -5, wxDateTime::Mon, wxDateTime::Dec, 2074 },
2021 };
2022
2023 static const char *fmt = "%d-%b-%Y";
2024
2025 wxDateTime dt;
2026 for ( n = 0; n < WXSIZEOF(weekDatesTestData); n++ )
2027 {
2028 const WeekDateTestData& wd = weekDatesTestData[n];
2029
2030 dt.SetToWeekDay(wd.wday, wd.nWeek, wd.month, wd.year);
2031
2032 printf("%s is %s", wd.Format().c_str(), dt.Format(fmt).c_str());
2033
2034 const Date& d = wd.date;
2035 if ( d.SameDay(dt.GetTm()) )
2036 {
2037 puts(" (ok)");
2038 }
2039 else
2040 {
2041 dt.Set(d.day, d.month, d.year);
2042
2043 printf(" (ERROR: should be %s)\n", dt.Format(fmt).c_str());
2044 }
2045 }
2046 }
2047
2048 // test the computation of (ISO) week numbers
2049 static void TestTimeWNumber()
2050 {
2051 puts("\n*** wxDateTime week number test ***");
2052
2053 struct WeekNumberTestData
2054 {
2055 Date date; // the date
2056 wxDateTime::wxDateTime_t week; // the week number in the year
2057 wxDateTime::wxDateTime_t wmon; // the week number in the month
2058 wxDateTime::wxDateTime_t wmon2; // same but week starts with Sun
2059 wxDateTime::wxDateTime_t dnum; // day number in the year
2060 };
2061
2062 // data generated with the following python script:
2063 /*
2064 from DateTime import *
2065 from whrandom import *
2066 from string import *
2067
2068 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2069 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2070
2071 def GetMonthWeek(dt):
2072 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
2073 if weekNumMonth < 0:
2074 weekNumMonth = weekNumMonth + 53
2075 return weekNumMonth
2076
2077 def GetLastSundayBefore(dt):
2078 if dt.iso_week[2] == 7:
2079 return dt
2080 else:
2081 return dt - DateTimeDelta(dt.iso_week[2])
2082
2083 for n in range(20):
2084 year = randint(1900, 2100)
2085 month = randint(1, 12)
2086 day = randint(1, 28)
2087 dt = DateTime(year, month, day)
2088 dayNum = dt.day_of_year
2089 weekNum = dt.iso_week[1]
2090 weekNumMonth = GetMonthWeek(dt)
2091
2092 weekNumMonth2 = 0
2093 dtSunday = GetLastSundayBefore(dt)
2094
2095 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
2096 weekNumMonth2 = weekNumMonth2 + 1
2097 dtSunday = dtSunday - DateTimeDelta(7)
2098
2099 data = { 'day': rjust(`day`, 2), \
2100 'month': monthNames[month - 1], \
2101 'year': year, \
2102 'weekNum': rjust(`weekNum`, 2), \
2103 'weekNumMonth': weekNumMonth, \
2104 'weekNumMonth2': weekNumMonth2, \
2105 'dayNum': rjust(`dayNum`, 3) }
2106
2107 print " { { %(day)s, "\
2108 "wxDateTime::%(month)s, "\
2109 "%(year)d }, "\
2110 "%(weekNum)s, "\
2111 "%(weekNumMonth)s, "\
2112 "%(weekNumMonth2)s, "\
2113 "%(dayNum)s }," % data
2114
2115 */
2116 static const WeekNumberTestData weekNumberTestDates[] =
2117 {
2118 { { 27, wxDateTime::Dec, 1966 }, 52, 5, 5, 361 },
2119 { { 22, wxDateTime::Jul, 1926 }, 29, 4, 4, 203 },
2120 { { 22, wxDateTime::Oct, 2076 }, 43, 4, 4, 296 },
2121 { { 1, wxDateTime::Jul, 1967 }, 26, 1, 1, 182 },
2122 { { 8, wxDateTime::Nov, 2004 }, 46, 2, 2, 313 },
2123 { { 21, wxDateTime::Mar, 1920 }, 12, 3, 4, 81 },
2124 { { 7, wxDateTime::Jan, 1965 }, 1, 2, 2, 7 },
2125 { { 19, wxDateTime::Oct, 1999 }, 42, 4, 4, 292 },
2126 { { 13, wxDateTime::Aug, 1955 }, 32, 2, 2, 225 },
2127 { { 18, wxDateTime::Jul, 2087 }, 29, 3, 3, 199 },
2128 { { 2, wxDateTime::Sep, 2028 }, 35, 1, 1, 246 },
2129 { { 28, wxDateTime::Jul, 1945 }, 30, 5, 4, 209 },
2130 { { 15, wxDateTime::Jun, 1901 }, 24, 3, 3, 166 },
2131 { { 10, wxDateTime::Oct, 1939 }, 41, 3, 2, 283 },
2132 { { 3, wxDateTime::Dec, 1965 }, 48, 1, 1, 337 },
2133 { { 23, wxDateTime::Feb, 1940 }, 8, 4, 4, 54 },
2134 { { 2, wxDateTime::Jan, 1987 }, 1, 1, 1, 2 },
2135 { { 11, wxDateTime::Aug, 2079 }, 32, 2, 2, 223 },
2136 { { 2, wxDateTime::Feb, 2063 }, 5, 1, 1, 33 },
2137 { { 16, wxDateTime::Oct, 1942 }, 42, 3, 3, 289 },
2138 };
2139
2140 for ( size_t n = 0; n < WXSIZEOF(weekNumberTestDates); n++ )
2141 {
2142 const WeekNumberTestData& wn = weekNumberTestDates[n];
2143 const Date& d = wn.date;
2144
2145 wxDateTime dt = d.DT();
2146
2147 wxDateTime::wxDateTime_t
2148 week = dt.GetWeekOfYear(wxDateTime::Monday_First),
2149 wmon = dt.GetWeekOfMonth(wxDateTime::Monday_First),
2150 wmon2 = dt.GetWeekOfMonth(wxDateTime::Sunday_First),
2151 dnum = dt.GetDayOfYear();
2152
2153 printf("%s: the day number is %d",
2154 d.FormatDate().c_str(), dnum);
2155 if ( dnum == wn.dnum )
2156 {
2157 printf(" (ok)");
2158 }
2159 else
2160 {
2161 printf(" (ERROR: should be %d)", wn.dnum);
2162 }
2163
2164 printf(", week in month is %d", wmon);
2165 if ( wmon == wn.wmon )
2166 {
2167 printf(" (ok)");
2168 }
2169 else
2170 {
2171 printf(" (ERROR: should be %d)", wn.wmon);
2172 }
2173
2174 printf(" or %d", wmon2);
2175 if ( wmon2 == wn.wmon2 )
2176 {
2177 printf(" (ok)");
2178 }
2179 else
2180 {
2181 printf(" (ERROR: should be %d)", wn.wmon2);
2182 }
2183
2184 printf(", week in year is %d", week);
2185 if ( week == wn.week )
2186 {
2187 puts(" (ok)");
2188 }
2189 else
2190 {
2191 printf(" (ERROR: should be %d)\n", wn.week);
2192 }
2193 }
2194 }
2195
2196 // test DST calculations
2197 static void TestTimeDST()
2198 {
2199 puts("\n*** wxDateTime DST test ***");
2200
2201 printf("DST is%s in effect now.\n\n",
2202 wxDateTime::Now().IsDST() ? "" : " not");
2203
2204 // taken from http://www.energy.ca.gov/daylightsaving.html
2205 static const Date datesDST[2][2004 - 1900 + 1] =
2206 {
2207 {
2208 { 1, wxDateTime::Apr, 1990 },
2209 { 7, wxDateTime::Apr, 1991 },
2210 { 5, wxDateTime::Apr, 1992 },
2211 { 4, wxDateTime::Apr, 1993 },
2212 { 3, wxDateTime::Apr, 1994 },
2213 { 2, wxDateTime::Apr, 1995 },
2214 { 7, wxDateTime::Apr, 1996 },
2215 { 6, wxDateTime::Apr, 1997 },
2216 { 5, wxDateTime::Apr, 1998 },
2217 { 4, wxDateTime::Apr, 1999 },
2218 { 2, wxDateTime::Apr, 2000 },
2219 { 1, wxDateTime::Apr, 2001 },
2220 { 7, wxDateTime::Apr, 2002 },
2221 { 6, wxDateTime::Apr, 2003 },
2222 { 4, wxDateTime::Apr, 2004 },
2223 },
2224 {
2225 { 28, wxDateTime::Oct, 1990 },
2226 { 27, wxDateTime::Oct, 1991 },
2227 { 25, wxDateTime::Oct, 1992 },
2228 { 31, wxDateTime::Oct, 1993 },
2229 { 30, wxDateTime::Oct, 1994 },
2230 { 29, wxDateTime::Oct, 1995 },
2231 { 27, wxDateTime::Oct, 1996 },
2232 { 26, wxDateTime::Oct, 1997 },
2233 { 25, wxDateTime::Oct, 1998 },
2234 { 31, wxDateTime::Oct, 1999 },
2235 { 29, wxDateTime::Oct, 2000 },
2236 { 28, wxDateTime::Oct, 2001 },
2237 { 27, wxDateTime::Oct, 2002 },
2238 { 26, wxDateTime::Oct, 2003 },
2239 { 31, wxDateTime::Oct, 2004 },
2240 }
2241 };
2242
2243 int year;
2244 for ( year = 1990; year < 2005; year++ )
2245 {
2246 wxDateTime dtBegin = wxDateTime::GetBeginDST(year, wxDateTime::USA),
2247 dtEnd = wxDateTime::GetEndDST(year, wxDateTime::USA);
2248
2249 printf("DST period in the US for year %d: from %s to %s",
2250 year, dtBegin.Format().c_str(), dtEnd.Format().c_str());
2251
2252 size_t n = year - 1990;
2253 const Date& dBegin = datesDST[0][n];
2254 const Date& dEnd = datesDST[1][n];
2255
2256 if ( dBegin.SameDay(dtBegin.GetTm()) && dEnd.SameDay(dtEnd.GetTm()) )
2257 {
2258 puts(" (ok)");
2259 }
2260 else
2261 {
2262 printf(" (ERROR: should be %s %d to %s %d)\n",
2263 wxDateTime::GetMonthName(dBegin.month).c_str(), dBegin.day,
2264 wxDateTime::GetMonthName(dEnd.month).c_str(), dEnd.day);
2265 }
2266 }
2267
2268 puts("");
2269
2270 for ( year = 1990; year < 2005; year++ )
2271 {
2272 printf("DST period in Europe for year %d: from %s to %s\n",
2273 year,
2274 wxDateTime::GetBeginDST(year, wxDateTime::Country_EEC).Format().c_str(),
2275 wxDateTime::GetEndDST(year, wxDateTime::Country_EEC).Format().c_str());
2276 }
2277 }
2278
2279 // test wxDateTime -> text conversion
2280 static void TestTimeFormat()
2281 {
2282 puts("\n*** wxDateTime formatting test ***");
2283
2284 // some information may be lost during conversion, so store what kind
2285 // of info should we recover after a round trip
2286 enum CompareKind
2287 {
2288 CompareNone, // don't try comparing
2289 CompareBoth, // dates and times should be identical
2290 CompareDate, // dates only
2291 CompareTime // time only
2292 };
2293
2294 static const struct
2295 {
2296 CompareKind compareKind;
2297 const char *format;
2298 } formatTestFormats[] =
2299 {
2300 { CompareBoth, "---> %c" },
2301 { CompareDate, "Date is %A, %d of %B, in year %Y" },
2302 { CompareBoth, "Date is %x, time is %X" },
2303 { CompareTime, "Time is %H:%M:%S or %I:%M:%S %p" },
2304 { CompareNone, "The day of year: %j, the week of year: %W" },
2305 { CompareDate, "ISO date without separators: %4Y%2m%2d" },
2306 };
2307
2308 static const Date formatTestDates[] =
2309 {
2310 { 29, wxDateTime::May, 1976, 18, 30, 00 },
2311 { 31, wxDateTime::Dec, 1999, 23, 30, 00 },
2312 #if 0
2313 // this test can't work for other centuries because it uses two digit
2314 // years in formats, so don't even try it
2315 { 29, wxDateTime::May, 2076, 18, 30, 00 },
2316 { 29, wxDateTime::Feb, 2400, 02, 15, 25 },
2317 { 01, wxDateTime::Jan, -52, 03, 16, 47 },
2318 #endif
2319 };
2320
2321 // an extra test (as it doesn't depend on date, don't do it in the loop)
2322 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
2323
2324 for ( size_t d = 0; d < WXSIZEOF(formatTestDates) + 1; d++ )
2325 {
2326 puts("");
2327
2328 wxDateTime dt = d == 0 ? wxDateTime::Now() : formatTestDates[d - 1].DT();
2329 for ( size_t n = 0; n < WXSIZEOF(formatTestFormats); n++ )
2330 {
2331 wxString s = dt.Format(formatTestFormats[n].format);
2332 printf("%s", s.c_str());
2333
2334 // what can we recover?
2335 int kind = formatTestFormats[n].compareKind;
2336
2337 // convert back
2338 wxDateTime dt2;
2339 const wxChar *result = dt2.ParseFormat(s, formatTestFormats[n].format);
2340 if ( !result )
2341 {
2342 // converion failed - should it have?
2343 if ( kind == CompareNone )
2344 puts(" (ok)");
2345 else
2346 puts(" (ERROR: conversion back failed)");
2347 }
2348 else if ( *result )
2349 {
2350 // should have parsed the entire string
2351 puts(" (ERROR: conversion back stopped too soon)");
2352 }
2353 else
2354 {
2355 bool equal = FALSE; // suppress compilaer warning
2356 switch ( kind )
2357 {
2358 case CompareBoth:
2359 equal = dt2 == dt;
2360 break;
2361
2362 case CompareDate:
2363 equal = dt.IsSameDate(dt2);
2364 break;
2365
2366 case CompareTime:
2367 equal = dt.IsSameTime(dt2);
2368 break;
2369 }
2370
2371 if ( !equal )
2372 {
2373 printf(" (ERROR: got back '%s' instead of '%s')\n",
2374 dt2.Format().c_str(), dt.Format().c_str());
2375 }
2376 else
2377 {
2378 puts(" (ok)");
2379 }
2380 }
2381 }
2382 }
2383 }
2384
2385 // test text -> wxDateTime conversion
2386 static void TestTimeParse()
2387 {
2388 puts("\n*** wxDateTime parse test ***");
2389
2390 struct ParseTestData
2391 {
2392 const char *format;
2393 Date date;
2394 bool good;
2395 };
2396
2397 static const ParseTestData parseTestDates[] =
2398 {
2399 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec, 1999, 00, 46, 40 }, TRUE },
2400 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec, 1999, 03, 17, 20 }, TRUE },
2401 };
2402
2403 for ( size_t n = 0; n < WXSIZEOF(parseTestDates); n++ )
2404 {
2405 const char *format = parseTestDates[n].format;
2406
2407 printf("%s => ", format);
2408
2409 wxDateTime dt;
2410 if ( dt.ParseRfc822Date(format) )
2411 {
2412 printf("%s ", dt.Format().c_str());
2413
2414 if ( parseTestDates[n].good )
2415 {
2416 wxDateTime dtReal = parseTestDates[n].date.DT();
2417 if ( dt == dtReal )
2418 {
2419 puts("(ok)");
2420 }
2421 else
2422 {
2423 printf("(ERROR: should be %s)\n", dtReal.Format().c_str());
2424 }
2425 }
2426 else
2427 {
2428 puts("(ERROR: bad format)");
2429 }
2430 }
2431 else
2432 {
2433 printf("bad format (%s)\n",
2434 parseTestDates[n].good ? "ERROR" : "ok");
2435 }
2436 }
2437 }
2438
2439 static void TestInteractive()
2440 {
2441 puts("\n*** interactive wxDateTime tests ***");
2442
2443 char buf[128];
2444
2445 for ( ;; )
2446 {
2447 printf("Enter a date: ");
2448 if ( !fgets(buf, WXSIZEOF(buf), stdin) )
2449 break;
2450
2451 // kill the last '\n'
2452 buf[strlen(buf) - 1] = 0;
2453
2454 wxDateTime dt;
2455 const char *p = dt.ParseDate(buf);
2456 if ( !p )
2457 {
2458 printf("ERROR: failed to parse the date '%s'.\n", buf);
2459
2460 continue;
2461 }
2462 else if ( *p )
2463 {
2464 printf("WARNING: parsed only first %u characters.\n", p - buf);
2465 }
2466
2467 printf("%s: day %u, week of month %u/%u, week of year %u\n",
2468 dt.Format("%b %d, %Y").c_str(),
2469 dt.GetDayOfYear(),
2470 dt.GetWeekOfMonth(wxDateTime::Monday_First),
2471 dt.GetWeekOfMonth(wxDateTime::Sunday_First),
2472 dt.GetWeekOfYear(wxDateTime::Monday_First));
2473 }
2474
2475 puts("\n*** done ***");
2476 }
2477
2478 static void TestTimeMS()
2479 {
2480 puts("*** testing millisecond-resolution support in wxDateTime ***");
2481
2482 wxDateTime dt1 = wxDateTime::Now(),
2483 dt2 = wxDateTime::UNow();
2484
2485 printf("Now = %s\n", dt1.Format("%H:%M:%S:%l").c_str());
2486 printf("UNow = %s\n", dt2.Format("%H:%M:%S:%l").c_str());
2487 printf("Difference is %s\n", (dt2 - dt1).Format("%l").c_str());
2488
2489 puts("\n*** done ***");
2490 }
2491
2492 static void TestTimeArithmetics()
2493 {
2494 puts("\n*** testing arithmetic operations on wxDateTime ***");
2495
2496 static const struct ArithmData
2497 {
2498 ArithmData(const wxDateSpan& sp, const char *nam)
2499 : span(sp), name(nam) { }
2500
2501 wxDateSpan span;
2502 const char *name;
2503 } testArithmData[] =
2504 {
2505 ArithmData(wxDateSpan::Day(), "day"),
2506 ArithmData(wxDateSpan::Week(), "week"),
2507 ArithmData(wxDateSpan::Month(), "month"),
2508 ArithmData(wxDateSpan::Year(), "year"),
2509 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
2510 };
2511
2512 wxDateTime dt(29, wxDateTime::Dec, 1999), dt1, dt2;
2513
2514 for ( size_t n = 0; n < WXSIZEOF(testArithmData); n++ )
2515 {
2516 wxDateSpan span = testArithmData[n].span;
2517 dt1 = dt + span;
2518 dt2 = dt - span;
2519
2520 const char *name = testArithmData[n].name;
2521 printf("%s + %s = %s, %s - %s = %s\n",
2522 dt.FormatISODate().c_str(), name, dt1.FormatISODate().c_str(),
2523 dt.FormatISODate().c_str(), name, dt2.FormatISODate().c_str());
2524
2525 printf("Going back: %s", (dt1 - span).FormatISODate().c_str());
2526 if ( dt1 - span == dt )
2527 {
2528 puts(" (ok)");
2529 }
2530 else
2531 {
2532 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
2533 }
2534
2535 printf("Going forward: %s", (dt2 + span).FormatISODate().c_str());
2536 if ( dt2 + span == dt )
2537 {
2538 puts(" (ok)");
2539 }
2540 else
2541 {
2542 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
2543 }
2544
2545 printf("Double increment: %s", (dt2 + 2*span).FormatISODate().c_str());
2546 if ( dt2 + 2*span == dt1 )
2547 {
2548 puts(" (ok)");
2549 }
2550 else
2551 {
2552 printf(" (ERROR: should be %s)\n", dt2.FormatISODate().c_str());
2553 }
2554
2555 puts("");
2556 }
2557 }
2558
2559 static void TestTimeHolidays()
2560 {
2561 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
2562
2563 wxDateTime::Tm tm = wxDateTime(29, wxDateTime::May, 2000).GetTm();
2564 wxDateTime dtStart(1, tm.mon, tm.year),
2565 dtEnd = dtStart.GetLastMonthDay();
2566
2567 wxDateTimeArray hol;
2568 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart, dtEnd, hol);
2569
2570 const wxChar *format = "%d-%b-%Y (%a)";
2571
2572 printf("All holidays between %s and %s:\n",
2573 dtStart.Format(format).c_str(), dtEnd.Format(format).c_str());
2574
2575 size_t count = hol.GetCount();
2576 for ( size_t n = 0; n < count; n++ )
2577 {
2578 printf("\t%s\n", hol[n].Format(format).c_str());
2579 }
2580
2581 puts("");
2582 }
2583
2584 static void TestTimeZoneBug()
2585 {
2586 puts("\n*** testing for DST/timezone bug ***\n");
2587
2588 wxDateTime date = wxDateTime(1, wxDateTime::Mar, 2000);
2589 for ( int i = 0; i < 31; i++ )
2590 {
2591 printf("Date %s: week day %s.\n",
2592 date.Format(_T("%d-%m-%Y")).c_str(),
2593 date.GetWeekDayName(date.GetWeekDay()).c_str());
2594
2595 date += wxDateSpan::Day();
2596 }
2597
2598 puts("");
2599 }
2600
2601 #if 0
2602
2603 // test compatibility with the old wxDate/wxTime classes
2604 static void TestTimeCompatibility()
2605 {
2606 puts("\n*** wxDateTime compatibility test ***");
2607
2608 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
2609 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
2610
2611 double jdnNow = wxDateTime::Now().GetJDN();
2612 long jdnMidnight = (long)(jdnNow - 0.5);
2613 printf("wxDate for today: %s\n", wxDate(jdnMidnight).FormatDate().c_str());
2614
2615 jdnMidnight = wxDate().Set().GetJulianDate();
2616 printf("wxDateTime for today: %s\n",
2617 wxDateTime((double)(jdnMidnight + 0.5)).Format("%c", wxDateTime::GMT0).c_str());
2618
2619 int flags = wxEUROPEAN;//wxFULL;
2620 wxDate date;
2621 date.Set();
2622 printf("Today is %s\n", date.FormatDate(flags).c_str());
2623 for ( int n = 0; n < 7; n++ )
2624 {
2625 printf("Previous %s is %s\n",
2626 wxDateTime::GetWeekDayName((wxDateTime::WeekDay)n),
2627 date.Previous(n + 1).FormatDate(flags).c_str());
2628 }
2629 }
2630
2631 #endif // 0
2632
2633 #endif // TEST_DATETIME
2634
2635 // ----------------------------------------------------------------------------
2636 // threads
2637 // ----------------------------------------------------------------------------
2638
2639 #ifdef TEST_THREADS
2640
2641 #include <wx/thread.h>
2642
2643 static size_t gs_counter = (size_t)-1;
2644 static wxCriticalSection gs_critsect;
2645 static wxCondition gs_cond;
2646
2647 class MyJoinableThread : public wxThread
2648 {
2649 public:
2650 MyJoinableThread(size_t n) : wxThread(wxTHREAD_JOINABLE)
2651 { m_n = n; Create(); }
2652
2653 // thread execution starts here
2654 virtual ExitCode Entry();
2655
2656 private:
2657 size_t m_n;
2658 };
2659
2660 wxThread::ExitCode MyJoinableThread::Entry()
2661 {
2662 unsigned long res = 1;
2663 for ( size_t n = 1; n < m_n; n++ )
2664 {
2665 res *= n;
2666
2667 // it's a loooong calculation :-)
2668 Sleep(100);
2669 }
2670
2671 return (ExitCode)res;
2672 }
2673
2674 class MyDetachedThread : public wxThread
2675 {
2676 public:
2677 MyDetachedThread(size_t n, char ch)
2678 {
2679 m_n = n;
2680 m_ch = ch;
2681 m_cancelled = FALSE;
2682
2683 Create();
2684 }
2685
2686 // thread execution starts here
2687 virtual ExitCode Entry();
2688
2689 // and stops here
2690 virtual void OnExit();
2691
2692 private:
2693 size_t m_n; // number of characters to write
2694 char m_ch; // character to write
2695
2696 bool m_cancelled; // FALSE if we exit normally
2697 };
2698
2699 wxThread::ExitCode MyDetachedThread::Entry()
2700 {
2701 {
2702 wxCriticalSectionLocker lock(gs_critsect);
2703 if ( gs_counter == (size_t)-1 )
2704 gs_counter = 1;
2705 else
2706 gs_counter++;
2707 }
2708
2709 for ( size_t n = 0; n < m_n; n++ )
2710 {
2711 if ( TestDestroy() )
2712 {
2713 m_cancelled = TRUE;
2714
2715 break;
2716 }
2717
2718 putchar(m_ch);
2719 fflush(stdout);
2720
2721 wxThread::Sleep(100);
2722 }
2723
2724 return 0;
2725 }
2726
2727 void MyDetachedThread::OnExit()
2728 {
2729 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
2730
2731 wxCriticalSectionLocker lock(gs_critsect);
2732 if ( !--gs_counter && !m_cancelled )
2733 gs_cond.Signal();
2734 }
2735
2736 void TestDetachedThreads()
2737 {
2738 puts("\n*** Testing detached threads ***");
2739
2740 static const size_t nThreads = 3;
2741 MyDetachedThread *threads[nThreads];
2742 size_t n;
2743 for ( n = 0; n < nThreads; n++ )
2744 {
2745 threads[n] = new MyDetachedThread(10, 'A' + n);
2746 }
2747
2748 threads[0]->SetPriority(WXTHREAD_MIN_PRIORITY);
2749 threads[1]->SetPriority(WXTHREAD_MAX_PRIORITY);
2750
2751 for ( n = 0; n < nThreads; n++ )
2752 {
2753 threads[n]->Run();
2754 }
2755
2756 // wait until all threads terminate
2757 gs_cond.Wait();
2758
2759 puts("");
2760 }
2761
2762 void TestJoinableThreads()
2763 {
2764 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
2765
2766 // calc 10! in the background
2767 MyJoinableThread thread(10);
2768 thread.Run();
2769
2770 printf("\nThread terminated with exit code %lu.\n",
2771 (unsigned long)thread.Wait());
2772 }
2773
2774 void TestThreadSuspend()
2775 {
2776 puts("\n*** Testing thread suspend/resume functions ***");
2777
2778 MyDetachedThread *thread = new MyDetachedThread(15, 'X');
2779
2780 thread->Run();
2781
2782 // this is for this demo only, in a real life program we'd use another
2783 // condition variable which would be signaled from wxThread::Entry() to
2784 // tell us that the thread really started running - but here just wait a
2785 // bit and hope that it will be enough (the problem is, of course, that
2786 // the thread might still not run when we call Pause() which will result
2787 // in an error)
2788 wxThread::Sleep(300);
2789
2790 for ( size_t n = 0; n < 3; n++ )
2791 {
2792 thread->Pause();
2793
2794 puts("\nThread suspended");
2795 if ( n > 0 )
2796 {
2797 // don't sleep but resume immediately the first time
2798 wxThread::Sleep(300);
2799 }
2800 puts("Going to resume the thread");
2801
2802 thread->Resume();
2803 }
2804
2805 puts("Waiting until it terminates now");
2806
2807 // wait until the thread terminates
2808 gs_cond.Wait();
2809
2810 puts("");
2811 }
2812
2813 void TestThreadDelete()
2814 {
2815 // As above, using Sleep() is only for testing here - we must use some
2816 // synchronisation object instead to ensure that the thread is still
2817 // running when we delete it - deleting a detached thread which already
2818 // terminated will lead to a crash!
2819
2820 puts("\n*** Testing thread delete function ***");
2821
2822 MyDetachedThread *thread0 = new MyDetachedThread(30, 'W');
2823
2824 thread0->Delete();
2825
2826 puts("\nDeleted a thread which didn't start to run yet.");
2827
2828 MyDetachedThread *thread1 = new MyDetachedThread(30, 'Y');
2829
2830 thread1->Run();
2831
2832 wxThread::Sleep(300);
2833
2834 thread1->Delete();
2835
2836 puts("\nDeleted a running thread.");
2837
2838 MyDetachedThread *thread2 = new MyDetachedThread(30, 'Z');
2839
2840 thread2->Run();
2841
2842 wxThread::Sleep(300);
2843
2844 thread2->Pause();
2845
2846 thread2->Delete();
2847
2848 puts("\nDeleted a sleeping thread.");
2849
2850 MyJoinableThread thread3(20);
2851 thread3.Run();
2852
2853 thread3.Delete();
2854
2855 puts("\nDeleted a joinable thread.");
2856
2857 MyJoinableThread thread4(2);
2858 thread4.Run();
2859
2860 wxThread::Sleep(300);
2861
2862 thread4.Delete();
2863
2864 puts("\nDeleted a joinable thread which already terminated.");
2865
2866 puts("");
2867 }
2868
2869 #endif // TEST_THREADS
2870
2871 // ----------------------------------------------------------------------------
2872 // arrays
2873 // ----------------------------------------------------------------------------
2874
2875 #ifdef TEST_ARRAYS
2876
2877 static void PrintArray(const char* name, const wxArrayString& array)
2878 {
2879 printf("Dump of the array '%s'\n", name);
2880
2881 size_t nCount = array.GetCount();
2882 for ( size_t n = 0; n < nCount; n++ )
2883 {
2884 printf("\t%s[%u] = '%s'\n", name, n, array[n].c_str());
2885 }
2886 }
2887
2888 static int StringLenCompare(const wxString& first, const wxString& second)
2889 {
2890 return first.length() - second.length();
2891 }
2892
2893 #include "wx/dynarray.h"
2894
2895 WX_DECLARE_OBJARRAY(Bar, ArrayBars);
2896 #include "wx/arrimpl.cpp"
2897 WX_DEFINE_OBJARRAY(ArrayBars);
2898
2899 static void TestArrayOfObjects()
2900 {
2901 puts("*** Testing wxObjArray ***\n");
2902
2903 {
2904 ArrayBars bars;
2905 Bar bar("second bar");
2906
2907 printf("Initially: %u objects in the array, %u objects total.\n",
2908 bars.GetCount(), Bar::GetNumber());
2909
2910 bars.Add(new Bar("first bar"));
2911 bars.Add(bar);
2912
2913 printf("Now: %u objects in the array, %u objects total.\n",
2914 bars.GetCount(), Bar::GetNumber());
2915
2916 bars.Empty();
2917
2918 printf("After Empty(): %u objects in the array, %u objects total.\n",
2919 bars.GetCount(), Bar::GetNumber());
2920 }
2921
2922 printf("Finally: no more objects in the array, %u objects total.\n",
2923 Bar::GetNumber());
2924 }
2925
2926 #endif // TEST_ARRAYS
2927
2928 // ----------------------------------------------------------------------------
2929 // strings
2930 // ----------------------------------------------------------------------------
2931
2932 #ifdef TEST_STRINGS
2933
2934 #include "wx/timer.h"
2935 #include "wx/tokenzr.h"
2936
2937 static void TestStringConstruction()
2938 {
2939 puts("*** Testing wxString constructores ***");
2940
2941 #define TEST_CTOR(args, res) \
2942 { \
2943 wxString s args ; \
2944 printf("wxString%s = %s ", #args, s.c_str()); \
2945 if ( s == res ) \
2946 { \
2947 puts("(ok)"); \
2948 } \
2949 else \
2950 { \
2951 printf("(ERROR: should be %s)\n", res); \
2952 } \
2953 }
2954
2955 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
2956 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
2957 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
2958 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
2959
2960 static const wxChar *s = _T("?really!");
2961 const wxChar *start = wxStrchr(s, _T('r'));
2962 const wxChar *end = wxStrchr(s, _T('!'));
2963 TEST_CTOR((start, end), _T("really"));
2964
2965 puts("");
2966 }
2967
2968 static void TestString()
2969 {
2970 wxStopWatch sw;
2971
2972 wxString a, b, c;
2973
2974 a.reserve (128);
2975 b.reserve (128);
2976 c.reserve (128);
2977
2978 for (int i = 0; i < 1000000; ++i)
2979 {
2980 a = "Hello";
2981 b = " world";
2982 c = "! How'ya doin'?";
2983 a += b;
2984 a += c;
2985 c = "Hello world! What's up?";
2986 if (c != a)
2987 c = "Doh!";
2988 }
2989
2990 printf ("TestString elapsed time: %ld\n", sw.Time());
2991 }
2992
2993 static void TestPChar()
2994 {
2995 wxStopWatch sw;
2996
2997 char a [128];
2998 char b [128];
2999 char c [128];
3000
3001 for (int i = 0; i < 1000000; ++i)
3002 {
3003 strcpy (a, "Hello");
3004 strcpy (b, " world");
3005 strcpy (c, "! How'ya doin'?");
3006 strcat (a, b);
3007 strcat (a, c);
3008 strcpy (c, "Hello world! What's up?");
3009 if (strcmp (c, a) == 0)
3010 strcpy (c, "Doh!");
3011 }
3012
3013 printf ("TestPChar elapsed time: %ld\n", sw.Time());
3014 }
3015
3016 static void TestStringSub()
3017 {
3018 wxString s("Hello, world!");
3019
3020 puts("*** Testing wxString substring extraction ***");
3021
3022 printf("String = '%s'\n", s.c_str());
3023 printf("Left(5) = '%s'\n", s.Left(5).c_str());
3024 printf("Right(6) = '%s'\n", s.Right(6).c_str());
3025 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
3026 printf("Mid(3) = '%s'\n", s.Mid(3).c_str());
3027 printf("substr(3, 5) = '%s'\n", s.substr(3, 5).c_str());
3028 printf("substr(3) = '%s'\n", s.substr(3).c_str());
3029
3030 static const wxChar *prefixes[] =
3031 {
3032 _T("Hello"),
3033 _T("Hello, "),
3034 _T("Hello, world!"),
3035 _T("Hello, world!!!"),
3036 _T(""),
3037 _T("Goodbye"),
3038 _T("Hi"),
3039 };
3040
3041 for ( size_t n = 0; n < WXSIZEOF(prefixes); n++ )
3042 {
3043 wxString prefix = prefixes[n], rest;
3044 bool rc = s.StartsWith(prefix, &rest);
3045 printf("StartsWith('%s') = %s", prefix.c_str(), rc ? "TRUE" : "FALSE");
3046 if ( rc )
3047 {
3048 printf(" (the rest is '%s')\n", rest.c_str());
3049 }
3050 else
3051 {
3052 putchar('\n');
3053 }
3054 }
3055
3056 puts("");
3057 }
3058
3059 static void TestStringFormat()
3060 {
3061 puts("*** Testing wxString formatting ***");
3062
3063 wxString s;
3064 s.Printf("%03d", 18);
3065
3066 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
3067 printf("Number 18: %s\n", s.c_str());
3068
3069 puts("");
3070 }
3071
3072 // returns "not found" for npos, value for all others
3073 static wxString PosToString(size_t res)
3074 {
3075 wxString s = res == wxString::npos ? wxString(_T("not found"))
3076 : wxString::Format(_T("%u"), res);
3077 return s;
3078 }
3079
3080 static void TestStringFind()
3081 {
3082 puts("*** Testing wxString find() functions ***");
3083
3084 static const wxChar *strToFind = _T("ell");
3085 static const struct StringFindTest
3086 {
3087 const wxChar *str;
3088 size_t start,
3089 result; // of searching "ell" in str
3090 } findTestData[] =
3091 {
3092 { _T("Well, hello world"), 0, 1 },
3093 { _T("Well, hello world"), 6, 7 },
3094 { _T("Well, hello world"), 9, wxString::npos },
3095 };
3096
3097 for ( size_t n = 0; n < WXSIZEOF(findTestData); n++ )
3098 {
3099 const StringFindTest& ft = findTestData[n];
3100 size_t res = wxString(ft.str).find(strToFind, ft.start);
3101
3102 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
3103 strToFind, ft.str, ft.start, PosToString(res).c_str());
3104
3105 size_t resTrue = ft.result;
3106 if ( res == resTrue )
3107 {
3108 puts(_T("(ok)"));
3109 }
3110 else
3111 {
3112 printf(_T("(ERROR: should be %s)\n"),
3113 PosToString(resTrue).c_str());
3114 }
3115 }
3116
3117 puts("");
3118 }
3119
3120 static void TestStringTokenizer()
3121 {
3122 puts("*** Testing wxStringTokenizer ***");
3123
3124 static const wxChar *modeNames[] =
3125 {
3126 _T("default"),
3127 _T("return empty"),
3128 _T("return all empty"),
3129 _T("with delims"),
3130 _T("like strtok"),
3131 };
3132
3133 static const struct StringTokenizerTest
3134 {
3135 const wxChar *str; // string to tokenize
3136 const wxChar *delims; // delimiters to use
3137 size_t count; // count of token
3138 wxStringTokenizerMode mode; // how should we tokenize it
3139 } tokenizerTestData[] =
3140 {
3141 { _T(""), _T(" "), 0 },
3142 { _T("Hello, world"), _T(" "), 2 },
3143 { _T("Hello, world "), _T(" "), 2 },
3144 { _T("Hello, world"), _T(","), 2 },
3145 { _T("Hello, world!"), _T(",!"), 2 },
3146 { _T("Hello,, world!"), _T(",!"), 3 },
3147 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL },
3148 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
3149 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 4 },
3150 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 6, wxTOKEN_RET_EMPTY },
3151 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 9, wxTOKEN_RET_EMPTY_ALL },
3152 { _T("01/02/99"), _T("/-"), 3 },
3153 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS },
3154 };
3155
3156 for ( size_t n = 0; n < WXSIZEOF(tokenizerTestData); n++ )
3157 {
3158 const StringTokenizerTest& tt = tokenizerTestData[n];
3159 wxStringTokenizer tkz(tt.str, tt.delims, tt.mode);
3160
3161 size_t count = tkz.CountTokens();
3162 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
3163 MakePrintable(tt.str).c_str(),
3164 count,
3165 MakePrintable(tt.delims).c_str(),
3166 modeNames[tkz.GetMode()]);
3167 if ( count == tt.count )
3168 {
3169 puts(_T("(ok)"));
3170 }
3171 else
3172 {
3173 printf(_T("(ERROR: should be %u)\n"), tt.count);
3174
3175 continue;
3176 }
3177
3178 // if we emulate strtok(), check that we do it correctly
3179 wxChar *buf, *s = NULL, *last;
3180
3181 if ( tkz.GetMode() == wxTOKEN_STRTOK )
3182 {
3183 buf = new wxChar[wxStrlen(tt.str) + 1];
3184 wxStrcpy(buf, tt.str);
3185
3186 s = wxStrtok(buf, tt.delims, &last);
3187 }
3188 else
3189 {
3190 buf = NULL;
3191 }
3192
3193 // now show the tokens themselves
3194 size_t count2 = 0;
3195 while ( tkz.HasMoreTokens() )
3196 {
3197 wxString token = tkz.GetNextToken();
3198
3199 printf(_T("\ttoken %u: '%s'"),
3200 ++count2,
3201 MakePrintable(token).c_str());
3202
3203 if ( buf )
3204 {
3205 if ( token == s )
3206 {
3207 puts(" (ok)");
3208 }
3209 else
3210 {
3211 printf(" (ERROR: should be %s)\n", s);
3212 }
3213
3214 s = wxStrtok(NULL, tt.delims, &last);
3215 }
3216 else
3217 {
3218 // nothing to compare with
3219 puts("");
3220 }
3221 }
3222
3223 if ( count2 != count )
3224 {
3225 puts(_T("\tERROR: token count mismatch"));
3226 }
3227
3228 delete [] buf;
3229 }
3230
3231 puts("");
3232 }
3233
3234 static void TestStringReplace()
3235 {
3236 puts("*** Testing wxString::replace ***");
3237
3238 static const struct StringReplaceTestData
3239 {
3240 const wxChar *original; // original test string
3241 size_t start, len; // the part to replace
3242 const wxChar *replacement; // the replacement string
3243 const wxChar *result; // and the expected result
3244 } stringReplaceTestData[] =
3245 {
3246 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
3247 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
3248 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
3249 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
3250 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
3251 };
3252
3253 for ( size_t n = 0; n < WXSIZEOF(stringReplaceTestData); n++ )
3254 {
3255 const StringReplaceTestData data = stringReplaceTestData[n];
3256
3257 wxString original = data.original;
3258 original.replace(data.start, data.len, data.replacement);
3259
3260 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
3261 data.original, data.start, data.len, data.replacement,
3262 original.c_str());
3263
3264 if ( original == data.result )
3265 {
3266 puts("(ok)");
3267 }
3268 else
3269 {
3270 wxPrintf(_T("(ERROR: should be '%s')\n"), data.result);
3271 }
3272 }
3273
3274 puts("");
3275 }
3276
3277 #endif // TEST_STRINGS
3278
3279 // ----------------------------------------------------------------------------
3280 // entry point
3281 // ----------------------------------------------------------------------------
3282
3283 int main(int argc, char **argv)
3284 {
3285 if ( !wxInitialize() )
3286 {
3287 fprintf(stderr, "Failed to initialize the wxWindows library, aborting.");
3288 }
3289
3290 #ifdef TEST_USLEEP
3291 puts("Sleeping for 3 seconds... z-z-z-z-z...");
3292 wxUsleep(3000);
3293 #endif // TEST_USLEEP
3294
3295 #ifdef TEST_CMDLINE
3296 static const wxCmdLineEntryDesc cmdLineDesc[] =
3297 {
3298 { wxCMD_LINE_SWITCH, "v", "verbose", "be verbose" },
3299 { wxCMD_LINE_SWITCH, "q", "quiet", "be quiet" },
3300
3301 { wxCMD_LINE_OPTION, "o", "output", "output file" },
3302 { wxCMD_LINE_OPTION, "i", "input", "input dir" },
3303 { wxCMD_LINE_OPTION, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER },
3304 { wxCMD_LINE_OPTION, "d", "date", "output file date", wxCMD_LINE_VAL_DATE },
3305
3306 { wxCMD_LINE_PARAM, NULL, NULL, "input file",
3307 wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_MULTIPLE },
3308
3309 { wxCMD_LINE_NONE }
3310 };
3311
3312 wxCmdLineParser parser(cmdLineDesc, argc, argv);
3313
3314 parser.AddOption("project_name", "", "full path to project file",
3315 wxCMD_LINE_VAL_STRING,
3316 wxCMD_LINE_OPTION_MANDATORY | wxCMD_LINE_NEEDS_SEPARATOR);
3317
3318 switch ( parser.Parse() )
3319 {
3320 case -1:
3321 wxLogMessage("Help was given, terminating.");
3322 break;
3323
3324 case 0:
3325 ShowCmdLine(parser);
3326 break;
3327
3328 default:
3329 wxLogMessage("Syntax error detected, aborting.");
3330 break;
3331 }
3332 #endif // TEST_CMDLINE
3333
3334 #ifdef TEST_STRINGS
3335 if ( 0 )
3336 {
3337 TestPChar();
3338 TestString();
3339 }
3340 TestStringSub();
3341 if ( 0 )
3342 {
3343 TestStringConstruction();
3344 TestStringFormat();
3345 TestStringFind();
3346 TestStringTokenizer();
3347 TestStringReplace();
3348 }
3349 #endif // TEST_STRINGS
3350
3351 #ifdef TEST_ARRAYS
3352 wxArrayString a1;
3353 a1.Add("tiger");
3354 a1.Add("cat");
3355 a1.Add("lion");
3356 a1.Add("dog");
3357 a1.Add("human");
3358 a1.Add("ape");
3359
3360 puts("*** Initially:");
3361
3362 PrintArray("a1", a1);
3363
3364 wxArrayString a2(a1);
3365 PrintArray("a2", a2);
3366
3367 wxSortedArrayString a3(a1);
3368 PrintArray("a3", a3);
3369
3370 puts("*** After deleting a string from a1");
3371 a1.Remove(2);
3372
3373 PrintArray("a1", a1);
3374 PrintArray("a2", a2);
3375 PrintArray("a3", a3);
3376
3377 puts("*** After reassigning a1 to a2 and a3");
3378 a3 = a2 = a1;
3379 PrintArray("a2", a2);
3380 PrintArray("a3", a3);
3381
3382 puts("*** After sorting a1");
3383 a1.Sort();
3384 PrintArray("a1", a1);
3385
3386 puts("*** After sorting a1 in reverse order");
3387 a1.Sort(TRUE);
3388 PrintArray("a1", a1);
3389
3390 puts("*** After sorting a1 by the string length");
3391 a1.Sort(StringLenCompare);
3392 PrintArray("a1", a1);
3393
3394 TestArrayOfObjects();
3395 #endif // TEST_ARRAYS
3396
3397 #ifdef TEST_DIR
3398 TestDirEnum();
3399 #endif // TEST_DIR
3400
3401 #ifdef TEST_DLLLOADER
3402 TestDllLoad();
3403 #endif // TEST_DLLLOADER
3404
3405 #ifdef TEST_EXECUTE
3406 TestExecute();
3407 #endif // TEST_EXECUTE
3408
3409 #ifdef TEST_FILECONF
3410 TestFileConfRead();
3411 #endif // TEST_FILECONF
3412
3413 #ifdef TEST_LIST
3414 TestListCtor();
3415 #endif // TEST_LIST
3416
3417 #ifdef TEST_LOG
3418 wxString s;
3419 for ( size_t n = 0; n < 8000; n++ )
3420 {
3421 s << (char)('A' + (n % 26));
3422 }
3423
3424 wxString msg;
3425 msg.Printf("A very very long message: '%s', the end!\n", s.c_str());
3426
3427 // this one shouldn't be truncated
3428 printf(msg);
3429
3430 // but this one will because log functions use fixed size buffer
3431 // (note that it doesn't need '\n' at the end neither - will be added
3432 // by wxLog anyhow)
3433 wxLogMessage("A very very long message 2: '%s', the end!", s.c_str());
3434 #endif // TEST_LOG
3435
3436 #ifdef TEST_FILE
3437 TestFileRead();
3438 TestTextFileRead();
3439 #endif // TEST_FILE
3440
3441 #ifdef TEST_THREADS
3442 int nCPUs = wxThread::GetCPUCount();
3443 printf("This system has %d CPUs\n", nCPUs);
3444 if ( nCPUs != -1 )
3445 wxThread::SetConcurrency(nCPUs);
3446
3447 if ( argc > 1 && argv[1][0] == 't' )
3448 wxLog::AddTraceMask("thread");
3449
3450 if ( 1 )
3451 TestDetachedThreads();
3452 if ( 1 )
3453 TestJoinableThreads();
3454 if ( 1 )
3455 TestThreadSuspend();
3456 if ( 1 )
3457 TestThreadDelete();
3458
3459 #endif // TEST_THREADS
3460
3461 #ifdef TEST_LONGLONG
3462 // seed pseudo random generator
3463 srand((unsigned)time(NULL));
3464
3465 if ( 0 )
3466 {
3467 TestSpeed();
3468 }
3469 if ( 0 )
3470 {
3471 TestMultiplication();
3472 TestDivision();
3473 TestAddition();
3474 TestLongLongConversion();
3475 TestBitOperations();
3476 }
3477 TestLongLongComparison();
3478 #endif // TEST_LONGLONG
3479
3480 #ifdef TEST_HASH
3481 TestHash();
3482 #endif // TEST_HASH
3483
3484 #ifdef TEST_MIME
3485 wxLog::AddTraceMask(_T("mime"));
3486 if ( 0 )
3487 TestMimeEnum();
3488 TestMimeOverride();
3489 TestMimeFilename();
3490 #endif // TEST_MIME
3491
3492 #ifdef TEST_INFO_FUNCTIONS
3493 TestOsInfo();
3494 TestUserInfo();
3495 #endif // TEST_INFO_FUNCTIONS
3496
3497 #ifdef TEST_SOCKETS
3498 if ( 0 )
3499 {
3500 TestSocketServer();
3501 TestSocketClient();
3502 TestProtocolFtp();
3503 }
3504 TestProtocolFtpUpload();
3505 #endif // TEST_SOCKETS
3506
3507 #ifdef TEST_TIMER
3508 TestStopWatch();
3509 #endif // TEST_TIMER
3510
3511 #ifdef TEST_DATETIME
3512 if ( 0 )
3513 {
3514 TestTimeSet();
3515 TestTimeStatic();
3516 TestTimeRange();
3517 TestTimeZones();
3518 TestTimeTicks();
3519 TestTimeJDN();
3520 TestTimeDST();
3521 TestTimeWDays();
3522 TestTimeWNumber();
3523 TestTimeParse();
3524 TestTimeArithmetics();
3525 TestTimeHolidays();
3526 TestTimeFormat();
3527
3528 TestTimeZoneBug();
3529 }
3530 TestTimeMS();
3531 if ( 0 )
3532 TestInteractive();
3533 #endif // TEST_DATETIME
3534
3535 #ifdef TEST_VCARD
3536 if ( 0 )
3537 TestVCardRead();
3538 TestVCardWrite();
3539 #endif // TEST_VCARD
3540
3541 #ifdef TEST_WCHAR
3542 TestUtf8();
3543 #endif // TEST_WCHAR
3544
3545 #ifdef TEST_ZIP
3546 TestZipStreamRead();
3547 #endif // TEST_ZIP
3548
3549 wxUninitialize();
3550
3551 return 0;
3552 }
3553