]> git.saurik.com Git - wxWidgets.git/blob - samples/console/console.cpp
added wxCmdLineParser::ConvertStringToArgs(), wxApp::ConertToStandardCommandArgs...
[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 "wx/defs.h"
21
22 #if wxUSE_GUI
23 #error "This sample can't be compiled in GUI mode."
24 #endif // wxUSE_GUI
25
26 #include <stdio.h>
27
28 #include "wx/string.h"
29 #include "wx/file.h"
30 #include "wx/app.h"
31
32 // without this pragma, the stupid compiler precompiles #defines below so that
33 // changing them doesn't "take place" later!
34 #ifdef __VISUALC__
35 #pragma hdrstop
36 #endif
37
38 // ----------------------------------------------------------------------------
39 // conditional compilation
40 // ----------------------------------------------------------------------------
41
42 // what to test (in alphabetic order)? uncomment the line below to do all tests
43 //#define TEST_ALL
44 #ifdef TEST_ALL
45 #define TEST_ARRAYS
46 #define TEST_CHARSET
47 #define TEST_CMDLINE
48 #define TEST_DATETIME
49 #define TEST_DIR
50 #define TEST_DLLLOADER
51 #define TEST_ENVIRON
52 #define TEST_EXECUTE
53 #define TEST_FILE
54 #define TEST_FILECONF
55 #define TEST_FILENAME
56 #define TEST_FILETIME
57 #define TEST_FTP
58 #define TEST_HASH
59 #define TEST_INFO_FUNCTIONS
60 #define TEST_LIST
61 #define TEST_LOCALE
62 #define TEST_LOG
63 #define TEST_LONGLONG
64 #define TEST_MIME
65 #define TEST_PATHLIST
66 #define TEST_REGCONF
67 #define TEST_REGEX
68 #define TEST_REGISTRY
69 #define TEST_SNGLINST
70 #define TEST_SOCKETS
71 #define TEST_STREAMS
72 #define TEST_STRINGS
73 #define TEST_THREADS
74 #define TEST_TIMER
75 // #define TEST_VCARD -- don't enable this (VZ)
76 #define TEST_WCHAR
77 #define TEST_ZIP
78 #define TEST_ZLIB
79 #else
80 #define TEST_CMDLINE
81 #endif
82
83 #ifdef TEST_SNGLINST
84 #include "wx/snglinst.h"
85 #endif // TEST_SNGLINST
86
87 // ----------------------------------------------------------------------------
88 // test class for container objects
89 // ----------------------------------------------------------------------------
90
91 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
92
93 class Bar // Foo is already taken in the hash test
94 {
95 public:
96 Bar(const wxString& name) : m_name(name) { ms_bars++; }
97 ~Bar() { ms_bars--; }
98
99 static size_t GetNumber() { return ms_bars; }
100
101 const char *GetName() const { return m_name; }
102
103 private:
104 wxString m_name;
105
106 static size_t ms_bars;
107 };
108
109 size_t Bar::ms_bars = 0;
110
111 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
112
113 // ============================================================================
114 // implementation
115 // ============================================================================
116
117 // ----------------------------------------------------------------------------
118 // helper functions
119 // ----------------------------------------------------------------------------
120
121 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
122
123 // replace TABs with \t and CRs with \n
124 static wxString MakePrintable(const wxChar *s)
125 {
126 wxString str(s);
127 (void)str.Replace(_T("\t"), _T("\\t"));
128 (void)str.Replace(_T("\n"), _T("\\n"));
129 (void)str.Replace(_T("\r"), _T("\\r"));
130
131 return str;
132 }
133
134 #endif // MakePrintable() is used
135
136 // ----------------------------------------------------------------------------
137 // wxFontMapper::CharsetToEncoding
138 // ----------------------------------------------------------------------------
139
140 #ifdef TEST_CHARSET
141
142 #include "wx/fontmap.h"
143
144 static void TestCharset()
145 {
146 static const wxChar *charsets[] =
147 {
148 // some vali charsets
149 _T("us-ascii "),
150 _T("iso8859-1 "),
151 _T("iso-8859-12 "),
152 _T("koi8-r "),
153 _T("utf-7 "),
154 _T("cp1250 "),
155 _T("windows-1252"),
156
157 // and now some bogus ones
158 _T(" "),
159 _T("cp1249 "),
160 _T("iso--8859-1 "),
161 _T("iso-8859-19 "),
162 };
163
164 for ( size_t n = 0; n < WXSIZEOF(charsets); n++ )
165 {
166 wxFontEncoding enc = wxTheFontMapper->CharsetToEncoding(charsets[n]);
167 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
168 charsets[n],
169 wxTheFontMapper->GetEncodingName(enc).c_str(),
170 wxTheFontMapper->GetEncodingDescription(enc).c_str());
171 }
172 }
173
174 #endif // TEST_CHARSET
175
176 // ----------------------------------------------------------------------------
177 // wxCmdLineParser
178 // ----------------------------------------------------------------------------
179
180 #ifdef TEST_CMDLINE
181
182 #include "wx/cmdline.h"
183 #include "wx/datetime.h"
184
185 #if wxUSE_CMDLINE_PARSER
186
187 static void ShowCmdLine(const wxCmdLineParser& parser)
188 {
189 wxString s = "Input files: ";
190
191 size_t count = parser.GetParamCount();
192 for ( size_t param = 0; param < count; param++ )
193 {
194 s << parser.GetParam(param) << ' ';
195 }
196
197 s << '\n'
198 << "Verbose:\t" << (parser.Found("v") ? "yes" : "no") << '\n'
199 << "Quiet:\t" << (parser.Found("q") ? "yes" : "no") << '\n';
200
201 wxString strVal;
202 long lVal;
203 wxDateTime dt;
204 if ( parser.Found("o", &strVal) )
205 s << "Output file:\t" << strVal << '\n';
206 if ( parser.Found("i", &strVal) )
207 s << "Input dir:\t" << strVal << '\n';
208 if ( parser.Found("s", &lVal) )
209 s << "Size:\t" << lVal << '\n';
210 if ( parser.Found("d", &dt) )
211 s << "Date:\t" << dt.FormatISODate() << '\n';
212 if ( parser.Found("project_name", &strVal) )
213 s << "Project:\t" << strVal << '\n';
214
215 wxLogMessage(s);
216 }
217
218 #endif // wxUSE_CMDLINE_PARSER
219
220 static void TestCmdLineConvert()
221 {
222 static const char *cmdlines[] =
223 {
224 "arg1 arg2",
225 "-a \"-bstring 1\" -c\"string 2\" \"string 3\"",
226 "literal \\\" and \"\"",
227 };
228
229 for ( size_t n = 0; n < WXSIZEOF(cmdlines); n++ )
230 {
231 const char *cmdline = cmdlines[n];
232 printf("Parsing: %s\n", cmdline);
233 wxArrayString args = wxCmdLineParser::ConvertStringToArgs(cmdline);
234
235 size_t count = args.GetCount();
236 printf("\targc = %u\n", count);
237 for ( size_t arg = 0; arg < count; arg++ )
238 {
239 printf("\targv[%u] = %s\n", arg, args[arg]);
240 }
241 }
242 }
243
244 #endif // TEST_CMDLINE
245
246 // ----------------------------------------------------------------------------
247 // wxDir
248 // ----------------------------------------------------------------------------
249
250 #ifdef TEST_DIR
251
252 #include "wx/dir.h"
253
254 #ifdef __UNIX__
255 static const wxChar *ROOTDIR = _T("/");
256 static const wxChar *TESTDIR = _T("/usr");
257 #elif defined(__WXMSW__)
258 static const wxChar *ROOTDIR = _T("c:\\");
259 static const wxChar *TESTDIR = _T("d:\\");
260 #else
261 #error "don't know where the root directory is"
262 #endif
263
264 static void TestDirEnumHelper(wxDir& dir,
265 int flags = wxDIR_DEFAULT,
266 const wxString& filespec = wxEmptyString)
267 {
268 wxString filename;
269
270 if ( !dir.IsOpened() )
271 return;
272
273 bool cont = dir.GetFirst(&filename, filespec, flags);
274 while ( cont )
275 {
276 printf("\t%s\n", filename.c_str());
277
278 cont = dir.GetNext(&filename);
279 }
280
281 puts("");
282 }
283
284 static void TestDirEnum()
285 {
286 puts("*** Testing wxDir::GetFirst/GetNext ***");
287
288 wxDir dir(wxGetCwd());
289
290 puts("Enumerating everything in current directory:");
291 TestDirEnumHelper(dir);
292
293 puts("Enumerating really everything in current directory:");
294 TestDirEnumHelper(dir, wxDIR_DEFAULT | wxDIR_DOTDOT);
295
296 puts("Enumerating object files in current directory:");
297 TestDirEnumHelper(dir, wxDIR_DEFAULT, "*.o");
298
299 puts("Enumerating directories in current directory:");
300 TestDirEnumHelper(dir, wxDIR_DIRS);
301
302 puts("Enumerating files in current directory:");
303 TestDirEnumHelper(dir, wxDIR_FILES);
304
305 puts("Enumerating files including hidden in current directory:");
306 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
307
308 dir.Open(ROOTDIR);
309
310 puts("Enumerating everything in root directory:");
311 TestDirEnumHelper(dir, wxDIR_DEFAULT);
312
313 puts("Enumerating directories in root directory:");
314 TestDirEnumHelper(dir, wxDIR_DIRS);
315
316 puts("Enumerating files in root directory:");
317 TestDirEnumHelper(dir, wxDIR_FILES);
318
319 puts("Enumerating files including hidden in root directory:");
320 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
321
322 puts("Enumerating files in non existing directory:");
323 wxDir dirNo("nosuchdir");
324 TestDirEnumHelper(dirNo);
325 }
326
327 class DirPrintTraverser : public wxDirTraverser
328 {
329 public:
330 virtual wxDirTraverseResult OnFile(const wxString& filename)
331 {
332 return wxDIR_CONTINUE;
333 }
334
335 virtual wxDirTraverseResult OnDir(const wxString& dirname)
336 {
337 wxString path, name, ext;
338 wxSplitPath(dirname, &path, &name, &ext);
339
340 if ( !ext.empty() )
341 name << _T('.') << ext;
342
343 wxString indent;
344 for ( const wxChar *p = path.c_str(); *p; p++ )
345 {
346 if ( wxIsPathSeparator(*p) )
347 indent += _T(" ");
348 }
349
350 printf("%s%s\n", indent.c_str(), name.c_str());
351
352 return wxDIR_CONTINUE;
353 }
354 };
355
356 static void TestDirTraverse()
357 {
358 puts("*** Testing wxDir::Traverse() ***");
359
360 // enum all files
361 wxArrayString files;
362 size_t n = wxDir::GetAllFiles(TESTDIR, &files);
363 printf("There are %u files under '%s'\n", n, TESTDIR);
364 if ( n > 1 )
365 {
366 printf("First one is '%s'\n", files[0u].c_str());
367 printf(" last one is '%s'\n", files[n - 1].c_str());
368 }
369
370 // enum again with custom traverser
371 wxDir dir(TESTDIR);
372 DirPrintTraverser traverser;
373 dir.Traverse(traverser, _T(""), wxDIR_DIRS | wxDIR_HIDDEN);
374 }
375
376 #endif // TEST_DIR
377
378 // ----------------------------------------------------------------------------
379 // wxDllLoader
380 // ----------------------------------------------------------------------------
381
382 #ifdef TEST_DLLLOADER
383
384 #include "wx/dynlib.h"
385
386 static void TestDllLoad()
387 {
388 #if defined(__WXMSW__)
389 static const wxChar *LIB_NAME = _T("kernel32.dll");
390 static const wxChar *FUNC_NAME = _T("lstrlenA");
391 #elif defined(__UNIX__)
392 // weird: using just libc.so does *not* work!
393 static const wxChar *LIB_NAME = _T("/lib/libc-2.0.7.so");
394 static const wxChar *FUNC_NAME = _T("strlen");
395 #else
396 #error "don't know how to test wxDllLoader on this platform"
397 #endif
398
399 puts("*** testing wxDllLoader ***\n");
400
401 wxDllType dllHandle = wxDllLoader::LoadLibrary(LIB_NAME);
402 if ( !dllHandle )
403 {
404 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME);
405 }
406 else
407 {
408 typedef int (*strlenType)(const char *);
409 strlenType pfnStrlen = (strlenType)wxDllLoader::GetSymbol(dllHandle, FUNC_NAME);
410 if ( !pfnStrlen )
411 {
412 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
413 FUNC_NAME, LIB_NAME);
414 }
415 else
416 {
417 if ( pfnStrlen("foo") != 3 )
418 {
419 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
420 }
421 else
422 {
423 puts("... ok");
424 }
425 }
426
427 wxDllLoader::UnloadLibrary(dllHandle);
428 }
429 }
430
431 #endif // TEST_DLLLOADER
432
433 // ----------------------------------------------------------------------------
434 // wxGet/SetEnv
435 // ----------------------------------------------------------------------------
436
437 #ifdef TEST_ENVIRON
438
439 #include "wx/utils.h"
440
441 static wxString MyGetEnv(const wxString& var)
442 {
443 wxString val;
444 if ( !wxGetEnv(var, &val) )
445 val = _T("<empty>");
446 else
447 val = wxString(_T('\'')) + val + _T('\'');
448
449 return val;
450 }
451
452 static void TestEnvironment()
453 {
454 const wxChar *var = _T("wxTestVar");
455
456 puts("*** testing environment access functions ***");
457
458 printf("Initially getenv(%s) = %s\n", var, MyGetEnv(var).c_str());
459 wxSetEnv(var, _T("value for wxTestVar"));
460 printf("After wxSetEnv: getenv(%s) = %s\n", var, MyGetEnv(var).c_str());
461 wxSetEnv(var, _T("another value"));
462 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var, MyGetEnv(var).c_str());
463 wxUnsetEnv(var);
464 printf("After wxUnsetEnv: getenv(%s) = %s\n", var, MyGetEnv(var).c_str());
465 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
466 }
467
468 #endif // TEST_ENVIRON
469
470 // ----------------------------------------------------------------------------
471 // wxExecute
472 // ----------------------------------------------------------------------------
473
474 #ifdef TEST_EXECUTE
475
476 #include "wx/utils.h"
477
478 static void TestExecute()
479 {
480 puts("*** testing wxExecute ***");
481
482 #ifdef __UNIX__
483 #define COMMAND "cat -n ../../Makefile" // "echo hi"
484 #define SHELL_COMMAND "echo hi from shell"
485 #define REDIRECT_COMMAND COMMAND // "date"
486 #elif defined(__WXMSW__)
487 #define COMMAND "command.com -c 'echo hi'"
488 #define SHELL_COMMAND "echo hi"
489 #define REDIRECT_COMMAND COMMAND
490 #else
491 #error "no command to exec"
492 #endif // OS
493
494 printf("Testing wxShell: ");
495 fflush(stdout);
496 if ( wxShell(SHELL_COMMAND) )
497 puts("Ok.");
498 else
499 puts("ERROR.");
500
501 printf("Testing wxExecute: ");
502 fflush(stdout);
503 if ( wxExecute(COMMAND, TRUE /* sync */) == 0 )
504 puts("Ok.");
505 else
506 puts("ERROR.");
507
508 #if 0 // no, it doesn't work (yet?)
509 printf("Testing async wxExecute: ");
510 fflush(stdout);
511 if ( wxExecute(COMMAND) != 0 )
512 puts("Ok (command launched).");
513 else
514 puts("ERROR.");
515 #endif // 0
516
517 printf("Testing wxExecute with redirection:\n");
518 wxArrayString output;
519 if ( wxExecute(REDIRECT_COMMAND, output) != 0 )
520 {
521 puts("ERROR.");
522 }
523 else
524 {
525 size_t count = output.GetCount();
526 for ( size_t n = 0; n < count; n++ )
527 {
528 printf("\t%s\n", output[n].c_str());
529 }
530
531 puts("Ok.");
532 }
533 }
534
535 #endif // TEST_EXECUTE
536
537 // ----------------------------------------------------------------------------
538 // file
539 // ----------------------------------------------------------------------------
540
541 #ifdef TEST_FILE
542
543 #include "wx/file.h"
544 #include "wx/ffile.h"
545 #include "wx/textfile.h"
546
547 static void TestFileRead()
548 {
549 puts("*** wxFile read test ***");
550
551 wxFile file(_T("testdata.fc"));
552 if ( file.IsOpened() )
553 {
554 printf("File length: %lu\n", file.Length());
555
556 puts("File dump:\n----------");
557
558 static const off_t len = 1024;
559 char buf[len];
560 for ( ;; )
561 {
562 off_t nRead = file.Read(buf, len);
563 if ( nRead == wxInvalidOffset )
564 {
565 printf("Failed to read the file.");
566 break;
567 }
568
569 fwrite(buf, nRead, 1, stdout);
570
571 if ( nRead < len )
572 break;
573 }
574
575 puts("----------");
576 }
577 else
578 {
579 printf("ERROR: can't open test file.\n");
580 }
581
582 puts("");
583 }
584
585 static void TestTextFileRead()
586 {
587 puts("*** wxTextFile read test ***");
588
589 wxTextFile file(_T("testdata.fc"));
590 if ( file.Open() )
591 {
592 printf("Number of lines: %u\n", file.GetLineCount());
593 printf("Last line: '%s'\n", file.GetLastLine().c_str());
594
595 wxString s;
596
597 puts("\nDumping the entire file:");
598 for ( s = file.GetFirstLine(); !file.Eof(); s = file.GetNextLine() )
599 {
600 printf("%6u: %s\n", file.GetCurrentLine() + 1, s.c_str());
601 }
602 printf("%6u: %s\n", file.GetCurrentLine() + 1, s.c_str());
603
604 puts("\nAnd now backwards:");
605 for ( s = file.GetLastLine();
606 file.GetCurrentLine() != 0;
607 s = file.GetPrevLine() )
608 {
609 printf("%6u: %s\n", file.GetCurrentLine() + 1, s.c_str());
610 }
611 printf("%6u: %s\n", file.GetCurrentLine() + 1, s.c_str());
612 }
613 else
614 {
615 printf("ERROR: can't open '%s'\n", file.GetName());
616 }
617
618 puts("");
619 }
620
621 static void TestFileCopy()
622 {
623 puts("*** Testing wxCopyFile ***");
624
625 static const wxChar *filename1 = _T("testdata.fc");
626 static const wxChar *filename2 = _T("test2");
627 if ( !wxCopyFile(filename1, filename2) )
628 {
629 puts("ERROR: failed to copy file");
630 }
631 else
632 {
633 wxFFile f1(filename1, "rb"),
634 f2(filename2, "rb");
635
636 if ( !f1.IsOpened() || !f2.IsOpened() )
637 {
638 puts("ERROR: failed to open file(s)");
639 }
640 else
641 {
642 wxString s1, s2;
643 if ( !f1.ReadAll(&s1) || !f2.ReadAll(&s2) )
644 {
645 puts("ERROR: failed to read file(s)");
646 }
647 else
648 {
649 if ( (s1.length() != s2.length()) ||
650 (memcmp(s1.c_str(), s2.c_str(), s1.length()) != 0) )
651 {
652 puts("ERROR: copy error!");
653 }
654 else
655 {
656 puts("File was copied ok.");
657 }
658 }
659 }
660 }
661
662 if ( !wxRemoveFile(filename2) )
663 {
664 puts("ERROR: failed to remove the file");
665 }
666
667 puts("");
668 }
669
670 #endif // TEST_FILE
671
672 // ----------------------------------------------------------------------------
673 // wxFileConfig
674 // ----------------------------------------------------------------------------
675
676 #ifdef TEST_FILECONF
677
678 #include "wx/confbase.h"
679 #include "wx/fileconf.h"
680
681 static const struct FileConfTestData
682 {
683 const wxChar *name; // value name
684 const wxChar *value; // the value from the file
685 } fcTestData[] =
686 {
687 { _T("value1"), _T("one") },
688 { _T("value2"), _T("two") },
689 { _T("novalue"), _T("default") },
690 };
691
692 static void TestFileConfRead()
693 {
694 puts("*** testing wxFileConfig loading/reading ***");
695
696 wxFileConfig fileconf(_T("test"), wxEmptyString,
697 _T("testdata.fc"), wxEmptyString,
698 wxCONFIG_USE_RELATIVE_PATH);
699
700 // test simple reading
701 puts("\nReading config file:");
702 wxString defValue(_T("default")), value;
703 for ( size_t n = 0; n < WXSIZEOF(fcTestData); n++ )
704 {
705 const FileConfTestData& data = fcTestData[n];
706 value = fileconf.Read(data.name, defValue);
707 printf("\t%s = %s ", data.name, value.c_str());
708 if ( value == data.value )
709 {
710 puts("(ok)");
711 }
712 else
713 {
714 printf("(ERROR: should be %s)\n", data.value);
715 }
716 }
717
718 // test enumerating the entries
719 puts("\nEnumerating all root entries:");
720 long dummy;
721 wxString name;
722 bool cont = fileconf.GetFirstEntry(name, dummy);
723 while ( cont )
724 {
725 printf("\t%s = %s\n",
726 name.c_str(),
727 fileconf.Read(name.c_str(), _T("ERROR")).c_str());
728
729 cont = fileconf.GetNextEntry(name, dummy);
730 }
731 }
732
733 #endif // TEST_FILECONF
734
735 // ----------------------------------------------------------------------------
736 // wxFileName
737 // ----------------------------------------------------------------------------
738
739 #ifdef TEST_FILENAME
740
741 #include "wx/filename.h"
742
743 static struct FileNameInfo
744 {
745 const wxChar *fullname;
746 const wxChar *path;
747 const wxChar *name;
748 const wxChar *ext;
749 } filenames[] =
750 {
751 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
752 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
753 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
754 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
755 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
756 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
757 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
758 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
759 };
760
761 static void TestFileNameConstruction()
762 {
763 puts("*** testing wxFileName construction ***");
764
765 for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
766 {
767 wxFileName fn(filenames[n].fullname, wxPATH_UNIX);
768
769 printf("Filename: '%s'\t", fn.GetFullPath().c_str());
770 if ( !fn.Normalize(wxPATH_NORM_ALL, _T(""), wxPATH_UNIX) )
771 {
772 puts("ERROR (couldn't be normalized)");
773 }
774 else
775 {
776 printf("normalized: '%s'\n", fn.GetFullPath().c_str());
777 }
778 }
779
780 puts("");
781 }
782
783 static void TestFileNameSplit()
784 {
785 puts("*** testing wxFileName splitting ***");
786
787 for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
788 {
789 const FileNameInfo &fni = filenames[n];
790 wxString path, name, ext;
791 wxFileName::SplitPath(fni.fullname, &path, &name, &ext);
792
793 printf("%s -> path = '%s', name = '%s', ext = '%s'",
794 fni.fullname, path.c_str(), name.c_str(), ext.c_str());
795 if ( path != fni.path )
796 printf(" (ERROR: path = '%s')", fni.path);
797 if ( name != fni.name )
798 printf(" (ERROR: name = '%s')", fni.name);
799 if ( ext != fni.ext )
800 printf(" (ERROR: ext = '%s')", fni.ext);
801 puts("");
802 }
803
804 puts("");
805 }
806
807 static void TestFileNameComparison()
808 {
809 // TODO!
810 }
811
812 static void TestFileNameOperations()
813 {
814 // TODO!
815 }
816
817 static void TestFileNameCwd()
818 {
819 // TODO!
820 }
821
822 #endif // TEST_FILENAME
823
824 // ----------------------------------------------------------------------------
825 // wxFileName time functions
826 // ----------------------------------------------------------------------------
827
828 #ifdef TEST_FILETIME
829
830 #include <wx/filename.h>
831 #include <wx/datetime.h>
832
833 static void TestFileGetTimes()
834 {
835 wxFileName fn(_T("testdata.fc"));
836
837 wxDateTime dtAccess, dtMod, dtChange;
838 if ( !fn.GetTimes(&dtAccess, &dtMod, &dtChange) )
839 {
840 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
841 }
842 else
843 {
844 static const wxChar *fmt = _T("%Y-%b-%d %H:%M:%S");
845
846 wxPrintf(_T("File times for '%s':\n"), fn.GetFullPath().c_str());
847 wxPrintf(_T("Access: \t%s\n"), dtAccess.Format(fmt).c_str());
848 wxPrintf(_T("Mod/creation:\t%s\n"), dtMod.Format(fmt).c_str());
849 wxPrintf(_T("Change: \t%s\n"), dtChange.Format(fmt).c_str());
850 }
851 }
852
853 static void TestFileSetTimes()
854 {
855 wxFileName fn(_T("testdata.fc"));
856
857 wxDateTime dtAccess, dtMod, dtChange;
858 if ( !fn.Touch() )
859 {
860 wxPrintf(_T("ERROR: Touch() failed.\n"));
861 }
862 }
863
864 #endif // TEST_FILETIME
865
866 // ----------------------------------------------------------------------------
867 // wxHashTable
868 // ----------------------------------------------------------------------------
869
870 #ifdef TEST_HASH
871
872 #include "wx/hash.h"
873
874 struct Foo
875 {
876 Foo(int n_) { n = n_; count++; }
877 ~Foo() { count--; }
878
879 int n;
880
881 static size_t count;
882 };
883
884 size_t Foo::count = 0;
885
886 WX_DECLARE_LIST(Foo, wxListFoos);
887 WX_DECLARE_HASH(Foo, wxListFoos, wxHashFoos);
888
889 #include "wx/listimpl.cpp"
890
891 WX_DEFINE_LIST(wxListFoos);
892
893 static void TestHash()
894 {
895 puts("*** Testing wxHashTable ***\n");
896
897 {
898 wxHashFoos hash;
899 hash.DeleteContents(TRUE);
900
901 printf("Hash created: %u foos in hash, %u foos totally\n",
902 hash.GetCount(), Foo::count);
903
904 static const int hashTestData[] =
905 {
906 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
907 };
908
909 size_t n;
910 for ( n = 0; n < WXSIZEOF(hashTestData); n++ )
911 {
912 hash.Put(hashTestData[n], n, new Foo(n));
913 }
914
915 printf("Hash filled: %u foos in hash, %u foos totally\n",
916 hash.GetCount(), Foo::count);
917
918 puts("Hash access test:");
919 for ( n = 0; n < WXSIZEOF(hashTestData); n++ )
920 {
921 printf("\tGetting element with key %d, value %d: ",
922 hashTestData[n], n);
923 Foo *foo = hash.Get(hashTestData[n], n);
924 if ( !foo )
925 {
926 printf("ERROR, not found.\n");
927 }
928 else
929 {
930 printf("%d (%s)\n", foo->n,
931 (size_t)foo->n == n ? "ok" : "ERROR");
932 }
933 }
934
935 printf("\nTrying to get an element not in hash: ");
936
937 if ( hash.Get(1234) || hash.Get(1, 0) )
938 {
939 puts("ERROR: found!");
940 }
941 else
942 {
943 puts("ok (not found)");
944 }
945 }
946
947 printf("Hash destroyed: %u foos left\n", Foo::count);
948 }
949
950 #endif // TEST_HASH
951
952 // ----------------------------------------------------------------------------
953 // wxList
954 // ----------------------------------------------------------------------------
955
956 #ifdef TEST_LIST
957
958 #include "wx/list.h"
959
960 WX_DECLARE_LIST(Bar, wxListBars);
961 #include "wx/listimpl.cpp"
962 WX_DEFINE_LIST(wxListBars);
963
964 static void TestListCtor()
965 {
966 puts("*** Testing wxList construction ***\n");
967
968 {
969 wxListBars list1;
970 list1.Append(new Bar(_T("first")));
971 list1.Append(new Bar(_T("second")));
972
973 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
974 list1.GetCount(), Bar::GetNumber());
975
976 wxListBars list2;
977 list2 = list1;
978
979 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
980 list1.GetCount(), list2.GetCount(), Bar::GetNumber());
981
982 list1.DeleteContents(TRUE);
983 }
984
985 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
986 }
987
988 #endif // TEST_LIST
989
990 // ----------------------------------------------------------------------------
991 // wxLocale
992 // ----------------------------------------------------------------------------
993
994 #ifdef TEST_LOCALE
995
996 #include "wx/intl.h"
997 #include "wx/utils.h" // for wxSetEnv
998
999 static wxLocale gs_localeDefault(wxLANGUAGE_ENGLISH);
1000
1001 // find the name of the language from its value
1002 static const char *GetLangName(int lang)
1003 {
1004 static const char *languageNames[] =
1005 {
1006 "DEFAULT",
1007 "UNKNOWN",
1008 "ABKHAZIAN",
1009 "AFAR",
1010 "AFRIKAANS",
1011 "ALBANIAN",
1012 "AMHARIC",
1013 "ARABIC",
1014 "ARABIC_ALGERIA",
1015 "ARABIC_BAHRAIN",
1016 "ARABIC_EGYPT",
1017 "ARABIC_IRAQ",
1018 "ARABIC_JORDAN",
1019 "ARABIC_KUWAIT",
1020 "ARABIC_LEBANON",
1021 "ARABIC_LIBYA",
1022 "ARABIC_MOROCCO",
1023 "ARABIC_OMAN",
1024 "ARABIC_QATAR",
1025 "ARABIC_SAUDI_ARABIA",
1026 "ARABIC_SUDAN",
1027 "ARABIC_SYRIA",
1028 "ARABIC_TUNISIA",
1029 "ARABIC_UAE",
1030 "ARABIC_YEMEN",
1031 "ARMENIAN",
1032 "ASSAMESE",
1033 "AYMARA",
1034 "AZERI",
1035 "AZERI_CYRILLIC",
1036 "AZERI_LATIN",
1037 "BASHKIR",
1038 "BASQUE",
1039 "BELARUSIAN",
1040 "BENGALI",
1041 "BHUTANI",
1042 "BIHARI",
1043 "BISLAMA",
1044 "BRETON",
1045 "BULGARIAN",
1046 "BURMESE",
1047 "CAMBODIAN",
1048 "CATALAN",
1049 "CHINESE",
1050 "CHINESE_SIMPLIFIED",
1051 "CHINESE_TRADITIONAL",
1052 "CHINESE_HONGKONG",
1053 "CHINESE_MACAU",
1054 "CHINESE_SINGAPORE",
1055 "CHINESE_TAIWAN",
1056 "CORSICAN",
1057 "CROATIAN",
1058 "CZECH",
1059 "DANISH",
1060 "DUTCH",
1061 "DUTCH_BELGIAN",
1062 "ENGLISH",
1063 "ENGLISH_UK",
1064 "ENGLISH_US",
1065 "ENGLISH_AUSTRALIA",
1066 "ENGLISH_BELIZE",
1067 "ENGLISH_BOTSWANA",
1068 "ENGLISH_CANADA",
1069 "ENGLISH_CARIBBEAN",
1070 "ENGLISH_DENMARK",
1071 "ENGLISH_EIRE",
1072 "ENGLISH_JAMAICA",
1073 "ENGLISH_NEW_ZEALAND",
1074 "ENGLISH_PHILIPPINES",
1075 "ENGLISH_SOUTH_AFRICA",
1076 "ENGLISH_TRINIDAD",
1077 "ENGLISH_ZIMBABWE",
1078 "ESPERANTO",
1079 "ESTONIAN",
1080 "FAEROESE",
1081 "FARSI",
1082 "FIJI",
1083 "FINNISH",
1084 "FRENCH",
1085 "FRENCH_BELGIAN",
1086 "FRENCH_CANADIAN",
1087 "FRENCH_LUXEMBOURG",
1088 "FRENCH_MONACO",
1089 "FRENCH_SWISS",
1090 "FRISIAN",
1091 "GALICIAN",
1092 "GEORGIAN",
1093 "GERMAN",
1094 "GERMAN_AUSTRIAN",
1095 "GERMAN_BELGIUM",
1096 "GERMAN_LIECHTENSTEIN",
1097 "GERMAN_LUXEMBOURG",
1098 "GERMAN_SWISS",
1099 "GREEK",
1100 "GREENLANDIC",
1101 "GUARANI",
1102 "GUJARATI",
1103 "HAUSA",
1104 "HEBREW",
1105 "HINDI",
1106 "HUNGARIAN",
1107 "ICELANDIC",
1108 "INDONESIAN",
1109 "INTERLINGUA",
1110 "INTERLINGUE",
1111 "INUKTITUT",
1112 "INUPIAK",
1113 "IRISH",
1114 "ITALIAN",
1115 "ITALIAN_SWISS",
1116 "JAPANESE",
1117 "JAVANESE",
1118 "KANNADA",
1119 "KASHMIRI",
1120 "KASHMIRI_INDIA",
1121 "KAZAKH",
1122 "KERNEWEK",
1123 "KINYARWANDA",
1124 "KIRGHIZ",
1125 "KIRUNDI",
1126 "KONKANI",
1127 "KOREAN",
1128 "KURDISH",
1129 "LAOTHIAN",
1130 "LATIN",
1131 "LATVIAN",
1132 "LINGALA",
1133 "LITHUANIAN",
1134 "MACEDONIAN",
1135 "MALAGASY",
1136 "MALAY",
1137 "MALAYALAM",
1138 "MALAY_BRUNEI_DARUSSALAM",
1139 "MALAY_MALAYSIA",
1140 "MALTESE",
1141 "MANIPURI",
1142 "MAORI",
1143 "MARATHI",
1144 "MOLDAVIAN",
1145 "MONGOLIAN",
1146 "NAURU",
1147 "NEPALI",
1148 "NEPALI_INDIA",
1149 "NORWEGIAN_BOKMAL",
1150 "NORWEGIAN_NYNORSK",
1151 "OCCITAN",
1152 "ORIYA",
1153 "OROMO",
1154 "PASHTO",
1155 "POLISH",
1156 "PORTUGUESE",
1157 "PORTUGUESE_BRAZILIAN",
1158 "PUNJABI",
1159 "QUECHUA",
1160 "RHAETO_ROMANCE",
1161 "ROMANIAN",
1162 "RUSSIAN",
1163 "RUSSIAN_UKRAINE",
1164 "SAMOAN",
1165 "SANGHO",
1166 "SANSKRIT",
1167 "SCOTS_GAELIC",
1168 "SERBIAN",
1169 "SERBIAN_CYRILLIC",
1170 "SERBIAN_LATIN",
1171 "SERBO_CROATIAN",
1172 "SESOTHO",
1173 "SETSWANA",
1174 "SHONA",
1175 "SINDHI",
1176 "SINHALESE",
1177 "SISWATI",
1178 "SLOVAK",
1179 "SLOVENIAN",
1180 "SOMALI",
1181 "SPANISH",
1182 "SPANISH_ARGENTINA",
1183 "SPANISH_BOLIVIA",
1184 "SPANISH_CHILE",
1185 "SPANISH_COLOMBIA",
1186 "SPANISH_COSTA_RICA",
1187 "SPANISH_DOMINICAN_REPUBLIC",
1188 "SPANISH_ECUADOR",
1189 "SPANISH_EL_SALVADOR",
1190 "SPANISH_GUATEMALA",
1191 "SPANISH_HONDURAS",
1192 "SPANISH_MEXICAN",
1193 "SPANISH_MODERN",
1194 "SPANISH_NICARAGUA",
1195 "SPANISH_PANAMA",
1196 "SPANISH_PARAGUAY",
1197 "SPANISH_PERU",
1198 "SPANISH_PUERTO_RICO",
1199 "SPANISH_URUGUAY",
1200 "SPANISH_US",
1201 "SPANISH_VENEZUELA",
1202 "SUNDANESE",
1203 "SWAHILI",
1204 "SWEDISH",
1205 "SWEDISH_FINLAND",
1206 "TAGALOG",
1207 "TAJIK",
1208 "TAMIL",
1209 "TATAR",
1210 "TELUGU",
1211 "THAI",
1212 "TIBETAN",
1213 "TIGRINYA",
1214 "TONGA",
1215 "TSONGA",
1216 "TURKISH",
1217 "TURKMEN",
1218 "TWI",
1219 "UIGHUR",
1220 "UKRAINIAN",
1221 "URDU",
1222 "URDU_INDIA",
1223 "URDU_PAKISTAN",
1224 "UZBEK",
1225 "UZBEK_CYRILLIC",
1226 "UZBEK_LATIN",
1227 "VIETNAMESE",
1228 "VOLAPUK",
1229 "WELSH",
1230 "WOLOF",
1231 "XHOSA",
1232 "YIDDISH",
1233 "YORUBA",
1234 "ZHUANG",
1235 "ZULU",
1236 };
1237
1238 if ( (size_t)lang < WXSIZEOF(languageNames) )
1239 return languageNames[lang];
1240 else
1241 return "INVALID";
1242 }
1243
1244 static void TestDefaultLang()
1245 {
1246 puts("*** Testing wxLocale::GetSystemLanguage ***");
1247
1248 static const wxChar *langStrings[] =
1249 {
1250 NULL, // system default
1251 _T("C"),
1252 _T("fr"),
1253 _T("fr_FR"),
1254 _T("en"),
1255 _T("en_GB"),
1256 _T("en_US"),
1257 _T("de_DE.iso88591"),
1258 _T("german"),
1259 _T("?"), // invalid lang spec
1260 _T("klingonese"), // I bet on some systems it does exist...
1261 };
1262
1263 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1264 wxLocale::GetSystemEncodingName().c_str(),
1265 wxLocale::GetSystemEncoding());
1266
1267 for ( size_t n = 0; n < WXSIZEOF(langStrings); n++ )
1268 {
1269 const char *langStr = langStrings[n];
1270 if ( langStr )
1271 {
1272 // FIXME: this doesn't do anything at all under Windows, we need
1273 // to create a new wxLocale!
1274 wxSetEnv(_T("LC_ALL"), langStr);
1275 }
1276
1277 int lang = gs_localeDefault.GetSystemLanguage();
1278 printf("Locale for '%s' is %s.\n",
1279 langStr ? langStr : "system default", GetLangName(lang));
1280 }
1281 }
1282
1283 #endif // TEST_LOCALE
1284
1285 // ----------------------------------------------------------------------------
1286 // MIME types
1287 // ----------------------------------------------------------------------------
1288
1289 #ifdef TEST_MIME
1290
1291 #include "wx/mimetype.h"
1292
1293 static void TestMimeEnum()
1294 {
1295 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1296
1297 wxArrayString mimetypes;
1298
1299 size_t count = wxTheMimeTypesManager->EnumAllFileTypes(mimetypes);
1300
1301 printf("*** All %u known filetypes: ***\n", count);
1302
1303 wxArrayString exts;
1304 wxString desc;
1305
1306 for ( size_t n = 0; n < count; n++ )
1307 {
1308 wxFileType *filetype =
1309 wxTheMimeTypesManager->GetFileTypeFromMimeType(mimetypes[n]);
1310 if ( !filetype )
1311 {
1312 printf("nothing known about the filetype '%s'!\n",
1313 mimetypes[n].c_str());
1314 continue;
1315 }
1316
1317 filetype->GetDescription(&desc);
1318 filetype->GetExtensions(exts);
1319
1320 filetype->GetIcon(NULL);
1321
1322 wxString extsAll;
1323 for ( size_t e = 0; e < exts.GetCount(); e++ )
1324 {
1325 if ( e > 0 )
1326 extsAll << _T(", ");
1327 extsAll += exts[e];
1328 }
1329
1330 printf("\t%s: %s (%s)\n",
1331 mimetypes[n].c_str(), desc.c_str(), extsAll.c_str());
1332 }
1333
1334 puts("");
1335 }
1336
1337 static void TestMimeOverride()
1338 {
1339 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1340
1341 static const wxChar *mailcap = _T("/tmp/mailcap");
1342 static const wxChar *mimetypes = _T("/tmp/mime.types");
1343
1344 if ( wxFile::Exists(mailcap) )
1345 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1346 mailcap,
1347 wxTheMimeTypesManager->ReadMailcap(mailcap) ? _T("ok") : _T("ERROR"));
1348 else
1349 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1350 mailcap);
1351
1352 if ( wxFile::Exists(mimetypes) )
1353 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1354 mimetypes,
1355 wxTheMimeTypesManager->ReadMimeTypes(mimetypes) ? _T("ok") : _T("ERROR"));
1356 else
1357 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1358 mimetypes);
1359
1360 puts("");
1361 }
1362
1363 static void TestMimeFilename()
1364 {
1365 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1366
1367 static const wxChar *filenames[] =
1368 {
1369 _T("readme.txt"),
1370 _T("document.pdf"),
1371 _T("image.gif"),
1372 };
1373
1374 for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
1375 {
1376 const wxString fname = filenames[n];
1377 wxString ext = fname.AfterLast(_T('.'));
1378 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
1379 if ( !ft )
1380 {
1381 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext.c_str());
1382 }
1383 else
1384 {
1385 wxString desc;
1386 if ( !ft->GetDescription(&desc) )
1387 desc = _T("<no description>");
1388
1389 wxString cmd;
1390 if ( !ft->GetOpenCommand(&cmd,
1391 wxFileType::MessageParameters(fname, _T(""))) )
1392 cmd = _T("<no command available>");
1393
1394 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1395 fname.c_str(), desc.c_str(), cmd.c_str());
1396
1397 delete ft;
1398 }
1399 }
1400
1401 puts("");
1402 }
1403
1404 static void TestMimeAssociate()
1405 {
1406 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1407
1408 wxFileTypeInfo ftInfo(
1409 _T("application/x-xyz"),
1410 _T("xyzview '%s'"), // open cmd
1411 _T(""), // print cmd
1412 _T("XYZ File") // description
1413 _T(".xyz"), // extensions
1414 NULL // end of extensions
1415 );
1416 ftInfo.SetShortDesc(_T("XYZFile")); // used under Win32 only
1417
1418 wxFileType *ft = wxTheMimeTypesManager->Associate(ftInfo);
1419 if ( !ft )
1420 {
1421 wxPuts(_T("ERROR: failed to create association!"));
1422 }
1423 else
1424 {
1425 // TODO: read it back
1426 delete ft;
1427 }
1428
1429 puts("");
1430 }
1431
1432 #endif // TEST_MIME
1433
1434 // ----------------------------------------------------------------------------
1435 // misc information functions
1436 // ----------------------------------------------------------------------------
1437
1438 #ifdef TEST_INFO_FUNCTIONS
1439
1440 #include "wx/utils.h"
1441
1442 static void TestDiskInfo()
1443 {
1444 puts("*** Testing wxGetDiskSpace() ***");
1445
1446 for ( ;; )
1447 {
1448 char pathname[128];
1449 printf("\nEnter a directory name: ");
1450 if ( !fgets(pathname, WXSIZEOF(pathname), stdin) )
1451 break;
1452
1453 // kill the last '\n'
1454 pathname[strlen(pathname) - 1] = 0;
1455
1456 wxLongLong total, free;
1457 if ( !wxGetDiskSpace(pathname, &total, &free) )
1458 {
1459 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1460 }
1461 else
1462 {
1463 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1464 (total / 1024).ToString().c_str(),
1465 (free / 1024).ToString().c_str(),
1466 pathname);
1467 }
1468 }
1469 }
1470
1471 static void TestOsInfo()
1472 {
1473 puts("*** Testing OS info functions ***\n");
1474
1475 int major, minor;
1476 wxGetOsVersion(&major, &minor);
1477 printf("Running under: %s, version %d.%d\n",
1478 wxGetOsDescription().c_str(), major, minor);
1479
1480 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1481
1482 printf("Host name is %s (%s).\n",
1483 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1484
1485 puts("");
1486 }
1487
1488 static void TestUserInfo()
1489 {
1490 puts("*** Testing user info functions ***\n");
1491
1492 printf("User id is:\t%s\n", wxGetUserId().c_str());
1493 printf("User name is:\t%s\n", wxGetUserName().c_str());
1494 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1495 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1496
1497 puts("");
1498 }
1499
1500 #endif // TEST_INFO_FUNCTIONS
1501
1502 // ----------------------------------------------------------------------------
1503 // long long
1504 // ----------------------------------------------------------------------------
1505
1506 #ifdef TEST_LONGLONG
1507
1508 #include "wx/longlong.h"
1509 #include "wx/timer.h"
1510
1511 // make a 64 bit number from 4 16 bit ones
1512 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1513
1514 // get a random 64 bit number
1515 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1516
1517 static const long testLongs[] =
1518 {
1519 0,
1520 1,
1521 -1,
1522 LONG_MAX,
1523 LONG_MIN,
1524 0x1234,
1525 -0x1234
1526 };
1527
1528 #if wxUSE_LONGLONG_WX
1529 inline bool operator==(const wxLongLongWx& a, const wxLongLongNative& b)
1530 { return a.GetHi() == b.GetHi() && a.GetLo() == b.GetLo(); }
1531 inline bool operator==(const wxLongLongNative& a, const wxLongLongWx& b)
1532 { return a.GetHi() == b.GetHi() && a.GetLo() == b.GetLo(); }
1533 #endif // wxUSE_LONGLONG_WX
1534
1535 static void TestSpeed()
1536 {
1537 static const long max = 100000000;
1538 long n;
1539
1540 {
1541 wxStopWatch sw;
1542
1543 long l = 0;
1544 for ( n = 0; n < max; n++ )
1545 {
1546 l += n;
1547 }
1548
1549 printf("Summing longs took %ld milliseconds.\n", sw.Time());
1550 }
1551
1552 #if wxUSE_LONGLONG_NATIVE
1553 {
1554 wxStopWatch sw;
1555
1556 wxLongLong_t l = 0;
1557 for ( n = 0; n < max; n++ )
1558 {
1559 l += n;
1560 }
1561
1562 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw.Time());
1563 }
1564 #endif // wxUSE_LONGLONG_NATIVE
1565
1566 {
1567 wxStopWatch sw;
1568
1569 wxLongLong l;
1570 for ( n = 0; n < max; n++ )
1571 {
1572 l += n;
1573 }
1574
1575 printf("Summing wxLongLongs took %ld milliseconds.\n", sw.Time());
1576 }
1577 }
1578
1579 static void TestLongLongConversion()
1580 {
1581 puts("*** Testing wxLongLong conversions ***\n");
1582
1583 wxLongLong a;
1584 size_t nTested = 0;
1585 for ( size_t n = 0; n < 100000; n++ )
1586 {
1587 a = RAND_LL();
1588
1589 #if wxUSE_LONGLONG_NATIVE
1590 wxLongLongNative b(a.GetHi(), a.GetLo());
1591
1592 wxASSERT_MSG( a == b, "conversions failure" );
1593 #else
1594 puts("Can't do it without native long long type, test skipped.");
1595
1596 return;
1597 #endif // wxUSE_LONGLONG_NATIVE
1598
1599 if ( !(nTested % 1000) )
1600 {
1601 putchar('.');
1602 fflush(stdout);
1603 }
1604
1605 nTested++;
1606 }
1607
1608 puts(" done!");
1609 }
1610
1611 static void TestMultiplication()
1612 {
1613 puts("*** Testing wxLongLong multiplication ***\n");
1614
1615 wxLongLong a, b;
1616 size_t nTested = 0;
1617 for ( size_t n = 0; n < 100000; n++ )
1618 {
1619 a = RAND_LL();
1620 b = RAND_LL();
1621
1622 #if wxUSE_LONGLONG_NATIVE
1623 wxLongLongNative aa(a.GetHi(), a.GetLo());
1624 wxLongLongNative bb(b.GetHi(), b.GetLo());
1625
1626 wxASSERT_MSG( a*b == aa*bb, "multiplication failure" );
1627 #else // !wxUSE_LONGLONG_NATIVE
1628 puts("Can't do it without native long long type, test skipped.");
1629
1630 return;
1631 #endif // wxUSE_LONGLONG_NATIVE
1632
1633 if ( !(nTested % 1000) )
1634 {
1635 putchar('.');
1636 fflush(stdout);
1637 }
1638
1639 nTested++;
1640 }
1641
1642 puts(" done!");
1643 }
1644
1645 static void TestDivision()
1646 {
1647 puts("*** Testing wxLongLong division ***\n");
1648
1649 wxLongLong q, r;
1650 size_t nTested = 0;
1651 for ( size_t n = 0; n < 100000; n++ )
1652 {
1653 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1654 // multiplication will not overflow)
1655 wxLongLong ll = MAKE_LL((rand() >> 12), rand(), rand(), rand());
1656
1657 // get a random long (not wxLongLong for now) to divide it with
1658 long l = rand();
1659 q = ll / l;
1660 r = ll % l;
1661
1662 #if wxUSE_LONGLONG_NATIVE
1663 wxLongLongNative m(ll.GetHi(), ll.GetLo());
1664
1665 wxLongLongNative p = m / l, s = m % l;
1666 wxASSERT_MSG( q == p && r == s, "division failure" );
1667 #else // !wxUSE_LONGLONG_NATIVE
1668 // verify the result
1669 wxASSERT_MSG( ll == q*l + r, "division failure" );
1670 #endif // wxUSE_LONGLONG_NATIVE
1671
1672 if ( !(nTested % 1000) )
1673 {
1674 putchar('.');
1675 fflush(stdout);
1676 }
1677
1678 nTested++;
1679 }
1680
1681 puts(" done!");
1682 }
1683
1684 static void TestAddition()
1685 {
1686 puts("*** Testing wxLongLong addition ***\n");
1687
1688 wxLongLong a, b, c;
1689 size_t nTested = 0;
1690 for ( size_t n = 0; n < 100000; n++ )
1691 {
1692 a = RAND_LL();
1693 b = RAND_LL();
1694 c = a + b;
1695
1696 #if wxUSE_LONGLONG_NATIVE
1697 wxASSERT_MSG( c == wxLongLongNative(a.GetHi(), a.GetLo()) +
1698 wxLongLongNative(b.GetHi(), b.GetLo()),
1699 "addition failure" );
1700 #else // !wxUSE_LONGLONG_NATIVE
1701 wxASSERT_MSG( c - b == a, "addition failure" );
1702 #endif // wxUSE_LONGLONG_NATIVE
1703
1704 if ( !(nTested % 1000) )
1705 {
1706 putchar('.');
1707 fflush(stdout);
1708 }
1709
1710 nTested++;
1711 }
1712
1713 puts(" done!");
1714 }
1715
1716 static void TestBitOperations()
1717 {
1718 puts("*** Testing wxLongLong bit operation ***\n");
1719
1720 wxLongLong ll;
1721 size_t nTested = 0;
1722 for ( size_t n = 0; n < 100000; n++ )
1723 {
1724 ll = RAND_LL();
1725
1726 #if wxUSE_LONGLONG_NATIVE
1727 for ( size_t n = 0; n < 33; n++ )
1728 {
1729 }
1730 #else // !wxUSE_LONGLONG_NATIVE
1731 puts("Can't do it without native long long type, test skipped.");
1732
1733 return;
1734 #endif // wxUSE_LONGLONG_NATIVE
1735
1736 if ( !(nTested % 1000) )
1737 {
1738 putchar('.');
1739 fflush(stdout);
1740 }
1741
1742 nTested++;
1743 }
1744
1745 puts(" done!");
1746 }
1747
1748 static void TestLongLongComparison()
1749 {
1750 #if wxUSE_LONGLONG_WX
1751 puts("*** Testing wxLongLong comparison ***\n");
1752
1753 static const long ls[2] =
1754 {
1755 0x1234,
1756 -0x1234,
1757 };
1758
1759 wxLongLongWx lls[2];
1760 lls[0] = ls[0];
1761 lls[1] = ls[1];
1762
1763 for ( size_t n = 0; n < WXSIZEOF(testLongs); n++ )
1764 {
1765 bool res;
1766
1767 for ( size_t m = 0; m < WXSIZEOF(lls); m++ )
1768 {
1769 res = lls[m] > testLongs[n];
1770 printf("0x%lx > 0x%lx is %s (%s)\n",
1771 ls[m], testLongs[n], res ? "true" : "false",
1772 res == (ls[m] > testLongs[n]) ? "ok" : "ERROR");
1773
1774 res = lls[m] < testLongs[n];
1775 printf("0x%lx < 0x%lx is %s (%s)\n",
1776 ls[m], testLongs[n], res ? "true" : "false",
1777 res == (ls[m] < testLongs[n]) ? "ok" : "ERROR");
1778
1779 res = lls[m] == testLongs[n];
1780 printf("0x%lx == 0x%lx is %s (%s)\n",
1781 ls[m], testLongs[n], res ? "true" : "false",
1782 res == (ls[m] == testLongs[n]) ? "ok" : "ERROR");
1783 }
1784 }
1785 #endif // wxUSE_LONGLONG_WX
1786 }
1787
1788 static void TestLongLongPrint()
1789 {
1790 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
1791
1792 for ( size_t n = 0; n < WXSIZEOF(testLongs); n++ )
1793 {
1794 wxLongLong ll = testLongs[n];
1795 wxPrintf(_T("%ld == %s\n"), testLongs[n], ll.ToString().c_str());
1796 }
1797
1798 wxLongLong ll(0x12345678, 0x87654321);
1799 wxPrintf(_T("0x1234567887654321 = %s\n"), ll.ToString().c_str());
1800
1801 ll.Negate();
1802 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll.ToString().c_str());
1803 }
1804
1805 #undef MAKE_LL
1806 #undef RAND_LL
1807
1808 #endif // TEST_LONGLONG
1809
1810 // ----------------------------------------------------------------------------
1811 // path list
1812 // ----------------------------------------------------------------------------
1813
1814 #ifdef TEST_PATHLIST
1815
1816 static void TestPathList()
1817 {
1818 puts("*** Testing wxPathList ***\n");
1819
1820 wxPathList pathlist;
1821 pathlist.AddEnvList("PATH");
1822 wxString path = pathlist.FindValidPath("ls");
1823 if ( path.empty() )
1824 {
1825 printf("ERROR: command not found in the path.\n");
1826 }
1827 else
1828 {
1829 printf("Command found in the path as '%s'.\n", path.c_str());
1830 }
1831 }
1832
1833 #endif // TEST_PATHLIST
1834
1835 // ----------------------------------------------------------------------------
1836 // regular expressions
1837 // ----------------------------------------------------------------------------
1838
1839 #ifdef TEST_REGEX
1840
1841 #include "wx/regex.h"
1842
1843 static void TestRegExCompile()
1844 {
1845 wxPuts(_T("*** Testing RE compilation ***\n"));
1846
1847 static struct RegExCompTestData
1848 {
1849 const wxChar *pattern;
1850 bool correct;
1851 } regExCompTestData[] =
1852 {
1853 { _T("foo"), TRUE },
1854 { _T("foo("), FALSE },
1855 { _T("foo(bar"), FALSE },
1856 { _T("foo(bar)"), TRUE },
1857 { _T("foo["), FALSE },
1858 { _T("foo[bar"), FALSE },
1859 { _T("foo[bar]"), TRUE },
1860 { _T("foo{"), TRUE },
1861 { _T("foo{1"), FALSE },
1862 { _T("foo{bar"), TRUE },
1863 { _T("foo{1}"), TRUE },
1864 { _T("foo{1,2}"), TRUE },
1865 { _T("foo{bar}"), TRUE },
1866 { _T("foo*"), TRUE },
1867 { _T("foo**"), FALSE },
1868 { _T("foo+"), TRUE },
1869 { _T("foo++"), FALSE },
1870 { _T("foo?"), TRUE },
1871 { _T("foo??"), FALSE },
1872 { _T("foo?+"), FALSE },
1873 };
1874
1875 wxRegEx re;
1876 for ( size_t n = 0; n < WXSIZEOF(regExCompTestData); n++ )
1877 {
1878 const RegExCompTestData& data = regExCompTestData[n];
1879 bool ok = re.Compile(data.pattern);
1880
1881 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
1882 data.pattern,
1883 ok ? _T("") : _T("not "),
1884 ok == data.correct ? _T("ok") : _T("ERROR"));
1885 }
1886 }
1887
1888 static void TestRegExMatch()
1889 {
1890 wxPuts(_T("*** Testing RE matching ***\n"));
1891
1892 static struct RegExMatchTestData
1893 {
1894 const wxChar *pattern;
1895 const wxChar *text;
1896 bool correct;
1897 } regExMatchTestData[] =
1898 {
1899 { _T("foo"), _T("bar"), FALSE },
1900 { _T("foo"), _T("foobar"), TRUE },
1901 { _T("^foo"), _T("foobar"), TRUE },
1902 { _T("^foo"), _T("barfoo"), FALSE },
1903 { _T("bar$"), _T("barbar"), TRUE },
1904 { _T("bar$"), _T("barbar "), FALSE },
1905 };
1906
1907 for ( size_t n = 0; n < WXSIZEOF(regExMatchTestData); n++ )
1908 {
1909 const RegExMatchTestData& data = regExMatchTestData[n];
1910
1911 wxRegEx re(data.pattern);
1912 bool ok = re.Matches(data.text);
1913
1914 wxPrintf(_T("'%s' %s %s (%s)\n"),
1915 data.pattern,
1916 ok ? _T("matches") : _T("doesn't match"),
1917 data.text,
1918 ok == data.correct ? _T("ok") : _T("ERROR"));
1919 }
1920 }
1921
1922 static void TestRegExSubmatch()
1923 {
1924 wxPuts(_T("*** Testing RE subexpressions ***\n"));
1925
1926 wxRegEx re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
1927 if ( !re.IsValid() )
1928 {
1929 wxPuts(_T("ERROR: compilation failed."));
1930 return;
1931 }
1932
1933 wxString text = _T("Fri Jul 13 18:37:52 CEST 2001");
1934
1935 if ( !re.Matches(text) )
1936 {
1937 wxPuts(_T("ERROR: match expected."));
1938 }
1939 else
1940 {
1941 wxPrintf(_T("Entire match: %s\n"), re.GetMatch(text).c_str());
1942
1943 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
1944 re.GetMatch(text, 3).c_str(),
1945 re.GetMatch(text, 2).c_str(),
1946 re.GetMatch(text, 4).c_str(),
1947 re.GetMatch(text, 1).c_str());
1948 }
1949 }
1950
1951 static void TestRegExReplacement()
1952 {
1953 wxPuts(_T("*** Testing RE replacement ***"));
1954
1955 static struct RegExReplTestData
1956 {
1957 const wxChar *text;
1958 const wxChar *repl;
1959 const wxChar *result;
1960 size_t count;
1961 } regExReplTestData[] =
1962 {
1963 { _T("foo123"), _T("bar"), _T("bar"), 1 },
1964 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
1965 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
1966 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
1967 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
1968 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
1969 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
1970 };
1971
1972 const wxChar *pattern = _T("([a-z]+)[^0-9]*([0-9]+)");
1973 wxRegEx re = pattern;
1974
1975 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern);
1976
1977 for ( size_t n = 0; n < WXSIZEOF(regExReplTestData); n++ )
1978 {
1979 const RegExReplTestData& data = regExReplTestData[n];
1980
1981 wxString text = data.text;
1982 size_t nRepl = re.Replace(&text, data.repl);
1983
1984 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
1985 data.text, data.repl,
1986 nRepl, nRepl == 1 ? _T("") : _T("es"),
1987 text.c_str());
1988 if ( text == data.result && nRepl == data.count )
1989 {
1990 wxPuts(_T("ok)"));
1991 }
1992 else
1993 {
1994 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
1995 data.count, data.result);
1996 }
1997 }
1998 }
1999
2000 static void TestRegExInteractive()
2001 {
2002 wxPuts(_T("*** Testing RE interactively ***"));
2003
2004 for ( ;; )
2005 {
2006 char pattern[128];
2007 printf("\nEnter a pattern: ");
2008 if ( !fgets(pattern, WXSIZEOF(pattern), stdin) )
2009 break;
2010
2011 // kill the last '\n'
2012 pattern[strlen(pattern) - 1] = 0;
2013
2014 wxRegEx re;
2015 if ( !re.Compile(pattern) )
2016 {
2017 continue;
2018 }
2019
2020 char text[128];
2021 for ( ;; )
2022 {
2023 printf("Enter text to match: ");
2024 if ( !fgets(text, WXSIZEOF(text), stdin) )
2025 break;
2026
2027 // kill the last '\n'
2028 text[strlen(text) - 1] = 0;
2029
2030 if ( !re.Matches(text) )
2031 {
2032 printf("No match.\n");
2033 }
2034 else
2035 {
2036 printf("Pattern matches at '%s'\n", re.GetMatch(text).c_str());
2037
2038 size_t start, len;
2039 for ( size_t n = 1; ; n++ )
2040 {
2041 if ( !re.GetMatch(&start, &len, n) )
2042 {
2043 break;
2044 }
2045
2046 printf("Subexpr %u matched '%s'\n",
2047 n, wxString(text + start, len).c_str());
2048 }
2049 }
2050 }
2051 }
2052 }
2053
2054 #endif // TEST_REGEX
2055
2056 // ----------------------------------------------------------------------------
2057 // registry and related stuff
2058 // ----------------------------------------------------------------------------
2059
2060 // this is for MSW only
2061 #ifndef __WXMSW__
2062 #undef TEST_REGCONF
2063 #undef TEST_REGISTRY
2064 #endif
2065
2066 #ifdef TEST_REGCONF
2067
2068 #include "wx/confbase.h"
2069 #include "wx/msw/regconf.h"
2070
2071 static void TestRegConfWrite()
2072 {
2073 wxRegConfig regconf(_T("console"), _T("wxwindows"));
2074 regconf.Write(_T("Hello"), wxString(_T("world")));
2075 }
2076
2077 #endif // TEST_REGCONF
2078
2079 #ifdef TEST_REGISTRY
2080
2081 #include "wx/msw/registry.h"
2082
2083 // I chose this one because I liked its name, but it probably only exists under
2084 // NT
2085 static const wxChar *TESTKEY =
2086 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2087
2088 static void TestRegistryRead()
2089 {
2090 puts("*** testing registry reading ***");
2091
2092 wxRegKey key(TESTKEY);
2093 printf("The test key name is '%s'.\n", key.GetName().c_str());
2094 if ( !key.Open() )
2095 {
2096 puts("ERROR: test key can't be opened, aborting test.");
2097
2098 return;
2099 }
2100
2101 size_t nSubKeys, nValues;
2102 if ( key.GetKeyInfo(&nSubKeys, NULL, &nValues, NULL) )
2103 {
2104 printf("It has %u subkeys and %u values.\n", nSubKeys, nValues);
2105 }
2106
2107 printf("Enumerating values:\n");
2108
2109 long dummy;
2110 wxString value;
2111 bool cont = key.GetFirstValue(value, dummy);
2112 while ( cont )
2113 {
2114 printf("Value '%s': type ", value.c_str());
2115 switch ( key.GetValueType(value) )
2116 {
2117 case wxRegKey::Type_None: printf("ERROR (none)"); break;
2118 case wxRegKey::Type_String: printf("SZ"); break;
2119 case wxRegKey::Type_Expand_String: printf("EXPAND_SZ"); break;
2120 case wxRegKey::Type_Binary: printf("BINARY"); break;
2121 case wxRegKey::Type_Dword: printf("DWORD"); break;
2122 case wxRegKey::Type_Multi_String: printf("MULTI_SZ"); break;
2123 default: printf("other (unknown)"); break;
2124 }
2125
2126 printf(", value = ");
2127 if ( key.IsNumericValue(value) )
2128 {
2129 long val;
2130 key.QueryValue(value, &val);
2131 printf("%ld", val);
2132 }
2133 else // string
2134 {
2135 wxString val;
2136 key.QueryValue(value, val);
2137 printf("'%s'", val.c_str());
2138
2139 key.QueryRawValue(value, val);
2140 printf(" (raw value '%s')", val.c_str());
2141 }
2142
2143 putchar('\n');
2144
2145 cont = key.GetNextValue(value, dummy);
2146 }
2147 }
2148
2149 static void TestRegistryAssociation()
2150 {
2151 /*
2152 The second call to deleteself genertaes an error message, with a
2153 messagebox saying .flo is crucial to system operation, while the .ddf
2154 call also fails, but with no error message
2155 */
2156
2157 wxRegKey key;
2158
2159 key.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2160 key.Create();
2161 key = "ddxf_auto_file" ;
2162 key.SetName("HKEY_CLASSES_ROOT\\.flo" );
2163 key.Create();
2164 key = "ddxf_auto_file" ;
2165 key.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2166 key.Create();
2167 key = "program,0" ;
2168 key.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2169 key.Create();
2170 key = "program \"%1\"" ;
2171
2172 key.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2173 key.DeleteSelf();
2174 key.SetName("HKEY_CLASSES_ROOT\\.flo" );
2175 key.DeleteSelf();
2176 key.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2177 key.DeleteSelf();
2178 key.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2179 key.DeleteSelf();
2180 }
2181
2182 #endif // TEST_REGISTRY
2183
2184 // ----------------------------------------------------------------------------
2185 // sockets
2186 // ----------------------------------------------------------------------------
2187
2188 #ifdef TEST_SOCKETS
2189
2190 #include "wx/socket.h"
2191 #include "wx/protocol/protocol.h"
2192 #include "wx/protocol/http.h"
2193
2194 static void TestSocketServer()
2195 {
2196 puts("*** Testing wxSocketServer ***\n");
2197
2198 static const int PORT = 3000;
2199
2200 wxIPV4address addr;
2201 addr.Service(PORT);
2202
2203 wxSocketServer *server = new wxSocketServer(addr);
2204 if ( !server->Ok() )
2205 {
2206 puts("ERROR: failed to bind");
2207
2208 return;
2209 }
2210
2211 for ( ;; )
2212 {
2213 printf("Server: waiting for connection on port %d...\n", PORT);
2214
2215 wxSocketBase *socket = server->Accept();
2216 if ( !socket )
2217 {
2218 puts("ERROR: wxSocketServer::Accept() failed.");
2219 break;
2220 }
2221
2222 puts("Server: got a client.");
2223
2224 server->SetTimeout(60); // 1 min
2225
2226 while ( socket->IsConnected() )
2227 {
2228 wxString s;
2229 char ch = '\0';
2230 for ( ;; )
2231 {
2232 if ( socket->Read(&ch, sizeof(ch)).Error() )
2233 {
2234 // don't log error if the client just close the connection
2235 if ( socket->IsConnected() )
2236 {
2237 puts("ERROR: in wxSocket::Read.");
2238 }
2239
2240 break;
2241 }
2242
2243 if ( ch == '\r' )
2244 continue;
2245
2246 if ( ch == '\n' )
2247 break;
2248
2249 s += ch;
2250 }
2251
2252 if ( ch != '\n' )
2253 {
2254 break;
2255 }
2256
2257 printf("Server: got '%s'.\n", s.c_str());
2258 if ( s == _T("bye") )
2259 {
2260 delete socket;
2261
2262 break;
2263 }
2264
2265 socket->Write(s.MakeUpper().c_str(), s.length());
2266 socket->Write("\r\n", 2);
2267 printf("Server: wrote '%s'.\n", s.c_str());
2268 }
2269
2270 puts("Server: lost a client.");
2271
2272 socket->Destroy();
2273 }
2274
2275 // same as "delete server" but is consistent with GUI programs
2276 server->Destroy();
2277 }
2278
2279 static void TestSocketClient()
2280 {
2281 puts("*** Testing wxSocketClient ***\n");
2282
2283 static const char *hostname = "www.wxwindows.org";
2284
2285 wxIPV4address addr;
2286 addr.Hostname(hostname);
2287 addr.Service(80);
2288
2289 printf("--- Attempting to connect to %s:80...\n", hostname);
2290
2291 wxSocketClient client;
2292 if ( !client.Connect(addr) )
2293 {
2294 printf("ERROR: failed to connect to %s\n", hostname);
2295 }
2296 else
2297 {
2298 printf("--- Connected to %s:%u...\n",
2299 addr.Hostname().c_str(), addr.Service());
2300
2301 char buf[8192];
2302
2303 // could use simply "GET" here I suppose
2304 wxString cmdGet =
2305 wxString::Format("GET http://%s/\r\n", hostname);
2306 client.Write(cmdGet, cmdGet.length());
2307 printf("--- Sent command '%s' to the server\n",
2308 MakePrintable(cmdGet).c_str());
2309 client.Read(buf, WXSIZEOF(buf));
2310 printf("--- Server replied:\n%s", buf);
2311 }
2312 }
2313
2314 #endif // TEST_SOCKETS
2315
2316 // ----------------------------------------------------------------------------
2317 // FTP
2318 // ----------------------------------------------------------------------------
2319
2320 #ifdef TEST_FTP
2321
2322 #include "wx/protocol/ftp.h"
2323
2324 static wxFTP ftp;
2325
2326 #define FTP_ANONYMOUS
2327
2328 #ifdef FTP_ANONYMOUS
2329 static const char *directory = "/pub";
2330 static const char *filename = "welcome.msg";
2331 #else
2332 static const char *directory = "/etc";
2333 static const char *filename = "issue";
2334 #endif
2335
2336 static bool TestFtpConnect()
2337 {
2338 puts("*** Testing FTP connect ***");
2339
2340 #ifdef FTP_ANONYMOUS
2341 static const char *hostname = "ftp.wxwindows.org";
2342
2343 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname);
2344 #else // !FTP_ANONYMOUS
2345 static const char *hostname = "localhost";
2346
2347 char user[256];
2348 fgets(user, WXSIZEOF(user), stdin);
2349 user[strlen(user) - 1] = '\0'; // chop off '\n'
2350 ftp.SetUser(user);
2351
2352 char password[256];
2353 printf("Password for %s: ", password);
2354 fgets(password, WXSIZEOF(password), stdin);
2355 password[strlen(password) - 1] = '\0'; // chop off '\n'
2356 ftp.SetPassword(password);
2357
2358 printf("--- Attempting to connect to %s:21 as %s...\n", hostname, user);
2359 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2360
2361 if ( !ftp.Connect(hostname) )
2362 {
2363 printf("ERROR: failed to connect to %s\n", hostname);
2364
2365 return FALSE;
2366 }
2367 else
2368 {
2369 printf("--- Connected to %s, current directory is '%s'\n",
2370 hostname, ftp.Pwd().c_str());
2371 }
2372
2373 return TRUE;
2374 }
2375
2376 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2377 static void TestFtpWuFtpd()
2378 {
2379 wxFTP ftp;
2380 static const char *hostname = "ftp.eudora.com";
2381 if ( !ftp.Connect(hostname) )
2382 {
2383 printf("ERROR: failed to connect to %s\n", hostname);
2384 }
2385 else
2386 {
2387 static const char *filename = "eudora/pubs/draft-gellens-submit-09.txt";
2388 wxInputStream *in = ftp.GetInputStream(filename);
2389 if ( !in )
2390 {
2391 printf("ERROR: couldn't get input stream for %s\n", filename);
2392 }
2393 else
2394 {
2395 size_t size = in->StreamSize();
2396 printf("Reading file %s (%u bytes)...", filename, size);
2397
2398 char *data = new char[size];
2399 if ( !in->Read(data, size) )
2400 {
2401 puts("ERROR: read error");
2402 }
2403 else
2404 {
2405 printf("Successfully retrieved the file.\n");
2406 }
2407
2408 delete [] data;
2409 delete in;
2410 }
2411 }
2412 }
2413
2414 static void TestFtpList()
2415 {
2416 puts("*** Testing wxFTP file listing ***\n");
2417
2418 // test CWD
2419 if ( !ftp.ChDir(directory) )
2420 {
2421 printf("ERROR: failed to cd to %s\n", directory);
2422 }
2423
2424 printf("Current directory is '%s'\n", ftp.Pwd().c_str());
2425
2426 // test NLIST and LIST
2427 wxArrayString files;
2428 if ( !ftp.GetFilesList(files) )
2429 {
2430 puts("ERROR: failed to get NLIST of files");
2431 }
2432 else
2433 {
2434 printf("Brief list of files under '%s':\n", ftp.Pwd().c_str());
2435 size_t count = files.GetCount();
2436 for ( size_t n = 0; n < count; n++ )
2437 {
2438 printf("\t%s\n", files[n].c_str());
2439 }
2440 puts("End of the file list");
2441 }
2442
2443 if ( !ftp.GetDirList(files) )
2444 {
2445 puts("ERROR: failed to get LIST of files");
2446 }
2447 else
2448 {
2449 printf("Detailed list of files under '%s':\n", ftp.Pwd().c_str());
2450 size_t count = files.GetCount();
2451 for ( size_t n = 0; n < count; n++ )
2452 {
2453 printf("\t%s\n", files[n].c_str());
2454 }
2455 puts("End of the file list");
2456 }
2457
2458 if ( !ftp.ChDir(_T("..")) )
2459 {
2460 puts("ERROR: failed to cd to ..");
2461 }
2462
2463 printf("Current directory is '%s'\n", ftp.Pwd().c_str());
2464 }
2465
2466 static void TestFtpDownload()
2467 {
2468 puts("*** Testing wxFTP download ***\n");
2469
2470 // test RETR
2471 wxInputStream *in = ftp.GetInputStream(filename);
2472 if ( !in )
2473 {
2474 printf("ERROR: couldn't get input stream for %s\n", filename);
2475 }
2476 else
2477 {
2478 size_t size = in->StreamSize();
2479 printf("Reading file %s (%u bytes)...", filename, size);
2480 fflush(stdout);
2481
2482 char *data = new char[size];
2483 if ( !in->Read(data, size) )
2484 {
2485 puts("ERROR: read error");
2486 }
2487 else
2488 {
2489 printf("\nContents of %s:\n%s\n", filename, data);
2490 }
2491
2492 delete [] data;
2493 delete in;
2494 }
2495 }
2496
2497 static void TestFtpFileSize()
2498 {
2499 puts("*** Testing FTP SIZE command ***");
2500
2501 if ( !ftp.ChDir(directory) )
2502 {
2503 printf("ERROR: failed to cd to %s\n", directory);
2504 }
2505
2506 printf("Current directory is '%s'\n", ftp.Pwd().c_str());
2507
2508 if ( ftp.FileExists(filename) )
2509 {
2510 int size = ftp.GetFileSize(filename);
2511 if ( size == -1 )
2512 printf("ERROR: couldn't get size of '%s'\n", filename);
2513 else
2514 printf("Size of '%s' is %d bytes.\n", filename, size);
2515 }
2516 else
2517 {
2518 printf("ERROR: '%s' doesn't exist\n", filename);
2519 }
2520 }
2521
2522 static void TestFtpMisc()
2523 {
2524 puts("*** Testing miscellaneous wxFTP functions ***");
2525
2526 if ( ftp.SendCommand("STAT") != '2' )
2527 {
2528 puts("ERROR: STAT failed");
2529 }
2530 else
2531 {
2532 printf("STAT returned:\n\n%s\n", ftp.GetLastResult().c_str());
2533 }
2534
2535 if ( ftp.SendCommand("HELP SITE") != '2' )
2536 {
2537 puts("ERROR: HELP SITE failed");
2538 }
2539 else
2540 {
2541 printf("The list of site-specific commands:\n\n%s\n",
2542 ftp.GetLastResult().c_str());
2543 }
2544 }
2545
2546 static void TestFtpInteractive()
2547 {
2548 puts("\n*** Interactive wxFTP test ***");
2549
2550 char buf[128];
2551
2552 for ( ;; )
2553 {
2554 printf("Enter FTP command: ");
2555 if ( !fgets(buf, WXSIZEOF(buf), stdin) )
2556 break;
2557
2558 // kill the last '\n'
2559 buf[strlen(buf) - 1] = 0;
2560
2561 // special handling of LIST and NLST as they require data connection
2562 wxString start(buf, 4);
2563 start.MakeUpper();
2564 if ( start == "LIST" || start == "NLST" )
2565 {
2566 wxString wildcard;
2567 if ( strlen(buf) > 4 )
2568 wildcard = buf + 5;
2569
2570 wxArrayString files;
2571 if ( !ftp.GetList(files, wildcard, start == "LIST") )
2572 {
2573 printf("ERROR: failed to get %s of files\n", start.c_str());
2574 }
2575 else
2576 {
2577 printf("--- %s of '%s' under '%s':\n",
2578 start.c_str(), wildcard.c_str(), ftp.Pwd().c_str());
2579 size_t count = files.GetCount();
2580 for ( size_t n = 0; n < count; n++ )
2581 {
2582 printf("\t%s\n", files[n].c_str());
2583 }
2584 puts("--- End of the file list");
2585 }
2586 }
2587 else // !list
2588 {
2589 char ch = ftp.SendCommand(buf);
2590 printf("Command %s", ch ? "succeeded" : "failed");
2591 if ( ch )
2592 {
2593 printf(" (return code %c)", ch);
2594 }
2595
2596 printf(", server reply:\n%s\n\n", ftp.GetLastResult().c_str());
2597 }
2598 }
2599
2600 puts("\n*** done ***");
2601 }
2602
2603 static void TestFtpUpload()
2604 {
2605 puts("*** Testing wxFTP uploading ***\n");
2606
2607 // upload a file
2608 static const char *file1 = "test1";
2609 static const char *file2 = "test2";
2610 wxOutputStream *out = ftp.GetOutputStream(file1);
2611 if ( out )
2612 {
2613 printf("--- Uploading to %s ---\n", file1);
2614 out->Write("First hello", 11);
2615 delete out;
2616 }
2617
2618 // send a command to check the remote file
2619 if ( ftp.SendCommand(wxString("STAT ") + file1) != '2' )
2620 {
2621 printf("ERROR: STAT %s failed\n", file1);
2622 }
2623 else
2624 {
2625 printf("STAT %s returned:\n\n%s\n",
2626 file1, ftp.GetLastResult().c_str());
2627 }
2628
2629 out = ftp.GetOutputStream(file2);
2630 if ( out )
2631 {
2632 printf("--- Uploading to %s ---\n", file1);
2633 out->Write("Second hello", 12);
2634 delete out;
2635 }
2636 }
2637
2638 #endif // TEST_FTP
2639
2640 // ----------------------------------------------------------------------------
2641 // streams
2642 // ----------------------------------------------------------------------------
2643
2644 #ifdef TEST_STREAMS
2645
2646 #include "wx/wfstream.h"
2647 #include "wx/mstream.h"
2648
2649 static void TestFileStream()
2650 {
2651 puts("*** Testing wxFileInputStream ***");
2652
2653 static const wxChar *filename = _T("testdata.fs");
2654 {
2655 wxFileOutputStream fsOut(filename);
2656 fsOut.Write("foo", 3);
2657 }
2658
2659 wxFileInputStream fsIn(filename);
2660 printf("File stream size: %u\n", fsIn.GetSize());
2661 while ( !fsIn.Eof() )
2662 {
2663 putchar(fsIn.GetC());
2664 }
2665
2666 if ( !wxRemoveFile(filename) )
2667 {
2668 printf("ERROR: failed to remove the file '%s'.\n", filename);
2669 }
2670
2671 puts("\n*** wxFileInputStream test done ***");
2672 }
2673
2674 static void TestMemoryStream()
2675 {
2676 puts("*** Testing wxMemoryInputStream ***");
2677
2678 wxChar buf[1024];
2679 wxStrncpy(buf, _T("Hello, stream!"), WXSIZEOF(buf));
2680
2681 wxMemoryInputStream memInpStream(buf, wxStrlen(buf));
2682 printf(_T("Memory stream size: %u\n"), memInpStream.GetSize());
2683 while ( !memInpStream.Eof() )
2684 {
2685 putchar(memInpStream.GetC());
2686 }
2687
2688 puts("\n*** wxMemoryInputStream test done ***");
2689 }
2690
2691 #endif // TEST_STREAMS
2692
2693 // ----------------------------------------------------------------------------
2694 // timers
2695 // ----------------------------------------------------------------------------
2696
2697 #ifdef TEST_TIMER
2698
2699 #include "wx/timer.h"
2700 #include "wx/utils.h"
2701
2702 static void TestStopWatch()
2703 {
2704 puts("*** Testing wxStopWatch ***\n");
2705
2706 wxStopWatch sw;
2707 printf("Sleeping 3 seconds...");
2708 wxSleep(3);
2709 printf("\telapsed time: %ldms\n", sw.Time());
2710
2711 sw.Pause();
2712 printf("Sleeping 2 more seconds...");
2713 wxSleep(2);
2714 printf("\telapsed time: %ldms\n", sw.Time());
2715
2716 sw.Resume();
2717 printf("And 3 more seconds...");
2718 wxSleep(3);
2719 printf("\telapsed time: %ldms\n", sw.Time());
2720
2721 wxStopWatch sw2;
2722 puts("\nChecking for 'backwards clock' bug...");
2723 for ( size_t n = 0; n < 70; n++ )
2724 {
2725 sw2.Start();
2726
2727 for ( size_t m = 0; m < 100000; m++ )
2728 {
2729 if ( sw.Time() < 0 || sw2.Time() < 0 )
2730 {
2731 puts("\ntime is negative - ERROR!");
2732 }
2733 }
2734
2735 putchar('.');
2736 }
2737
2738 puts(", ok.");
2739 }
2740
2741 #endif // TEST_TIMER
2742
2743 // ----------------------------------------------------------------------------
2744 // vCard support
2745 // ----------------------------------------------------------------------------
2746
2747 #ifdef TEST_VCARD
2748
2749 #include "wx/vcard.h"
2750
2751 static void DumpVObject(size_t level, const wxVCardObject& vcard)
2752 {
2753 void *cookie;
2754 wxVCardObject *vcObj = vcard.GetFirstProp(&cookie);
2755 while ( vcObj )
2756 {
2757 printf("%s%s",
2758 wxString(_T('\t'), level).c_str(),
2759 vcObj->GetName().c_str());
2760
2761 wxString value;
2762 switch ( vcObj->GetType() )
2763 {
2764 case wxVCardObject::String:
2765 case wxVCardObject::UString:
2766 {
2767 wxString val;
2768 vcObj->GetValue(&val);
2769 value << _T('"') << val << _T('"');
2770 }
2771 break;
2772
2773 case wxVCardObject::Int:
2774 {
2775 unsigned int i;
2776 vcObj->GetValue(&i);
2777 value.Printf(_T("%u"), i);
2778 }
2779 break;
2780
2781 case wxVCardObject::Long:
2782 {
2783 unsigned long l;
2784 vcObj->GetValue(&l);
2785 value.Printf(_T("%lu"), l);
2786 }
2787 break;
2788
2789 case wxVCardObject::None:
2790 break;
2791
2792 case wxVCardObject::Object:
2793 value = _T("<node>");
2794 break;
2795
2796 default:
2797 value = _T("<unknown value type>");
2798 }
2799
2800 if ( !!value )
2801 printf(" = %s", value.c_str());
2802 putchar('\n');
2803
2804 DumpVObject(level + 1, *vcObj);
2805
2806 delete vcObj;
2807 vcObj = vcard.GetNextProp(&cookie);
2808 }
2809 }
2810
2811 static void DumpVCardAddresses(const wxVCard& vcard)
2812 {
2813 puts("\nShowing all addresses from vCard:\n");
2814
2815 size_t nAdr = 0;
2816 void *cookie;
2817 wxVCardAddress *addr = vcard.GetFirstAddress(&cookie);
2818 while ( addr )
2819 {
2820 wxString flagsStr;
2821 int flags = addr->GetFlags();
2822 if ( flags & wxVCardAddress::Domestic )
2823 {
2824 flagsStr << _T("domestic ");
2825 }
2826 if ( flags & wxVCardAddress::Intl )
2827 {
2828 flagsStr << _T("international ");
2829 }
2830 if ( flags & wxVCardAddress::Postal )
2831 {
2832 flagsStr << _T("postal ");
2833 }
2834 if ( flags & wxVCardAddress::Parcel )
2835 {
2836 flagsStr << _T("parcel ");
2837 }
2838 if ( flags & wxVCardAddress::Home )
2839 {
2840 flagsStr << _T("home ");
2841 }
2842 if ( flags & wxVCardAddress::Work )
2843 {
2844 flagsStr << _T("work ");
2845 }
2846
2847 printf("Address %u:\n"
2848 "\tflags = %s\n"
2849 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2850 ++nAdr,
2851 flagsStr.c_str(),
2852 addr->GetPostOffice().c_str(),
2853 addr->GetExtAddress().c_str(),
2854 addr->GetStreet().c_str(),
2855 addr->GetLocality().c_str(),
2856 addr->GetRegion().c_str(),
2857 addr->GetPostalCode().c_str(),
2858 addr->GetCountry().c_str()
2859 );
2860
2861 delete addr;
2862 addr = vcard.GetNextAddress(&cookie);
2863 }
2864 }
2865
2866 static void DumpVCardPhoneNumbers(const wxVCard& vcard)
2867 {
2868 puts("\nShowing all phone numbers from vCard:\n");
2869
2870 size_t nPhone = 0;
2871 void *cookie;
2872 wxVCardPhoneNumber *phone = vcard.GetFirstPhoneNumber(&cookie);
2873 while ( phone )
2874 {
2875 wxString flagsStr;
2876 int flags = phone->GetFlags();
2877 if ( flags & wxVCardPhoneNumber::Voice )
2878 {
2879 flagsStr << _T("voice ");
2880 }
2881 if ( flags & wxVCardPhoneNumber::Fax )
2882 {
2883 flagsStr << _T("fax ");
2884 }
2885 if ( flags & wxVCardPhoneNumber::Cellular )
2886 {
2887 flagsStr << _T("cellular ");
2888 }
2889 if ( flags & wxVCardPhoneNumber::Modem )
2890 {
2891 flagsStr << _T("modem ");
2892 }
2893 if ( flags & wxVCardPhoneNumber::Home )
2894 {
2895 flagsStr << _T("home ");
2896 }
2897 if ( flags & wxVCardPhoneNumber::Work )
2898 {
2899 flagsStr << _T("work ");
2900 }
2901
2902 printf("Phone number %u:\n"
2903 "\tflags = %s\n"
2904 "\tvalue = %s\n",
2905 ++nPhone,
2906 flagsStr.c_str(),
2907 phone->GetNumber().c_str()
2908 );
2909
2910 delete phone;
2911 phone = vcard.GetNextPhoneNumber(&cookie);
2912 }
2913 }
2914
2915 static void TestVCardRead()
2916 {
2917 puts("*** Testing wxVCard reading ***\n");
2918
2919 wxVCard vcard(_T("vcard.vcf"));
2920 if ( !vcard.IsOk() )
2921 {
2922 puts("ERROR: couldn't load vCard.");
2923 }
2924 else
2925 {
2926 // read individual vCard properties
2927 wxVCardObject *vcObj = vcard.GetProperty("FN");
2928 wxString value;
2929 if ( vcObj )
2930 {
2931 vcObj->GetValue(&value);
2932 delete vcObj;
2933 }
2934 else
2935 {
2936 value = _T("<none>");
2937 }
2938
2939 printf("Full name retrieved directly: %s\n", value.c_str());
2940
2941
2942 if ( !vcard.GetFullName(&value) )
2943 {
2944 value = _T("<none>");
2945 }
2946
2947 printf("Full name from wxVCard API: %s\n", value.c_str());
2948
2949 // now show how to deal with multiply occuring properties
2950 DumpVCardAddresses(vcard);
2951 DumpVCardPhoneNumbers(vcard);
2952
2953 // and finally show all
2954 puts("\nNow dumping the entire vCard:\n"
2955 "-----------------------------\n");
2956
2957 DumpVObject(0, vcard);
2958 }
2959 }
2960
2961 static void TestVCardWrite()
2962 {
2963 puts("*** Testing wxVCard writing ***\n");
2964
2965 wxVCard vcard;
2966 if ( !vcard.IsOk() )
2967 {
2968 puts("ERROR: couldn't create vCard.");
2969 }
2970 else
2971 {
2972 // set some fields
2973 vcard.SetName("Zeitlin", "Vadim");
2974 vcard.SetFullName("Vadim Zeitlin");
2975 vcard.SetOrganization("wxWindows", "R&D");
2976
2977 // just dump the vCard back
2978 puts("Entire vCard follows:\n");
2979 puts(vcard.Write());
2980 }
2981 }
2982
2983 #endif // TEST_VCARD
2984
2985 // ----------------------------------------------------------------------------
2986 // wide char (Unicode) support
2987 // ----------------------------------------------------------------------------
2988
2989 #ifdef TEST_WCHAR
2990
2991 #include "wx/strconv.h"
2992 #include "wx/fontenc.h"
2993 #include "wx/encconv.h"
2994 #include "wx/buffer.h"
2995
2996 static void TestUtf8()
2997 {
2998 puts("*** Testing UTF8 support ***\n");
2999
3000 static const char textInUtf8[] =
3001 {
3002 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3003 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3004 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3005 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3006 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3007 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3008 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3009 };
3010
3011 char buf[1024];
3012 wchar_t wbuf[1024];
3013 if ( wxConvUTF8.MB2WC(wbuf, textInUtf8, WXSIZEOF(textInUtf8)) <= 0 )
3014 {
3015 puts("ERROR: UTF-8 decoding failed.");
3016 }
3017 else
3018 {
3019 // using wxEncodingConverter
3020 #if 0
3021 wxEncodingConverter ec;
3022 ec.Init(wxFONTENCODING_UNICODE, wxFONTENCODING_KOI8);
3023 ec.Convert(wbuf, buf);
3024 #else // using wxCSConv
3025 wxCSConv conv(_T("koi8-r"));
3026 if ( conv.WC2MB(buf, wbuf, 0 /* not needed wcslen(wbuf) */) <= 0 )
3027 {
3028 puts("ERROR: conversion to KOI8-R failed.");
3029 }
3030 else
3031 #endif
3032
3033 printf("The resulting string (in koi8-r): %s\n", buf);
3034 }
3035 }
3036
3037 #endif // TEST_WCHAR
3038
3039 // ----------------------------------------------------------------------------
3040 // ZIP stream
3041 // ----------------------------------------------------------------------------
3042
3043 #ifdef TEST_ZIP
3044
3045 #include "wx/filesys.h"
3046 #include "wx/fs_zip.h"
3047 #include "wx/zipstrm.h"
3048
3049 static const wxChar *TESTFILE_ZIP = _T("testdata.zip");
3050
3051 static void TestZipStreamRead()
3052 {
3053 puts("*** Testing ZIP reading ***\n");
3054
3055 static const wxChar *filename = _T("foo");
3056 wxZipInputStream istr(TESTFILE_ZIP, filename);
3057 printf("Archive size: %u\n", istr.GetSize());
3058
3059 printf("Dumping the file '%s':\n", filename);
3060 while ( !istr.Eof() )
3061 {
3062 putchar(istr.GetC());
3063 fflush(stdout);
3064 }
3065
3066 puts("\n----- done ------");
3067 }
3068
3069 static void DumpZipDirectory(wxFileSystem& fs,
3070 const wxString& dir,
3071 const wxString& indent)
3072 {
3073 wxString prefix = wxString::Format(_T("%s#zip:%s"),
3074 TESTFILE_ZIP, dir.c_str());
3075 wxString wildcard = prefix + _T("/*");
3076
3077 wxString dirname = fs.FindFirst(wildcard, wxDIR);
3078 while ( !dirname.empty() )
3079 {
3080 if ( !dirname.StartsWith(prefix + _T('/'), &dirname) )
3081 {
3082 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3083
3084 break;
3085 }
3086
3087 wxPrintf(_T("%s%s\n"), indent.c_str(), dirname.c_str());
3088
3089 DumpZipDirectory(fs, dirname,
3090 indent + wxString(_T(' '), 4));
3091
3092 dirname = fs.FindNext();
3093 }
3094
3095 wxString filename = fs.FindFirst(wildcard, wxFILE);
3096 while ( !filename.empty() )
3097 {
3098 if ( !filename.StartsWith(prefix, &filename) )
3099 {
3100 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3101
3102 break;
3103 }
3104
3105 wxPrintf(_T("%s%s\n"), indent.c_str(), filename.c_str());
3106
3107 filename = fs.FindNext();
3108 }
3109 }
3110
3111 static void TestZipFileSystem()
3112 {
3113 puts("*** Testing ZIP file system ***\n");
3114
3115 wxFileSystem::AddHandler(new wxZipFSHandler);
3116 wxFileSystem fs;
3117 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP);
3118
3119 DumpZipDirectory(fs, _T(""), wxString(_T(' '), 4));
3120 }
3121
3122 #endif // TEST_ZIP
3123
3124 // ----------------------------------------------------------------------------
3125 // ZLIB stream
3126 // ----------------------------------------------------------------------------
3127
3128 #ifdef TEST_ZLIB
3129
3130 #include "wx/zstream.h"
3131 #include "wx/wfstream.h"
3132
3133 static const wxChar *FILENAME_GZ = _T("test.gz");
3134 static const char *TEST_DATA = "hello and hello again";
3135
3136 static void TestZlibStreamWrite()
3137 {
3138 puts("*** Testing Zlib stream reading ***\n");
3139
3140 wxFileOutputStream fileOutStream(FILENAME_GZ);
3141 wxZlibOutputStream ostr(fileOutStream, 0);
3142 printf("Compressing the test string... ");
3143 ostr.Write(TEST_DATA, sizeof(TEST_DATA));
3144 if ( !ostr )
3145 {
3146 puts("(ERROR: failed)");
3147 }
3148 else
3149 {
3150 puts("(ok)");
3151 }
3152
3153 puts("\n----- done ------");
3154 }
3155
3156 static void TestZlibStreamRead()
3157 {
3158 puts("*** Testing Zlib stream reading ***\n");
3159
3160 wxFileInputStream fileInStream(FILENAME_GZ);
3161 wxZlibInputStream istr(fileInStream);
3162 printf("Archive size: %u\n", istr.GetSize());
3163
3164 puts("Dumping the file:");
3165 while ( !istr.Eof() )
3166 {
3167 putchar(istr.GetC());
3168 fflush(stdout);
3169 }
3170
3171 puts("\n----- done ------");
3172 }
3173
3174 #endif // TEST_ZLIB
3175
3176 // ----------------------------------------------------------------------------
3177 // date time
3178 // ----------------------------------------------------------------------------
3179
3180 #ifdef TEST_DATETIME
3181
3182 #include <math.h>
3183
3184 #include "wx/date.h"
3185 #include "wx/datetime.h"
3186
3187 // the test data
3188 struct Date
3189 {
3190 wxDateTime::wxDateTime_t day;
3191 wxDateTime::Month month;
3192 int year;
3193 wxDateTime::wxDateTime_t hour, min, sec;
3194 double jdn;
3195 wxDateTime::WeekDay wday;
3196 time_t gmticks, ticks;
3197
3198 void Init(const wxDateTime::Tm& tm)
3199 {
3200 day = tm.mday;
3201 month = tm.mon;
3202 year = tm.year;
3203 hour = tm.hour;
3204 min = tm.min;
3205 sec = tm.sec;
3206 jdn = 0.0;
3207 gmticks = ticks = -1;
3208 }
3209
3210 wxDateTime DT() const
3211 { return wxDateTime(day, month, year, hour, min, sec); }
3212
3213 bool SameDay(const wxDateTime::Tm& tm) const
3214 {
3215 return day == tm.mday && month == tm.mon && year == tm.year;
3216 }
3217
3218 wxString Format() const
3219 {
3220 wxString s;
3221 s.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3222 hour, min, sec,
3223 wxDateTime::GetMonthName(month).c_str(),
3224 day,
3225 abs(wxDateTime::ConvertYearToBC(year)),
3226 year > 0 ? "AD" : "BC");
3227 return s;
3228 }
3229
3230 wxString FormatDate() const
3231 {
3232 wxString s;
3233 s.Printf("%02d-%s-%4d%s",
3234 day,
3235 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
3236 abs(wxDateTime::ConvertYearToBC(year)),
3237 year > 0 ? "AD" : "BC");
3238 return s;
3239 }
3240 };
3241
3242 static const Date testDates[] =
3243 {
3244 { 1, wxDateTime::Jan, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu, 0, -3600 },
3245 { 21, wxDateTime::Jan, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon, -1, -1 },
3246 { 29, wxDateTime::May, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat, 202219200, 202212000 },
3247 { 29, wxDateTime::Feb, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun, 194400000, 194396400 },
3248 { 1, wxDateTime::Jan, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon, -1, -1 },
3249 { 1, wxDateTime::Jan, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon, -1, -1 },
3250 { 15, wxDateTime::Oct, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri, -1, -1 },
3251 { 4, wxDateTime::Oct, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon, -1, -1 },
3252 { 1, wxDateTime::Mar, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu, -1, -1 },
3253 { 1, wxDateTime::Jan, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon, -1, -1 },
3254 { 31, wxDateTime::Dec, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun, -1, -1 },
3255 { 1, wxDateTime::Jan, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat, -1, -1 },
3256 { 12, wxDateTime::Aug, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri, -1, -1 },
3257 { 12, wxDateTime::Aug, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat, -1, -1 },
3258 { 24, wxDateTime::Nov, -4713, 00, 00, 00, -0.5, wxDateTime::Mon, -1, -1 },
3259 };
3260
3261 // this test miscellaneous static wxDateTime functions
3262 static void TestTimeStatic()
3263 {
3264 puts("\n*** wxDateTime static methods test ***");
3265
3266 // some info about the current date
3267 int year = wxDateTime::GetCurrentYear();
3268 printf("Current year %d is %sa leap one and has %d days.\n",
3269 year,
3270 wxDateTime::IsLeapYear(year) ? "" : "not ",
3271 wxDateTime::GetNumberOfDays(year));
3272
3273 wxDateTime::Month month = wxDateTime::GetCurrentMonth();
3274 printf("Current month is '%s' ('%s') and it has %d days\n",
3275 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
3276 wxDateTime::GetMonthName(month).c_str(),
3277 wxDateTime::GetNumberOfDays(month));
3278
3279 // leap year logic
3280 static const size_t nYears = 5;
3281 static const size_t years[2][nYears] =
3282 {
3283 // first line: the years to test
3284 { 1990, 1976, 2000, 2030, 1984, },
3285
3286 // second line: TRUE if leap, FALSE otherwise
3287 { FALSE, TRUE, TRUE, FALSE, TRUE }
3288 };
3289
3290 for ( size_t n = 0; n < nYears; n++ )
3291 {
3292 int year = years[0][n];
3293 bool should = years[1][n] != 0,
3294 is = wxDateTime::IsLeapYear(year);
3295
3296 printf("Year %d is %sa leap year (%s)\n",
3297 year,
3298 is ? "" : "not ",
3299 should == is ? "ok" : "ERROR");
3300
3301 wxASSERT( should == wxDateTime::IsLeapYear(year) );
3302 }
3303 }
3304
3305 // test constructing wxDateTime objects
3306 static void TestTimeSet()
3307 {
3308 puts("\n*** wxDateTime construction test ***");
3309
3310 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
3311 {
3312 const Date& d1 = testDates[n];
3313 wxDateTime dt = d1.DT();
3314
3315 Date d2;
3316 d2.Init(dt.GetTm());
3317
3318 wxString s1 = d1.Format(),
3319 s2 = d2.Format();
3320
3321 printf("Date: %s == %s (%s)\n",
3322 s1.c_str(), s2.c_str(),
3323 s1 == s2 ? "ok" : "ERROR");
3324 }
3325 }
3326
3327 // test time zones stuff
3328 static void TestTimeZones()
3329 {
3330 puts("\n*** wxDateTime timezone test ***");
3331
3332 wxDateTime now = wxDateTime::Now();
3333
3334 printf("Current GMT time:\t%s\n", now.Format("%c", wxDateTime::GMT0).c_str());
3335 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0).c_str());
3336 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST).c_str());
3337 printf("Current time in Paris:\t%s\n", now.Format("%c", wxDateTime::CET).c_str());
3338 printf(" Moscow:\t%s\n", now.Format("%c", wxDateTime::MSK).c_str());
3339 printf(" New York:\t%s\n", now.Format("%c", wxDateTime::EST).c_str());
3340
3341 wxDateTime::Tm tm = now.GetTm();
3342 if ( wxDateTime(tm) != now )
3343 {
3344 printf("ERROR: got %s instead of %s\n",
3345 wxDateTime(tm).Format().c_str(), now.Format().c_str());
3346 }
3347 }
3348
3349 // test some minimal support for the dates outside the standard range
3350 static void TestTimeRange()
3351 {
3352 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3353
3354 static const char *fmt = "%d-%b-%Y %H:%M:%S";
3355
3356 printf("Unix epoch:\t%s\n",
3357 wxDateTime(2440587.5).Format(fmt).c_str());
3358 printf("Feb 29, 0: \t%s\n",
3359 wxDateTime(29, wxDateTime::Feb, 0).Format(fmt).c_str());
3360 printf("JDN 0: \t%s\n",
3361 wxDateTime(0.0).Format(fmt).c_str());
3362 printf("Jan 1, 1AD:\t%s\n",
3363 wxDateTime(1, wxDateTime::Jan, 1).Format(fmt).c_str());
3364 printf("May 29, 2099:\t%s\n",
3365 wxDateTime(29, wxDateTime::May, 2099).Format(fmt).c_str());
3366 }
3367
3368 static void TestTimeTicks()
3369 {
3370 puts("\n*** wxDateTime ticks test ***");
3371
3372 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
3373 {
3374 const Date& d = testDates[n];
3375 if ( d.ticks == -1 )
3376 continue;
3377
3378 wxDateTime dt = d.DT();
3379 long ticks = (dt.GetValue() / 1000).ToLong();
3380 printf("Ticks of %s:\t% 10ld", d.Format().c_str(), ticks);
3381 if ( ticks == d.ticks )
3382 {
3383 puts(" (ok)");
3384 }
3385 else
3386 {
3387 printf(" (ERROR: should be %ld, delta = %ld)\n",
3388 d.ticks, ticks - d.ticks);
3389 }
3390
3391 dt = d.DT().ToTimezone(wxDateTime::GMT0);
3392 ticks = (dt.GetValue() / 1000).ToLong();
3393 printf("GMtks of %s:\t% 10ld", d.Format().c_str(), ticks);
3394 if ( ticks == d.gmticks )
3395 {
3396 puts(" (ok)");
3397 }
3398 else
3399 {
3400 printf(" (ERROR: should be %ld, delta = %ld)\n",
3401 d.gmticks, ticks - d.gmticks);
3402 }
3403 }
3404
3405 puts("");
3406 }
3407
3408 // test conversions to JDN &c
3409 static void TestTimeJDN()
3410 {
3411 puts("\n*** wxDateTime to JDN test ***");
3412
3413 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
3414 {
3415 const Date& d = testDates[n];
3416 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
3417 double jdn = dt.GetJulianDayNumber();
3418
3419 printf("JDN of %s is:\t% 15.6f", d.Format().c_str(), jdn);
3420 if ( jdn == d.jdn )
3421 {
3422 puts(" (ok)");
3423 }
3424 else
3425 {
3426 printf(" (ERROR: should be %f, delta = %f)\n",
3427 d.jdn, jdn - d.jdn);
3428 }
3429 }
3430 }
3431
3432 // test week days computation
3433 static void TestTimeWDays()
3434 {
3435 puts("\n*** wxDateTime weekday test ***");
3436
3437 // test GetWeekDay()
3438 size_t n;
3439 for ( n = 0; n < WXSIZEOF(testDates); n++ )
3440 {
3441 const Date& d = testDates[n];
3442 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
3443
3444 wxDateTime::WeekDay wday = dt.GetWeekDay();
3445 printf("%s is: %s",
3446 d.Format().c_str(),
3447 wxDateTime::GetWeekDayName(wday).c_str());
3448 if ( wday == d.wday )
3449 {
3450 puts(" (ok)");
3451 }
3452 else
3453 {
3454 printf(" (ERROR: should be %s)\n",
3455 wxDateTime::GetWeekDayName(d.wday).c_str());
3456 }
3457 }
3458
3459 puts("");
3460
3461 // test SetToWeekDay()
3462 struct WeekDateTestData
3463 {
3464 Date date; // the real date (precomputed)
3465 int nWeek; // its week index in the month
3466 wxDateTime::WeekDay wday; // the weekday
3467 wxDateTime::Month month; // the month
3468 int year; // and the year
3469
3470 wxString Format() const
3471 {
3472 wxString s, which;
3473 switch ( nWeek < -1 ? -nWeek : nWeek )
3474 {
3475 case 1: which = "first"; break;
3476 case 2: which = "second"; break;
3477 case 3: which = "third"; break;
3478 case 4: which = "fourth"; break;
3479 case 5: which = "fifth"; break;
3480
3481 case -1: which = "last"; break;
3482 }
3483
3484 if ( nWeek < -1 )
3485 {
3486 which += " from end";
3487 }
3488
3489 s.Printf("The %s %s of %s in %d",
3490 which.c_str(),
3491 wxDateTime::GetWeekDayName(wday).c_str(),
3492 wxDateTime::GetMonthName(month).c_str(),
3493 year);
3494
3495 return s;
3496 }
3497 };
3498
3499 // the array data was generated by the following python program
3500 /*
3501 from DateTime import *
3502 from whrandom import *
3503 from string import *
3504
3505 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3506 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3507
3508 week = DateTimeDelta(7)
3509
3510 for n in range(20):
3511 year = randint(1900, 2100)
3512 month = randint(1, 12)
3513 day = randint(1, 28)
3514 dt = DateTime(year, month, day)
3515 wday = dt.day_of_week
3516
3517 countFromEnd = choice([-1, 1])
3518 weekNum = 0;
3519
3520 while dt.month is month:
3521 dt = dt - countFromEnd * week
3522 weekNum = weekNum + countFromEnd
3523
3524 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3525
3526 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3527 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3528 */
3529
3530 static const WeekDateTestData weekDatesTestData[] =
3531 {
3532 { { 20, wxDateTime::Mar, 2045 }, 3, wxDateTime::Mon, wxDateTime::Mar, 2045 },
3533 { { 5, wxDateTime::Jun, 1985 }, -4, wxDateTime::Wed, wxDateTime::Jun, 1985 },
3534 { { 12, wxDateTime::Nov, 1961 }, -3, wxDateTime::Sun, wxDateTime::Nov, 1961 },
3535 { { 27, wxDateTime::Feb, 2093 }, -1, wxDateTime::Fri, wxDateTime::Feb, 2093 },
3536 { { 4, wxDateTime::Jul, 2070 }, -4, wxDateTime::Fri, wxDateTime::Jul, 2070 },
3537 { { 2, wxDateTime::Apr, 1906 }, -5, wxDateTime::Mon, wxDateTime::Apr, 1906 },
3538 { { 19, wxDateTime::Jul, 2023 }, -2, wxDateTime::Wed, wxDateTime::Jul, 2023 },
3539 { { 5, wxDateTime::May, 1958 }, -4, wxDateTime::Mon, wxDateTime::May, 1958 },
3540 { { 11, wxDateTime::Aug, 1900 }, 2, wxDateTime::Sat, wxDateTime::Aug, 1900 },
3541 { { 14, wxDateTime::Feb, 1945 }, 2, wxDateTime::Wed, wxDateTime::Feb, 1945 },
3542 { { 25, wxDateTime::Jul, 1967 }, -1, wxDateTime::Tue, wxDateTime::Jul, 1967 },
3543 { { 9, wxDateTime::May, 1916 }, -4, wxDateTime::Tue, wxDateTime::May, 1916 },
3544 { { 20, wxDateTime::Jun, 1927 }, 3, wxDateTime::Mon, wxDateTime::Jun, 1927 },
3545 { { 2, wxDateTime::Aug, 2000 }, 1, wxDateTime::Wed, wxDateTime::Aug, 2000 },
3546 { { 20, wxDateTime::Apr, 2044 }, 3, wxDateTime::Wed, wxDateTime::Apr, 2044 },
3547 { { 20, wxDateTime::Feb, 1932 }, -2, wxDateTime::Sat, wxDateTime::Feb, 1932 },
3548 { { 25, wxDateTime::Jul, 2069 }, 4, wxDateTime::Thu, wxDateTime::Jul, 2069 },
3549 { { 3, wxDateTime::Apr, 1925 }, 1, wxDateTime::Fri, wxDateTime::Apr, 1925 },
3550 { { 21, wxDateTime::Mar, 2093 }, 3, wxDateTime::Sat, wxDateTime::Mar, 2093 },
3551 { { 3, wxDateTime::Dec, 2074 }, -5, wxDateTime::Mon, wxDateTime::Dec, 2074 },
3552 };
3553
3554 static const char *fmt = "%d-%b-%Y";
3555
3556 wxDateTime dt;
3557 for ( n = 0; n < WXSIZEOF(weekDatesTestData); n++ )
3558 {
3559 const WeekDateTestData& wd = weekDatesTestData[n];
3560
3561 dt.SetToWeekDay(wd.wday, wd.nWeek, wd.month, wd.year);
3562
3563 printf("%s is %s", wd.Format().c_str(), dt.Format(fmt).c_str());
3564
3565 const Date& d = wd.date;
3566 if ( d.SameDay(dt.GetTm()) )
3567 {
3568 puts(" (ok)");
3569 }
3570 else
3571 {
3572 dt.Set(d.day, d.month, d.year);
3573
3574 printf(" (ERROR: should be %s)\n", dt.Format(fmt).c_str());
3575 }
3576 }
3577 }
3578
3579 // test the computation of (ISO) week numbers
3580 static void TestTimeWNumber()
3581 {
3582 puts("\n*** wxDateTime week number test ***");
3583
3584 struct WeekNumberTestData
3585 {
3586 Date date; // the date
3587 wxDateTime::wxDateTime_t week; // the week number in the year
3588 wxDateTime::wxDateTime_t wmon; // the week number in the month
3589 wxDateTime::wxDateTime_t wmon2; // same but week starts with Sun
3590 wxDateTime::wxDateTime_t dnum; // day number in the year
3591 };
3592
3593 // data generated with the following python script:
3594 /*
3595 from DateTime import *
3596 from whrandom import *
3597 from string import *
3598
3599 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3600 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3601
3602 def GetMonthWeek(dt):
3603 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3604 if weekNumMonth < 0:
3605 weekNumMonth = weekNumMonth + 53
3606 return weekNumMonth
3607
3608 def GetLastSundayBefore(dt):
3609 if dt.iso_week[2] == 7:
3610 return dt
3611 else:
3612 return dt - DateTimeDelta(dt.iso_week[2])
3613
3614 for n in range(20):
3615 year = randint(1900, 2100)
3616 month = randint(1, 12)
3617 day = randint(1, 28)
3618 dt = DateTime(year, month, day)
3619 dayNum = dt.day_of_year
3620 weekNum = dt.iso_week[1]
3621 weekNumMonth = GetMonthWeek(dt)
3622
3623 weekNumMonth2 = 0
3624 dtSunday = GetLastSundayBefore(dt)
3625
3626 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3627 weekNumMonth2 = weekNumMonth2 + 1
3628 dtSunday = dtSunday - DateTimeDelta(7)
3629
3630 data = { 'day': rjust(`day`, 2), \
3631 'month': monthNames[month - 1], \
3632 'year': year, \
3633 'weekNum': rjust(`weekNum`, 2), \
3634 'weekNumMonth': weekNumMonth, \
3635 'weekNumMonth2': weekNumMonth2, \
3636 'dayNum': rjust(`dayNum`, 3) }
3637
3638 print " { { %(day)s, "\
3639 "wxDateTime::%(month)s, "\
3640 "%(year)d }, "\
3641 "%(weekNum)s, "\
3642 "%(weekNumMonth)s, "\
3643 "%(weekNumMonth2)s, "\
3644 "%(dayNum)s }," % data
3645
3646 */
3647 static const WeekNumberTestData weekNumberTestDates[] =
3648 {
3649 { { 27, wxDateTime::Dec, 1966 }, 52, 5, 5, 361 },
3650 { { 22, wxDateTime::Jul, 1926 }, 29, 4, 4, 203 },
3651 { { 22, wxDateTime::Oct, 2076 }, 43, 4, 4, 296 },
3652 { { 1, wxDateTime::Jul, 1967 }, 26, 1, 1, 182 },
3653 { { 8, wxDateTime::Nov, 2004 }, 46, 2, 2, 313 },
3654 { { 21, wxDateTime::Mar, 1920 }, 12, 3, 4, 81 },
3655 { { 7, wxDateTime::Jan, 1965 }, 1, 2, 2, 7 },
3656 { { 19, wxDateTime::Oct, 1999 }, 42, 4, 4, 292 },
3657 { { 13, wxDateTime::Aug, 1955 }, 32, 2, 2, 225 },
3658 { { 18, wxDateTime::Jul, 2087 }, 29, 3, 3, 199 },
3659 { { 2, wxDateTime::Sep, 2028 }, 35, 1, 1, 246 },
3660 { { 28, wxDateTime::Jul, 1945 }, 30, 5, 4, 209 },
3661 { { 15, wxDateTime::Jun, 1901 }, 24, 3, 3, 166 },
3662 { { 10, wxDateTime::Oct, 1939 }, 41, 3, 2, 283 },
3663 { { 3, wxDateTime::Dec, 1965 }, 48, 1, 1, 337 },
3664 { { 23, wxDateTime::Feb, 1940 }, 8, 4, 4, 54 },
3665 { { 2, wxDateTime::Jan, 1987 }, 1, 1, 1, 2 },
3666 { { 11, wxDateTime::Aug, 2079 }, 32, 2, 2, 223 },
3667 { { 2, wxDateTime::Feb, 2063 }, 5, 1, 1, 33 },
3668 { { 16, wxDateTime::Oct, 1942 }, 42, 3, 3, 289 },
3669 };
3670
3671 for ( size_t n = 0; n < WXSIZEOF(weekNumberTestDates); n++ )
3672 {
3673 const WeekNumberTestData& wn = weekNumberTestDates[n];
3674 const Date& d = wn.date;
3675
3676 wxDateTime dt = d.DT();
3677
3678 wxDateTime::wxDateTime_t
3679 week = dt.GetWeekOfYear(wxDateTime::Monday_First),
3680 wmon = dt.GetWeekOfMonth(wxDateTime::Monday_First),
3681 wmon2 = dt.GetWeekOfMonth(wxDateTime::Sunday_First),
3682 dnum = dt.GetDayOfYear();
3683
3684 printf("%s: the day number is %d",
3685 d.FormatDate().c_str(), dnum);
3686 if ( dnum == wn.dnum )
3687 {
3688 printf(" (ok)");
3689 }
3690 else
3691 {
3692 printf(" (ERROR: should be %d)", wn.dnum);
3693 }
3694
3695 printf(", week in month is %d", wmon);
3696 if ( wmon == wn.wmon )
3697 {
3698 printf(" (ok)");
3699 }
3700 else
3701 {
3702 printf(" (ERROR: should be %d)", wn.wmon);
3703 }
3704
3705 printf(" or %d", wmon2);
3706 if ( wmon2 == wn.wmon2 )
3707 {
3708 printf(" (ok)");
3709 }
3710 else
3711 {
3712 printf(" (ERROR: should be %d)", wn.wmon2);
3713 }
3714
3715 printf(", week in year is %d", week);
3716 if ( week == wn.week )
3717 {
3718 puts(" (ok)");
3719 }
3720 else
3721 {
3722 printf(" (ERROR: should be %d)\n", wn.week);
3723 }
3724 }
3725 }
3726
3727 // test DST calculations
3728 static void TestTimeDST()
3729 {
3730 puts("\n*** wxDateTime DST test ***");
3731
3732 printf("DST is%s in effect now.\n\n",
3733 wxDateTime::Now().IsDST() ? "" : " not");
3734
3735 // taken from http://www.energy.ca.gov/daylightsaving.html
3736 static const Date datesDST[2][2004 - 1900 + 1] =
3737 {
3738 {
3739 { 1, wxDateTime::Apr, 1990 },
3740 { 7, wxDateTime::Apr, 1991 },
3741 { 5, wxDateTime::Apr, 1992 },
3742 { 4, wxDateTime::Apr, 1993 },
3743 { 3, wxDateTime::Apr, 1994 },
3744 { 2, wxDateTime::Apr, 1995 },
3745 { 7, wxDateTime::Apr, 1996 },
3746 { 6, wxDateTime::Apr, 1997 },
3747 { 5, wxDateTime::Apr, 1998 },
3748 { 4, wxDateTime::Apr, 1999 },
3749 { 2, wxDateTime::Apr, 2000 },
3750 { 1, wxDateTime::Apr, 2001 },
3751 { 7, wxDateTime::Apr, 2002 },
3752 { 6, wxDateTime::Apr, 2003 },
3753 { 4, wxDateTime::Apr, 2004 },
3754 },
3755 {
3756 { 28, wxDateTime::Oct, 1990 },
3757 { 27, wxDateTime::Oct, 1991 },
3758 { 25, wxDateTime::Oct, 1992 },
3759 { 31, wxDateTime::Oct, 1993 },
3760 { 30, wxDateTime::Oct, 1994 },
3761 { 29, wxDateTime::Oct, 1995 },
3762 { 27, wxDateTime::Oct, 1996 },
3763 { 26, wxDateTime::Oct, 1997 },
3764 { 25, wxDateTime::Oct, 1998 },
3765 { 31, wxDateTime::Oct, 1999 },
3766 { 29, wxDateTime::Oct, 2000 },
3767 { 28, wxDateTime::Oct, 2001 },
3768 { 27, wxDateTime::Oct, 2002 },
3769 { 26, wxDateTime::Oct, 2003 },
3770 { 31, wxDateTime::Oct, 2004 },
3771 }
3772 };
3773
3774 int year;
3775 for ( year = 1990; year < 2005; year++ )
3776 {
3777 wxDateTime dtBegin = wxDateTime::GetBeginDST(year, wxDateTime::USA),
3778 dtEnd = wxDateTime::GetEndDST(year, wxDateTime::USA);
3779
3780 printf("DST period in the US for year %d: from %s to %s",
3781 year, dtBegin.Format().c_str(), dtEnd.Format().c_str());
3782
3783 size_t n = year - 1990;
3784 const Date& dBegin = datesDST[0][n];
3785 const Date& dEnd = datesDST[1][n];
3786
3787 if ( dBegin.SameDay(dtBegin.GetTm()) && dEnd.SameDay(dtEnd.GetTm()) )
3788 {
3789 puts(" (ok)");
3790 }
3791 else
3792 {
3793 printf(" (ERROR: should be %s %d to %s %d)\n",
3794 wxDateTime::GetMonthName(dBegin.month).c_str(), dBegin.day,
3795 wxDateTime::GetMonthName(dEnd.month).c_str(), dEnd.day);
3796 }
3797 }
3798
3799 puts("");
3800
3801 for ( year = 1990; year < 2005; year++ )
3802 {
3803 printf("DST period in Europe for year %d: from %s to %s\n",
3804 year,
3805 wxDateTime::GetBeginDST(year, wxDateTime::Country_EEC).Format().c_str(),
3806 wxDateTime::GetEndDST(year, wxDateTime::Country_EEC).Format().c_str());
3807 }
3808 }
3809
3810 // test wxDateTime -> text conversion
3811 static void TestTimeFormat()
3812 {
3813 puts("\n*** wxDateTime formatting test ***");
3814
3815 // some information may be lost during conversion, so store what kind
3816 // of info should we recover after a round trip
3817 enum CompareKind
3818 {
3819 CompareNone, // don't try comparing
3820 CompareBoth, // dates and times should be identical
3821 CompareDate, // dates only
3822 CompareTime // time only
3823 };
3824
3825 static const struct
3826 {
3827 CompareKind compareKind;
3828 const char *format;
3829 } formatTestFormats[] =
3830 {
3831 { CompareBoth, "---> %c" },
3832 { CompareDate, "Date is %A, %d of %B, in year %Y" },
3833 { CompareBoth, "Date is %x, time is %X" },
3834 { CompareTime, "Time is %H:%M:%S or %I:%M:%S %p" },
3835 { CompareNone, "The day of year: %j, the week of year: %W" },
3836 { CompareDate, "ISO date without separators: %4Y%2m%2d" },
3837 };
3838
3839 static const Date formatTestDates[] =
3840 {
3841 { 29, wxDateTime::May, 1976, 18, 30, 00 },
3842 { 31, wxDateTime::Dec, 1999, 23, 30, 00 },
3843 #if 0
3844 // this test can't work for other centuries because it uses two digit
3845 // years in formats, so don't even try it
3846 { 29, wxDateTime::May, 2076, 18, 30, 00 },
3847 { 29, wxDateTime::Feb, 2400, 02, 15, 25 },
3848 { 01, wxDateTime::Jan, -52, 03, 16, 47 },
3849 #endif
3850 };
3851
3852 // an extra test (as it doesn't depend on date, don't do it in the loop)
3853 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3854
3855 for ( size_t d = 0; d < WXSIZEOF(formatTestDates) + 1; d++ )
3856 {
3857 puts("");
3858
3859 wxDateTime dt = d == 0 ? wxDateTime::Now() : formatTestDates[d - 1].DT();
3860 for ( size_t n = 0; n < WXSIZEOF(formatTestFormats); n++ )
3861 {
3862 wxString s = dt.Format(formatTestFormats[n].format);
3863 printf("%s", s.c_str());
3864
3865 // what can we recover?
3866 int kind = formatTestFormats[n].compareKind;
3867
3868 // convert back
3869 wxDateTime dt2;
3870 const wxChar *result = dt2.ParseFormat(s, formatTestFormats[n].format);
3871 if ( !result )
3872 {
3873 // converion failed - should it have?
3874 if ( kind == CompareNone )
3875 puts(" (ok)");
3876 else
3877 puts(" (ERROR: conversion back failed)");
3878 }
3879 else if ( *result )
3880 {
3881 // should have parsed the entire string
3882 puts(" (ERROR: conversion back stopped too soon)");
3883 }
3884 else
3885 {
3886 bool equal = FALSE; // suppress compilaer warning
3887 switch ( kind )
3888 {
3889 case CompareBoth:
3890 equal = dt2 == dt;
3891 break;
3892
3893 case CompareDate:
3894 equal = dt.IsSameDate(dt2);
3895 break;
3896
3897 case CompareTime:
3898 equal = dt.IsSameTime(dt2);
3899 break;
3900 }
3901
3902 if ( !equal )
3903 {
3904 printf(" (ERROR: got back '%s' instead of '%s')\n",
3905 dt2.Format().c_str(), dt.Format().c_str());
3906 }
3907 else
3908 {
3909 puts(" (ok)");
3910 }
3911 }
3912 }
3913 }
3914 }
3915
3916 // test text -> wxDateTime conversion
3917 static void TestTimeParse()
3918 {
3919 puts("\n*** wxDateTime parse test ***");
3920
3921 struct ParseTestData
3922 {
3923 const char *format;
3924 Date date;
3925 bool good;
3926 };
3927
3928 static const ParseTestData parseTestDates[] =
3929 {
3930 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec, 1999, 00, 46, 40 }, TRUE },
3931 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec, 1999, 03, 17, 20 }, TRUE },
3932 };
3933
3934 for ( size_t n = 0; n < WXSIZEOF(parseTestDates); n++ )
3935 {
3936 const char *format = parseTestDates[n].format;
3937
3938 printf("%s => ", format);
3939
3940 wxDateTime dt;
3941 if ( dt.ParseRfc822Date(format) )
3942 {
3943 printf("%s ", dt.Format().c_str());
3944
3945 if ( parseTestDates[n].good )
3946 {
3947 wxDateTime dtReal = parseTestDates[n].date.DT();
3948 if ( dt == dtReal )
3949 {
3950 puts("(ok)");
3951 }
3952 else
3953 {
3954 printf("(ERROR: should be %s)\n", dtReal.Format().c_str());
3955 }
3956 }
3957 else
3958 {
3959 puts("(ERROR: bad format)");
3960 }
3961 }
3962 else
3963 {
3964 printf("bad format (%s)\n",
3965 parseTestDates[n].good ? "ERROR" : "ok");
3966 }
3967 }
3968 }
3969
3970 static void TestDateTimeInteractive()
3971 {
3972 puts("\n*** interactive wxDateTime tests ***");
3973
3974 char buf[128];
3975
3976 for ( ;; )
3977 {
3978 printf("Enter a date: ");
3979 if ( !fgets(buf, WXSIZEOF(buf), stdin) )
3980 break;
3981
3982 // kill the last '\n'
3983 buf[strlen(buf) - 1] = 0;
3984
3985 wxDateTime dt;
3986 const char *p = dt.ParseDate(buf);
3987 if ( !p )
3988 {
3989 printf("ERROR: failed to parse the date '%s'.\n", buf);
3990
3991 continue;
3992 }
3993 else if ( *p )
3994 {
3995 printf("WARNING: parsed only first %u characters.\n", p - buf);
3996 }
3997
3998 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3999 dt.Format("%b %d, %Y").c_str(),
4000 dt.GetDayOfYear(),
4001 dt.GetWeekOfMonth(wxDateTime::Monday_First),
4002 dt.GetWeekOfMonth(wxDateTime::Sunday_First),
4003 dt.GetWeekOfYear(wxDateTime::Monday_First));
4004 }
4005
4006 puts("\n*** done ***");
4007 }
4008
4009 static void TestTimeMS()
4010 {
4011 puts("*** testing millisecond-resolution support in wxDateTime ***");
4012
4013 wxDateTime dt1 = wxDateTime::Now(),
4014 dt2 = wxDateTime::UNow();
4015
4016 printf("Now = %s\n", dt1.Format("%H:%M:%S:%l").c_str());
4017 printf("UNow = %s\n", dt2.Format("%H:%M:%S:%l").c_str());
4018 printf("Dummy loop: ");
4019 for ( int i = 0; i < 6000; i++ )
4020 {
4021 //for ( int j = 0; j < 10; j++ )
4022 {
4023 wxString s;
4024 s.Printf("%g", sqrt(i));
4025 }
4026
4027 if ( !(i % 100) )
4028 putchar('.');
4029 }
4030 puts(", done");
4031
4032 dt1 = dt2;
4033 dt2 = wxDateTime::UNow();
4034 printf("UNow = %s\n", dt2.Format("%H:%M:%S:%l").c_str());
4035
4036 printf("Loop executed in %s ms\n", (dt2 - dt1).Format("%l").c_str());
4037
4038 puts("\n*** done ***");
4039 }
4040
4041 static void TestTimeArithmetics()
4042 {
4043 puts("\n*** testing arithmetic operations on wxDateTime ***");
4044
4045 static const struct ArithmData
4046 {
4047 ArithmData(const wxDateSpan& sp, const char *nam)
4048 : span(sp), name(nam) { }
4049
4050 wxDateSpan span;
4051 const char *name;
4052 } testArithmData[] =
4053 {
4054 ArithmData(wxDateSpan::Day(), "day"),
4055 ArithmData(wxDateSpan::Week(), "week"),
4056 ArithmData(wxDateSpan::Month(), "month"),
4057 ArithmData(wxDateSpan::Year(), "year"),
4058 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4059 };
4060
4061 wxDateTime dt(29, wxDateTime::Dec, 1999), dt1, dt2;
4062
4063 for ( size_t n = 0; n < WXSIZEOF(testArithmData); n++ )
4064 {
4065 wxDateSpan span = testArithmData[n].span;
4066 dt1 = dt + span;
4067 dt2 = dt - span;
4068
4069 const char *name = testArithmData[n].name;
4070 printf("%s + %s = %s, %s - %s = %s\n",
4071 dt.FormatISODate().c_str(), name, dt1.FormatISODate().c_str(),
4072 dt.FormatISODate().c_str(), name, dt2.FormatISODate().c_str());
4073
4074 printf("Going back: %s", (dt1 - span).FormatISODate().c_str());
4075 if ( dt1 - span == dt )
4076 {
4077 puts(" (ok)");
4078 }
4079 else
4080 {
4081 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
4082 }
4083
4084 printf("Going forward: %s", (dt2 + span).FormatISODate().c_str());
4085 if ( dt2 + span == dt )
4086 {
4087 puts(" (ok)");
4088 }
4089 else
4090 {
4091 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
4092 }
4093
4094 printf("Double increment: %s", (dt2 + 2*span).FormatISODate().c_str());
4095 if ( dt2 + 2*span == dt1 )
4096 {
4097 puts(" (ok)");
4098 }
4099 else
4100 {
4101 printf(" (ERROR: should be %s)\n", dt2.FormatISODate().c_str());
4102 }
4103
4104 puts("");
4105 }
4106 }
4107
4108 static void TestTimeHolidays()
4109 {
4110 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4111
4112 wxDateTime::Tm tm = wxDateTime(29, wxDateTime::May, 2000).GetTm();
4113 wxDateTime dtStart(1, tm.mon, tm.year),
4114 dtEnd = dtStart.GetLastMonthDay();
4115
4116 wxDateTimeArray hol;
4117 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart, dtEnd, hol);
4118
4119 const wxChar *format = "%d-%b-%Y (%a)";
4120
4121 printf("All holidays between %s and %s:\n",
4122 dtStart.Format(format).c_str(), dtEnd.Format(format).c_str());
4123
4124 size_t count = hol.GetCount();
4125 for ( size_t n = 0; n < count; n++ )
4126 {
4127 printf("\t%s\n", hol[n].Format(format).c_str());
4128 }
4129
4130 puts("");
4131 }
4132
4133 static void TestTimeZoneBug()
4134 {
4135 puts("\n*** testing for DST/timezone bug ***\n");
4136
4137 wxDateTime date = wxDateTime(1, wxDateTime::Mar, 2000);
4138 for ( int i = 0; i < 31; i++ )
4139 {
4140 printf("Date %s: week day %s.\n",
4141 date.Format(_T("%d-%m-%Y")).c_str(),
4142 date.GetWeekDayName(date.GetWeekDay()).c_str());
4143
4144 date += wxDateSpan::Day();
4145 }
4146
4147 puts("");
4148 }
4149
4150 static void TestTimeSpanFormat()
4151 {
4152 puts("\n*** wxTimeSpan tests ***");
4153
4154 static const char *formats[] =
4155 {
4156 _T("(default) %H:%M:%S"),
4157 _T("%E weeks and %D days"),
4158 _T("%l milliseconds"),
4159 _T("(with ms) %H:%M:%S:%l"),
4160 _T("100%% of minutes is %M"), // test "%%"
4161 _T("%D days and %H hours"),
4162 _T("or also %S seconds"),
4163 };
4164
4165 wxTimeSpan ts1(1, 2, 3, 4),
4166 ts2(111, 222, 333);
4167 for ( size_t n = 0; n < WXSIZEOF(formats); n++ )
4168 {
4169 printf("ts1 = %s\tts2 = %s\n",
4170 ts1.Format(formats[n]).c_str(),
4171 ts2.Format(formats[n]).c_str());
4172 }
4173
4174 puts("");
4175 }
4176
4177 #if 0
4178
4179 // test compatibility with the old wxDate/wxTime classes
4180 static void TestTimeCompatibility()
4181 {
4182 puts("\n*** wxDateTime compatibility test ***");
4183
4184 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4185 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4186
4187 double jdnNow = wxDateTime::Now().GetJDN();
4188 long jdnMidnight = (long)(jdnNow - 0.5);
4189 printf("wxDate for today: %s\n", wxDate(jdnMidnight).FormatDate().c_str());
4190
4191 jdnMidnight = wxDate().Set().GetJulianDate();
4192 printf("wxDateTime for today: %s\n",
4193 wxDateTime((double)(jdnMidnight + 0.5)).Format("%c", wxDateTime::GMT0).c_str());
4194
4195 int flags = wxEUROPEAN;//wxFULL;
4196 wxDate date;
4197 date.Set();
4198 printf("Today is %s\n", date.FormatDate(flags).c_str());
4199 for ( int n = 0; n < 7; n++ )
4200 {
4201 printf("Previous %s is %s\n",
4202 wxDateTime::GetWeekDayName((wxDateTime::WeekDay)n),
4203 date.Previous(n + 1).FormatDate(flags).c_str());
4204 }
4205 }
4206
4207 #endif // 0
4208
4209 #endif // TEST_DATETIME
4210
4211 // ----------------------------------------------------------------------------
4212 // threads
4213 // ----------------------------------------------------------------------------
4214
4215 #ifdef TEST_THREADS
4216
4217 #include "wx/thread.h"
4218
4219 static size_t gs_counter = (size_t)-1;
4220 static wxCriticalSection gs_critsect;
4221 static wxCondition gs_cond;
4222
4223 class MyJoinableThread : public wxThread
4224 {
4225 public:
4226 MyJoinableThread(size_t n) : wxThread(wxTHREAD_JOINABLE)
4227 { m_n = n; Create(); }
4228
4229 // thread execution starts here
4230 virtual ExitCode Entry();
4231
4232 private:
4233 size_t m_n;
4234 };
4235
4236 wxThread::ExitCode MyJoinableThread::Entry()
4237 {
4238 unsigned long res = 1;
4239 for ( size_t n = 1; n < m_n; n++ )
4240 {
4241 res *= n;
4242
4243 // it's a loooong calculation :-)
4244 Sleep(100);
4245 }
4246
4247 return (ExitCode)res;
4248 }
4249
4250 class MyDetachedThread : public wxThread
4251 {
4252 public:
4253 MyDetachedThread(size_t n, char ch)
4254 {
4255 m_n = n;
4256 m_ch = ch;
4257 m_cancelled = FALSE;
4258
4259 Create();
4260 }
4261
4262 // thread execution starts here
4263 virtual ExitCode Entry();
4264
4265 // and stops here
4266 virtual void OnExit();
4267
4268 private:
4269 size_t m_n; // number of characters to write
4270 char m_ch; // character to write
4271
4272 bool m_cancelled; // FALSE if we exit normally
4273 };
4274
4275 wxThread::ExitCode MyDetachedThread::Entry()
4276 {
4277 {
4278 wxCriticalSectionLocker lock(gs_critsect);
4279 if ( gs_counter == (size_t)-1 )
4280 gs_counter = 1;
4281 else
4282 gs_counter++;
4283 }
4284
4285 for ( size_t n = 0; n < m_n; n++ )
4286 {
4287 if ( TestDestroy() )
4288 {
4289 m_cancelled = TRUE;
4290
4291 break;
4292 }
4293
4294 putchar(m_ch);
4295 fflush(stdout);
4296
4297 wxThread::Sleep(100);
4298 }
4299
4300 return 0;
4301 }
4302
4303 void MyDetachedThread::OnExit()
4304 {
4305 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4306
4307 wxCriticalSectionLocker lock(gs_critsect);
4308 if ( !--gs_counter && !m_cancelled )
4309 gs_cond.Signal();
4310 }
4311
4312 void TestDetachedThreads()
4313 {
4314 puts("\n*** Testing detached threads ***");
4315
4316 static const size_t nThreads = 3;
4317 MyDetachedThread *threads[nThreads];
4318 size_t n;
4319 for ( n = 0; n < nThreads; n++ )
4320 {
4321 threads[n] = new MyDetachedThread(10, 'A' + n);
4322 }
4323
4324 threads[0]->SetPriority(WXTHREAD_MIN_PRIORITY);
4325 threads[1]->SetPriority(WXTHREAD_MAX_PRIORITY);
4326
4327 for ( n = 0; n < nThreads; n++ )
4328 {
4329 threads[n]->Run();
4330 }
4331
4332 // wait until all threads terminate
4333 gs_cond.Wait();
4334
4335 puts("");
4336 }
4337
4338 void TestJoinableThreads()
4339 {
4340 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4341
4342 // calc 10! in the background
4343 MyJoinableThread thread(10);
4344 thread.Run();
4345
4346 printf("\nThread terminated with exit code %lu.\n",
4347 (unsigned long)thread.Wait());
4348 }
4349
4350 void TestThreadSuspend()
4351 {
4352 puts("\n*** Testing thread suspend/resume functions ***");
4353
4354 MyDetachedThread *thread = new MyDetachedThread(15, 'X');
4355
4356 thread->Run();
4357
4358 // this is for this demo only, in a real life program we'd use another
4359 // condition variable which would be signaled from wxThread::Entry() to
4360 // tell us that the thread really started running - but here just wait a
4361 // bit and hope that it will be enough (the problem is, of course, that
4362 // the thread might still not run when we call Pause() which will result
4363 // in an error)
4364 wxThread::Sleep(300);
4365
4366 for ( size_t n = 0; n < 3; n++ )
4367 {
4368 thread->Pause();
4369
4370 puts("\nThread suspended");
4371 if ( n > 0 )
4372 {
4373 // don't sleep but resume immediately the first time
4374 wxThread::Sleep(300);
4375 }
4376 puts("Going to resume the thread");
4377
4378 thread->Resume();
4379 }
4380
4381 puts("Waiting until it terminates now");
4382
4383 // wait until the thread terminates
4384 gs_cond.Wait();
4385
4386 puts("");
4387 }
4388
4389 void TestThreadDelete()
4390 {
4391 // As above, using Sleep() is only for testing here - we must use some
4392 // synchronisation object instead to ensure that the thread is still
4393 // running when we delete it - deleting a detached thread which already
4394 // terminated will lead to a crash!
4395
4396 puts("\n*** Testing thread delete function ***");
4397
4398 MyDetachedThread *thread0 = new MyDetachedThread(30, 'W');
4399
4400 thread0->Delete();
4401
4402 puts("\nDeleted a thread which didn't start to run yet.");
4403
4404 MyDetachedThread *thread1 = new MyDetachedThread(30, 'Y');
4405
4406 thread1->Run();
4407
4408 wxThread::Sleep(300);
4409
4410 thread1->Delete();
4411
4412 puts("\nDeleted a running thread.");
4413
4414 MyDetachedThread *thread2 = new MyDetachedThread(30, 'Z');
4415
4416 thread2->Run();
4417
4418 wxThread::Sleep(300);
4419
4420 thread2->Pause();
4421
4422 thread2->Delete();
4423
4424 puts("\nDeleted a sleeping thread.");
4425
4426 MyJoinableThread thread3(20);
4427 thread3.Run();
4428
4429 thread3.Delete();
4430
4431 puts("\nDeleted a joinable thread.");
4432
4433 MyJoinableThread thread4(2);
4434 thread4.Run();
4435
4436 wxThread::Sleep(300);
4437
4438 thread4.Delete();
4439
4440 puts("\nDeleted a joinable thread which already terminated.");
4441
4442 puts("");
4443 }
4444
4445 #endif // TEST_THREADS
4446
4447 // ----------------------------------------------------------------------------
4448 // arrays
4449 // ----------------------------------------------------------------------------
4450
4451 #ifdef TEST_ARRAYS
4452
4453 static void PrintArray(const char* name, const wxArrayString& array)
4454 {
4455 printf("Dump of the array '%s'\n", name);
4456
4457 size_t nCount = array.GetCount();
4458 for ( size_t n = 0; n < nCount; n++ )
4459 {
4460 printf("\t%s[%u] = '%s'\n", name, n, array[n].c_str());
4461 }
4462 }
4463
4464 static void PrintArray(const char* name, const wxArrayInt& array)
4465 {
4466 printf("Dump of the array '%s'\n", name);
4467
4468 size_t nCount = array.GetCount();
4469 for ( size_t n = 0; n < nCount; n++ )
4470 {
4471 printf("\t%s[%u] = %d\n", name, n, array[n]);
4472 }
4473 }
4474
4475 int wxCMPFUNC_CONV StringLenCompare(const wxString& first,
4476 const wxString& second)
4477 {
4478 return first.length() - second.length();
4479 }
4480
4481 int wxCMPFUNC_CONV IntCompare(int *first,
4482 int *second)
4483 {
4484 return *first - *second;
4485 }
4486
4487 int wxCMPFUNC_CONV IntRevCompare(int *first,
4488 int *second)
4489 {
4490 return *second - *first;
4491 }
4492
4493 static void TestArrayOfInts()
4494 {
4495 puts("*** Testing wxArrayInt ***\n");
4496
4497 wxArrayInt a;
4498 a.Add(1);
4499 a.Add(17);
4500 a.Add(5);
4501 a.Add(3);
4502
4503 puts("Initially:");
4504 PrintArray("a", a);
4505
4506 puts("After sort:");
4507 a.Sort(IntCompare);
4508 PrintArray("a", a);
4509
4510 puts("After reverse sort:");
4511 a.Sort(IntRevCompare);
4512 PrintArray("a", a);
4513 }
4514
4515 #include "wx/dynarray.h"
4516
4517 WX_DECLARE_OBJARRAY(Bar, ArrayBars);
4518 #include "wx/arrimpl.cpp"
4519 WX_DEFINE_OBJARRAY(ArrayBars);
4520
4521 static void TestArrayOfObjects()
4522 {
4523 puts("*** Testing wxObjArray ***\n");
4524
4525 {
4526 ArrayBars bars;
4527 Bar bar("second bar");
4528
4529 printf("Initially: %u objects in the array, %u objects total.\n",
4530 bars.GetCount(), Bar::GetNumber());
4531
4532 bars.Add(new Bar("first bar"));
4533 bars.Add(bar);
4534
4535 printf("Now: %u objects in the array, %u objects total.\n",
4536 bars.GetCount(), Bar::GetNumber());
4537
4538 bars.Empty();
4539
4540 printf("After Empty(): %u objects in the array, %u objects total.\n",
4541 bars.GetCount(), Bar::GetNumber());
4542 }
4543
4544 printf("Finally: no more objects in the array, %u objects total.\n",
4545 Bar::GetNumber());
4546 }
4547
4548 #endif // TEST_ARRAYS
4549
4550 // ----------------------------------------------------------------------------
4551 // strings
4552 // ----------------------------------------------------------------------------
4553
4554 #ifdef TEST_STRINGS
4555
4556 #include "wx/timer.h"
4557 #include "wx/tokenzr.h"
4558
4559 static void TestStringConstruction()
4560 {
4561 puts("*** Testing wxString constructores ***");
4562
4563 #define TEST_CTOR(args, res) \
4564 { \
4565 wxString s args ; \
4566 printf("wxString%s = %s ", #args, s.c_str()); \
4567 if ( s == res ) \
4568 { \
4569 puts("(ok)"); \
4570 } \
4571 else \
4572 { \
4573 printf("(ERROR: should be %s)\n", res); \
4574 } \
4575 }
4576
4577 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4578 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4579 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4580 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4581
4582 static const wxChar *s = _T("?really!");
4583 const wxChar *start = wxStrchr(s, _T('r'));
4584 const wxChar *end = wxStrchr(s, _T('!'));
4585 TEST_CTOR((start, end), _T("really"));
4586
4587 puts("");
4588 }
4589
4590 static void TestString()
4591 {
4592 wxStopWatch sw;
4593
4594 wxString a, b, c;
4595
4596 a.reserve (128);
4597 b.reserve (128);
4598 c.reserve (128);
4599
4600 for (int i = 0; i < 1000000; ++i)
4601 {
4602 a = "Hello";
4603 b = " world";
4604 c = "! How'ya doin'?";
4605 a += b;
4606 a += c;
4607 c = "Hello world! What's up?";
4608 if (c != a)
4609 c = "Doh!";
4610 }
4611
4612 printf ("TestString elapsed time: %ld\n", sw.Time());
4613 }
4614
4615 static void TestPChar()
4616 {
4617 wxStopWatch sw;
4618
4619 char a [128];
4620 char b [128];
4621 char c [128];
4622
4623 for (int i = 0; i < 1000000; ++i)
4624 {
4625 strcpy (a, "Hello");
4626 strcpy (b, " world");
4627 strcpy (c, "! How'ya doin'?");
4628 strcat (a, b);
4629 strcat (a, c);
4630 strcpy (c, "Hello world! What's up?");
4631 if (strcmp (c, a) == 0)
4632 strcpy (c, "Doh!");
4633 }
4634
4635 printf ("TestPChar elapsed time: %ld\n", sw.Time());
4636 }
4637
4638 static void TestStringSub()
4639 {
4640 wxString s("Hello, world!");
4641
4642 puts("*** Testing wxString substring extraction ***");
4643
4644 printf("String = '%s'\n", s.c_str());
4645 printf("Left(5) = '%s'\n", s.Left(5).c_str());
4646 printf("Right(6) = '%s'\n", s.Right(6).c_str());
4647 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4648 printf("Mid(3) = '%s'\n", s.Mid(3).c_str());
4649 printf("substr(3, 5) = '%s'\n", s.substr(3, 5).c_str());
4650 printf("substr(3) = '%s'\n", s.substr(3).c_str());
4651
4652 static const wxChar *prefixes[] =
4653 {
4654 _T("Hello"),
4655 _T("Hello, "),
4656 _T("Hello, world!"),
4657 _T("Hello, world!!!"),
4658 _T(""),
4659 _T("Goodbye"),
4660 _T("Hi"),
4661 };
4662
4663 for ( size_t n = 0; n < WXSIZEOF(prefixes); n++ )
4664 {
4665 wxString prefix = prefixes[n], rest;
4666 bool rc = s.StartsWith(prefix, &rest);
4667 printf("StartsWith('%s') = %s", prefix.c_str(), rc ? "TRUE" : "FALSE");
4668 if ( rc )
4669 {
4670 printf(" (the rest is '%s')\n", rest.c_str());
4671 }
4672 else
4673 {
4674 putchar('\n');
4675 }
4676 }
4677
4678 puts("");
4679 }
4680
4681 static void TestStringFormat()
4682 {
4683 puts("*** Testing wxString formatting ***");
4684
4685 wxString s;
4686 s.Printf("%03d", 18);
4687
4688 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4689 printf("Number 18: %s\n", s.c_str());
4690
4691 puts("");
4692 }
4693
4694 // returns "not found" for npos, value for all others
4695 static wxString PosToString(size_t res)
4696 {
4697 wxString s = res == wxString::npos ? wxString(_T("not found"))
4698 : wxString::Format(_T("%u"), res);
4699 return s;
4700 }
4701
4702 static void TestStringFind()
4703 {
4704 puts("*** Testing wxString find() functions ***");
4705
4706 static const wxChar *strToFind = _T("ell");
4707 static const struct StringFindTest
4708 {
4709 const wxChar *str;
4710 size_t start,
4711 result; // of searching "ell" in str
4712 } findTestData[] =
4713 {
4714 { _T("Well, hello world"), 0, 1 },
4715 { _T("Well, hello world"), 6, 7 },
4716 { _T("Well, hello world"), 9, wxString::npos },
4717 };
4718
4719 for ( size_t n = 0; n < WXSIZEOF(findTestData); n++ )
4720 {
4721 const StringFindTest& ft = findTestData[n];
4722 size_t res = wxString(ft.str).find(strToFind, ft.start);
4723
4724 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4725 strToFind, ft.str, ft.start, PosToString(res).c_str());
4726
4727 size_t resTrue = ft.result;
4728 if ( res == resTrue )
4729 {
4730 puts(_T("(ok)"));
4731 }
4732 else
4733 {
4734 printf(_T("(ERROR: should be %s)\n"),
4735 PosToString(resTrue).c_str());
4736 }
4737 }
4738
4739 puts("");
4740 }
4741
4742 static void TestStringTokenizer()
4743 {
4744 puts("*** Testing wxStringTokenizer ***");
4745
4746 static const wxChar *modeNames[] =
4747 {
4748 _T("default"),
4749 _T("return empty"),
4750 _T("return all empty"),
4751 _T("with delims"),
4752 _T("like strtok"),
4753 };
4754
4755 static const struct StringTokenizerTest
4756 {
4757 const wxChar *str; // string to tokenize
4758 const wxChar *delims; // delimiters to use
4759 size_t count; // count of token
4760 wxStringTokenizerMode mode; // how should we tokenize it
4761 } tokenizerTestData[] =
4762 {
4763 { _T(""), _T(" "), 0 },
4764 { _T("Hello, world"), _T(" "), 2 },
4765 { _T("Hello, world "), _T(" "), 2 },
4766 { _T("Hello, world"), _T(","), 2 },
4767 { _T("Hello, world!"), _T(",!"), 2 },
4768 { _T("Hello,, world!"), _T(",!"), 3 },
4769 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL },
4770 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4771 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 4 },
4772 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 6, wxTOKEN_RET_EMPTY },
4773 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 9, wxTOKEN_RET_EMPTY_ALL },
4774 { _T("01/02/99"), _T("/-"), 3 },
4775 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS },
4776 };
4777
4778 for ( size_t n = 0; n < WXSIZEOF(tokenizerTestData); n++ )
4779 {
4780 const StringTokenizerTest& tt = tokenizerTestData[n];
4781 wxStringTokenizer tkz(tt.str, tt.delims, tt.mode);
4782
4783 size_t count = tkz.CountTokens();
4784 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4785 MakePrintable(tt.str).c_str(),
4786 count,
4787 MakePrintable(tt.delims).c_str(),
4788 modeNames[tkz.GetMode()]);
4789 if ( count == tt.count )
4790 {
4791 puts(_T("(ok)"));
4792 }
4793 else
4794 {
4795 printf(_T("(ERROR: should be %u)\n"), tt.count);
4796
4797 continue;
4798 }
4799
4800 // if we emulate strtok(), check that we do it correctly
4801 wxChar *buf, *s = NULL, *last;
4802
4803 if ( tkz.GetMode() == wxTOKEN_STRTOK )
4804 {
4805 buf = new wxChar[wxStrlen(tt.str) + 1];
4806 wxStrcpy(buf, tt.str);
4807
4808 s = wxStrtok(buf, tt.delims, &last);
4809 }
4810 else
4811 {
4812 buf = NULL;
4813 }
4814
4815 // now show the tokens themselves
4816 size_t count2 = 0;
4817 while ( tkz.HasMoreTokens() )
4818 {
4819 wxString token = tkz.GetNextToken();
4820
4821 printf(_T("\ttoken %u: '%s'"),
4822 ++count2,
4823 MakePrintable(token).c_str());
4824
4825 if ( buf )
4826 {
4827 if ( token == s )
4828 {
4829 puts(" (ok)");
4830 }
4831 else
4832 {
4833 printf(" (ERROR: should be %s)\n", s);
4834 }
4835
4836 s = wxStrtok(NULL, tt.delims, &last);
4837 }
4838 else
4839 {
4840 // nothing to compare with
4841 puts("");
4842 }
4843 }
4844
4845 if ( count2 != count )
4846 {
4847 puts(_T("\tERROR: token count mismatch"));
4848 }
4849
4850 delete [] buf;
4851 }
4852
4853 puts("");
4854 }
4855
4856 static void TestStringReplace()
4857 {
4858 puts("*** Testing wxString::replace ***");
4859
4860 static const struct StringReplaceTestData
4861 {
4862 const wxChar *original; // original test string
4863 size_t start, len; // the part to replace
4864 const wxChar *replacement; // the replacement string
4865 const wxChar *result; // and the expected result
4866 } stringReplaceTestData[] =
4867 {
4868 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4869 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4870 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4871 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4872 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4873 };
4874
4875 for ( size_t n = 0; n < WXSIZEOF(stringReplaceTestData); n++ )
4876 {
4877 const StringReplaceTestData data = stringReplaceTestData[n];
4878
4879 wxString original = data.original;
4880 original.replace(data.start, data.len, data.replacement);
4881
4882 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4883 data.original, data.start, data.len, data.replacement,
4884 original.c_str());
4885
4886 if ( original == data.result )
4887 {
4888 puts("(ok)");
4889 }
4890 else
4891 {
4892 wxPrintf(_T("(ERROR: should be '%s')\n"), data.result);
4893 }
4894 }
4895
4896 puts("");
4897 }
4898
4899 static void TestStringMatch()
4900 {
4901 wxPuts(_T("*** Testing wxString::Matches() ***"));
4902
4903 static const struct StringMatchTestData
4904 {
4905 const wxChar *text;
4906 const wxChar *wildcard;
4907 bool matches;
4908 } stringMatchTestData[] =
4909 {
4910 { _T("foobar"), _T("foo*"), 1 },
4911 { _T("foobar"), _T("*oo*"), 1 },
4912 { _T("foobar"), _T("*bar"), 1 },
4913 { _T("foobar"), _T("??????"), 1 },
4914 { _T("foobar"), _T("f??b*"), 1 },
4915 { _T("foobar"), _T("f?b*"), 0 },
4916 { _T("foobar"), _T("*goo*"), 0 },
4917 { _T("foobar"), _T("*foo"), 0 },
4918 { _T("foobarfoo"), _T("*foo"), 1 },
4919 { _T(""), _T("*"), 1 },
4920 { _T(""), _T("?"), 0 },
4921 };
4922
4923 for ( size_t n = 0; n < WXSIZEOF(stringMatchTestData); n++ )
4924 {
4925 const StringMatchTestData& data = stringMatchTestData[n];
4926 bool matches = wxString(data.text).Matches(data.wildcard);
4927 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
4928 data.wildcard,
4929 matches ? _T("matches") : _T("doesn't match"),
4930 data.text,
4931 matches == data.matches ? _T("ok") : _T("ERROR"));
4932 }
4933
4934 wxPuts(_T(""));
4935 }
4936
4937 #endif // TEST_STRINGS
4938
4939 // ----------------------------------------------------------------------------
4940 // entry point
4941 // ----------------------------------------------------------------------------
4942
4943 int main(int argc, char **argv)
4944 {
4945 wxInitializer initializer;
4946 if ( !initializer )
4947 {
4948 fprintf(stderr, "Failed to initialize the wxWindows library, aborting.");
4949
4950 return -1;
4951 }
4952
4953 #ifdef TEST_SNGLINST
4954 wxSingleInstanceChecker checker;
4955 if ( checker.Create(_T(".wxconsole.lock")) )
4956 {
4957 if ( checker.IsAnotherRunning() )
4958 {
4959 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4960
4961 return 1;
4962 }
4963
4964 // wait some time to give time to launch another instance
4965 wxPrintf(_T("Press \"Enter\" to continue..."));
4966 wxFgetc(stdin);
4967 }
4968 else // failed to create
4969 {
4970 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4971 }
4972 #endif // TEST_SNGLINST
4973
4974 #ifdef TEST_CHARSET
4975 TestCharset();
4976 #endif // TEST_CHARSET
4977
4978 #ifdef TEST_CMDLINE
4979 TestCmdLineConvert();
4980
4981 #if wxUSE_CMDLINE_PARSER
4982 static const wxCmdLineEntryDesc cmdLineDesc[] =
4983 {
4984 { wxCMD_LINE_SWITCH, _T("h"), _T("help"), "show this help message",
4985 wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
4986 { wxCMD_LINE_SWITCH, "v", "verbose", "be verbose" },
4987 { wxCMD_LINE_SWITCH, "q", "quiet", "be quiet" },
4988
4989 { wxCMD_LINE_OPTION, "o", "output", "output file" },
4990 { wxCMD_LINE_OPTION, "i", "input", "input dir" },
4991 { wxCMD_LINE_OPTION, "s", "size", "output block size",
4992 wxCMD_LINE_VAL_NUMBER },
4993 { wxCMD_LINE_OPTION, "d", "date", "output file date",
4994 wxCMD_LINE_VAL_DATE },
4995
4996 { wxCMD_LINE_PARAM, NULL, NULL, "input file",
4997 wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_MULTIPLE },
4998
4999 { wxCMD_LINE_NONE }
5000 };
5001
5002 wxCmdLineParser parser(cmdLineDesc, argc, argv);
5003
5004 parser.AddOption("project_name", "", "full path to project file",
5005 wxCMD_LINE_VAL_STRING,
5006 wxCMD_LINE_OPTION_MANDATORY | wxCMD_LINE_NEEDS_SEPARATOR);
5007
5008 switch ( parser.Parse() )
5009 {
5010 case -1:
5011 wxLogMessage("Help was given, terminating.");
5012 break;
5013
5014 case 0:
5015 ShowCmdLine(parser);
5016 break;
5017
5018 default:
5019 wxLogMessage("Syntax error detected, aborting.");
5020 break;
5021 }
5022 #endif // wxUSE_CMDLINE_PARSER
5023
5024 #endif // TEST_CMDLINE
5025
5026 #ifdef TEST_STRINGS
5027 if ( 0 )
5028 {
5029 TestPChar();
5030 TestString();
5031 TestStringSub();
5032 TestStringConstruction();
5033 TestStringFormat();
5034 TestStringFind();
5035 TestStringTokenizer();
5036 TestStringReplace();
5037 }
5038 TestStringMatch();
5039 #endif // TEST_STRINGS
5040
5041 #ifdef TEST_ARRAYS
5042 if ( 0 )
5043 {
5044 wxArrayString a1;
5045 a1.Add("tiger");
5046 a1.Add("cat");
5047 a1.Add("lion");
5048 a1.Add("dog");
5049 a1.Add("human");
5050 a1.Add("ape");
5051
5052 puts("*** Initially:");
5053
5054 PrintArray("a1", a1);
5055
5056 wxArrayString a2(a1);
5057 PrintArray("a2", a2);
5058
5059 wxSortedArrayString a3(a1);
5060 PrintArray("a3", a3);
5061
5062 puts("*** After deleting a string from a1");
5063 a1.Remove(2);
5064
5065 PrintArray("a1", a1);
5066 PrintArray("a2", a2);
5067 PrintArray("a3", a3);
5068
5069 puts("*** After reassigning a1 to a2 and a3");
5070 a3 = a2 = a1;
5071 PrintArray("a2", a2);
5072 PrintArray("a3", a3);
5073
5074 puts("*** After sorting a1");
5075 a1.Sort();
5076 PrintArray("a1", a1);
5077
5078 puts("*** After sorting a1 in reverse order");
5079 a1.Sort(TRUE);
5080 PrintArray("a1", a1);
5081
5082 puts("*** After sorting a1 by the string length");
5083 a1.Sort(StringLenCompare);
5084 PrintArray("a1", a1);
5085
5086 TestArrayOfObjects();
5087 }
5088 TestArrayOfInts();
5089 #endif // TEST_ARRAYS
5090
5091 #ifdef TEST_DIR
5092 if ( 0 )
5093 TestDirEnum();
5094 TestDirTraverse();
5095 #endif // TEST_DIR
5096
5097 #ifdef TEST_DLLLOADER
5098 TestDllLoad();
5099 #endif // TEST_DLLLOADER
5100
5101 #ifdef TEST_ENVIRON
5102 TestEnvironment();
5103 #endif // TEST_ENVIRON
5104
5105 #ifdef TEST_EXECUTE
5106 TestExecute();
5107 #endif // TEST_EXECUTE
5108
5109 #ifdef TEST_FILECONF
5110 TestFileConfRead();
5111 #endif // TEST_FILECONF
5112
5113 #ifdef TEST_LIST
5114 TestListCtor();
5115 #endif // TEST_LIST
5116
5117 #ifdef TEST_LOCALE
5118 TestDefaultLang();
5119 #endif // TEST_LOCALE
5120
5121 #ifdef TEST_LOG
5122 wxString s;
5123 for ( size_t n = 0; n < 8000; n++ )
5124 {
5125 s << (char)('A' + (n % 26));
5126 }
5127
5128 wxString msg;
5129 msg.Printf("A very very long message: '%s', the end!\n", s.c_str());
5130
5131 // this one shouldn't be truncated
5132 printf(msg);
5133
5134 // but this one will because log functions use fixed size buffer
5135 // (note that it doesn't need '\n' at the end neither - will be added
5136 // by wxLog anyhow)
5137 wxLogMessage("A very very long message 2: '%s', the end!", s.c_str());
5138 #endif // TEST_LOG
5139
5140 #ifdef TEST_FILE
5141 if ( 0 )
5142 {
5143 TestFileRead();
5144 TestTextFileRead();
5145 }
5146 TestFileCopy();
5147 #endif // TEST_FILE
5148
5149 #ifdef TEST_FILENAME
5150 TestFileNameSplit();
5151 if ( 0 )
5152 {
5153 TestFileNameConstruction();
5154 TestFileNameCwd();
5155 TestFileNameComparison();
5156 TestFileNameOperations();
5157 }
5158 #endif // TEST_FILENAME
5159
5160 #ifdef TEST_FILETIME
5161 TestFileGetTimes();
5162 TestFileSetTimes();
5163 #endif // TEST_FILETIME
5164
5165 #ifdef TEST_FTP
5166 wxLog::AddTraceMask(FTP_TRACE_MASK);
5167 if ( TestFtpConnect() )
5168 {
5169 TestFtpFileSize();
5170 if ( 0 )
5171 {
5172 TestFtpList();
5173 TestFtpDownload();
5174 TestFtpMisc();
5175 TestFtpUpload();
5176 }
5177 if ( 0 )
5178 TestFtpInteractive();
5179 }
5180 //else: connecting to the FTP server failed
5181
5182 if ( 0 )
5183 TestFtpWuFtpd();
5184 #endif // TEST_FTP
5185
5186 #ifdef TEST_THREADS
5187 int nCPUs = wxThread::GetCPUCount();
5188 printf("This system has %d CPUs\n", nCPUs);
5189 if ( nCPUs != -1 )
5190 wxThread::SetConcurrency(nCPUs);
5191
5192 if ( argc > 1 && argv[1][0] == 't' )
5193 wxLog::AddTraceMask("thread");
5194
5195 if ( 1 )
5196 TestDetachedThreads();
5197 if ( 1 )
5198 TestJoinableThreads();
5199 if ( 1 )
5200 TestThreadSuspend();
5201 if ( 1 )
5202 TestThreadDelete();
5203
5204 #endif // TEST_THREADS
5205
5206 #ifdef TEST_LONGLONG
5207 // seed pseudo random generator
5208 srand((unsigned)time(NULL));
5209
5210 if ( 0 )
5211 {
5212 TestSpeed();
5213 }
5214 if ( 0 )
5215 {
5216 TestMultiplication();
5217 TestDivision();
5218 TestAddition();
5219 TestLongLongConversion();
5220 TestBitOperations();
5221 TestLongLongComparison();
5222 }
5223 TestLongLongPrint();
5224 #endif // TEST_LONGLONG
5225
5226 #ifdef TEST_HASH
5227 TestHash();
5228 #endif // TEST_HASH
5229
5230 #ifdef TEST_MIME
5231 wxLog::AddTraceMask(_T("mime"));
5232 if ( 1 )
5233 {
5234 TestMimeEnum();
5235 TestMimeOverride();
5236 TestMimeFilename();
5237 }
5238 else
5239 TestMimeAssociate();
5240 #endif // TEST_MIME
5241
5242 #ifdef TEST_INFO_FUNCTIONS
5243 TestDiskInfo();
5244 if ( 0 )
5245 {
5246 TestOsInfo();
5247 TestUserInfo();
5248 }
5249 #endif // TEST_INFO_FUNCTIONS
5250
5251 #ifdef TEST_PATHLIST
5252 TestPathList();
5253 #endif // TEST_PATHLIST
5254
5255 #ifdef TEST_REGCONF
5256 TestRegConfWrite();
5257 #endif // TEST_REGCONF
5258
5259 #ifdef TEST_REGEX
5260 // TODO: write a real test using src/regex/tests file
5261 if ( 0 )
5262 {
5263 TestRegExCompile();
5264 TestRegExMatch();
5265 TestRegExSubmatch();
5266 TestRegExInteractive();
5267 }
5268 TestRegExReplacement();
5269 #endif // TEST_REGEX
5270
5271 #ifdef TEST_REGISTRY
5272 if ( 0 )
5273 TestRegistryRead();
5274 TestRegistryAssociation();
5275 #endif // TEST_REGISTRY
5276
5277 #ifdef TEST_SOCKETS
5278 if ( 0 )
5279 {
5280 TestSocketServer();
5281 }
5282 TestSocketClient();
5283 #endif // TEST_SOCKETS
5284
5285 #ifdef TEST_STREAMS
5286 if ( 0 )
5287 TestFileStream();
5288 TestMemoryStream();
5289 #endif // TEST_STREAMS
5290
5291 #ifdef TEST_TIMER
5292 TestStopWatch();
5293 #endif // TEST_TIMER
5294
5295 #ifdef TEST_DATETIME
5296 if ( 0 )
5297 {
5298 TestTimeSet();
5299 TestTimeStatic();
5300 TestTimeRange();
5301 TestTimeZones();
5302 TestTimeTicks();
5303 TestTimeJDN();
5304 TestTimeDST();
5305 TestTimeWDays();
5306 TestTimeWNumber();
5307 TestTimeParse();
5308 TestTimeArithmetics();
5309 TestTimeHolidays();
5310 TestTimeFormat();
5311 TestTimeMS();
5312
5313 TestTimeZoneBug();
5314 }
5315 TestTimeSpanFormat();
5316 if ( 0 )
5317 TestDateTimeInteractive();
5318 #endif // TEST_DATETIME
5319
5320 #ifdef TEST_USLEEP
5321 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5322 wxUsleep(3000);
5323 #endif // TEST_USLEEP
5324
5325 #ifdef TEST_VCARD
5326 if ( 0 )
5327 TestVCardRead();
5328 TestVCardWrite();
5329 #endif // TEST_VCARD
5330
5331 #ifdef TEST_WCHAR
5332 TestUtf8();
5333 #endif // TEST_WCHAR
5334
5335 #ifdef TEST_ZIP
5336 if ( 0 )
5337 TestZipStreamRead();
5338 TestZipFileSystem();
5339 #endif // TEST_ZIP
5340
5341 #ifdef TEST_ZLIB
5342 if ( 0 )
5343 TestZlibStreamWrite();
5344 TestZlibStreamRead();
5345 #endif // TEST_ZLIB
5346
5347 return 0;
5348 }
5349