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