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