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