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