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