1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWindows
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
23 #error "This sample can't be compiled in GUI mode."
28 #include "wx/string.h"
32 // without this pragma, the stupid compiler precompiles #defines below so that
33 // changing them doesn't "take place" later!
38 // ----------------------------------------------------------------------------
39 // conditional compilation
40 // ----------------------------------------------------------------------------
43 A note about all these conditional compilation macros: this file is used
44 both as a test suite for various non-GUI wxWindows classes and as a
45 scratchpad for quick tests. So there are two compilation modes: if you
46 define TEST_ALL all tests are run, otherwise you may enable the individual
47 tests individually in the "#else" branch below.
50 // what to test (in alphabetic order)? uncomment the line below to do all tests
58 #define TEST_DLLLOADER
68 #define TEST_INFO_FUNCTIONS
84 // #define TEST_VCARD -- don't enable this (VZ)
90 static const bool TEST_ALL
= TRUE
;
94 static const bool TEST_ALL
= FALSE
;
97 // some tests are interactive, define this to run them
98 #ifdef TEST_INTERACTIVE
99 #undef TEST_INTERACTIVE
101 static const bool TEST_INTERACTIVE
= FALSE
;
103 static const bool TEST_INTERACTIVE
= FALSE
;
106 // ----------------------------------------------------------------------------
107 // test class for container objects
108 // ----------------------------------------------------------------------------
110 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
112 class Bar
// Foo is already taken in the hash test
115 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
116 ~Bar() { ms_bars
--; }
118 static size_t GetNumber() { return ms_bars
; }
120 const char *GetName() const { return m_name
; }
125 static size_t ms_bars
;
128 size_t Bar::ms_bars
= 0;
130 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
132 // ============================================================================
134 // ============================================================================
136 // ----------------------------------------------------------------------------
138 // ----------------------------------------------------------------------------
140 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
142 // replace TABs with \t and CRs with \n
143 static wxString
MakePrintable(const wxChar
*s
)
146 (void)str
.Replace(_T("\t"), _T("\\t"));
147 (void)str
.Replace(_T("\n"), _T("\\n"));
148 (void)str
.Replace(_T("\r"), _T("\\r"));
153 #endif // MakePrintable() is used
155 // ----------------------------------------------------------------------------
156 // wxFontMapper::CharsetToEncoding
157 // ----------------------------------------------------------------------------
161 #include "wx/fontmap.h"
163 static void TestCharset()
165 static const wxChar
*charsets
[] =
167 // some vali charsets
176 // and now some bogus ones
183 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
185 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(charsets
[n
]);
186 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
188 wxTheFontMapper
->GetEncodingName(enc
).c_str(),
189 wxTheFontMapper
->GetEncodingDescription(enc
).c_str());
193 #endif // TEST_CHARSET
195 // ----------------------------------------------------------------------------
197 // ----------------------------------------------------------------------------
201 #include "wx/cmdline.h"
202 #include "wx/datetime.h"
204 #if wxUSE_CMDLINE_PARSER
206 static void ShowCmdLine(const wxCmdLineParser
& parser
)
208 wxString s
= "Input files: ";
210 size_t count
= parser
.GetParamCount();
211 for ( size_t param
= 0; param
< count
; param
++ )
213 s
<< parser
.GetParam(param
) << ' ';
217 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
218 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
223 if ( parser
.Found("o", &strVal
) )
224 s
<< "Output file:\t" << strVal
<< '\n';
225 if ( parser
.Found("i", &strVal
) )
226 s
<< "Input dir:\t" << strVal
<< '\n';
227 if ( parser
.Found("s", &lVal
) )
228 s
<< "Size:\t" << lVal
<< '\n';
229 if ( parser
.Found("d", &dt
) )
230 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
231 if ( parser
.Found("project_name", &strVal
) )
232 s
<< "Project:\t" << strVal
<< '\n';
237 #endif // wxUSE_CMDLINE_PARSER
239 static void TestCmdLineConvert()
241 static const char *cmdlines
[] =
244 "-a \"-bstring 1\" -c\"string 2\" \"string 3\"",
245 "literal \\\" and \"\"",
248 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
250 const char *cmdline
= cmdlines
[n
];
251 printf("Parsing: %s\n", cmdline
);
252 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
254 size_t count
= args
.GetCount();
255 printf("\targc = %u\n", count
);
256 for ( size_t arg
= 0; arg
< count
; arg
++ )
258 printf("\targv[%u] = %s\n", arg
, args
[arg
].c_str());
263 #endif // TEST_CMDLINE
265 // ----------------------------------------------------------------------------
267 // ----------------------------------------------------------------------------
274 static const wxChar
*ROOTDIR
= _T("/");
275 static const wxChar
*TESTDIR
= _T("/usr");
276 #elif defined(__WXMSW__)
277 static const wxChar
*ROOTDIR
= _T("c:\\");
278 static const wxChar
*TESTDIR
= _T("d:\\");
280 #error "don't know where the root directory is"
283 static void TestDirEnumHelper(wxDir
& dir
,
284 int flags
= wxDIR_DEFAULT
,
285 const wxString
& filespec
= wxEmptyString
)
289 if ( !dir
.IsOpened() )
292 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
295 printf("\t%s\n", filename
.c_str());
297 cont
= dir
.GetNext(&filename
);
303 static void TestDirEnum()
305 puts("*** Testing wxDir::GetFirst/GetNext ***");
307 wxDir
dir(wxGetCwd());
309 puts("Enumerating everything in current directory:");
310 TestDirEnumHelper(dir
);
312 puts("Enumerating really everything in current directory:");
313 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
315 puts("Enumerating object files in current directory:");
316 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
318 puts("Enumerating directories in current directory:");
319 TestDirEnumHelper(dir
, wxDIR_DIRS
);
321 puts("Enumerating files in current directory:");
322 TestDirEnumHelper(dir
, wxDIR_FILES
);
324 puts("Enumerating files including hidden in current directory:");
325 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
329 puts("Enumerating everything in root directory:");
330 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
332 puts("Enumerating directories in root directory:");
333 TestDirEnumHelper(dir
, wxDIR_DIRS
);
335 puts("Enumerating files in root directory:");
336 TestDirEnumHelper(dir
, wxDIR_FILES
);
338 puts("Enumerating files including hidden in root directory:");
339 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
341 puts("Enumerating files in non existing directory:");
342 wxDir
dirNo("nosuchdir");
343 TestDirEnumHelper(dirNo
);
346 class DirPrintTraverser
: public wxDirTraverser
349 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
351 return wxDIR_CONTINUE
;
354 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
356 wxString path
, name
, ext
;
357 wxSplitPath(dirname
, &path
, &name
, &ext
);
360 name
<< _T('.') << ext
;
363 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
365 if ( wxIsPathSeparator(*p
) )
369 printf("%s%s\n", indent
.c_str(), name
.c_str());
371 return wxDIR_CONTINUE
;
375 static void TestDirTraverse()
377 puts("*** Testing wxDir::Traverse() ***");
381 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
382 printf("There are %u files under '%s'\n", n
, TESTDIR
);
385 printf("First one is '%s'\n", files
[0u].c_str());
386 printf(" last one is '%s'\n", files
[n
- 1].c_str());
389 // enum again with custom traverser
391 DirPrintTraverser traverser
;
392 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
397 // ----------------------------------------------------------------------------
399 // ----------------------------------------------------------------------------
401 #ifdef TEST_DLLLOADER
403 #include "wx/dynlib.h"
405 static void TestDllLoad()
407 #if defined(__WXMSW__)
408 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
409 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
410 #elif defined(__UNIX__)
411 // weird: using just libc.so does *not* work!
412 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
413 static const wxChar
*FUNC_NAME
= _T("strlen");
415 #error "don't know how to test wxDllLoader on this platform"
418 puts("*** testing wxDllLoader ***\n");
420 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
423 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
427 typedef int (*strlenType
)(const char *);
428 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
431 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
432 FUNC_NAME
, LIB_NAME
);
436 if ( pfnStrlen("foo") != 3 )
438 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
446 wxDllLoader::UnloadLibrary(dllHandle
);
450 #endif // TEST_DLLLOADER
452 // ----------------------------------------------------------------------------
454 // ----------------------------------------------------------------------------
458 #include "wx/utils.h"
460 static wxString
MyGetEnv(const wxString
& var
)
463 if ( !wxGetEnv(var
, &val
) )
466 val
= wxString(_T('\'')) + val
+ _T('\'');
471 static void TestEnvironment()
473 const wxChar
*var
= _T("wxTestVar");
475 puts("*** testing environment access functions ***");
477 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
478 wxSetEnv(var
, _T("value for wxTestVar"));
479 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
480 wxSetEnv(var
, _T("another value"));
481 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
483 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
484 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
487 #endif // TEST_ENVIRON
489 // ----------------------------------------------------------------------------
491 // ----------------------------------------------------------------------------
495 #include "wx/utils.h"
497 static void TestExecute()
499 puts("*** testing wxExecute ***");
502 #define COMMAND "cat -n ../../Makefile" // "echo hi"
503 #define SHELL_COMMAND "echo hi from shell"
504 #define REDIRECT_COMMAND COMMAND // "date"
505 #elif defined(__WXMSW__)
506 #define COMMAND "command.com -c 'echo hi'"
507 #define SHELL_COMMAND "echo hi"
508 #define REDIRECT_COMMAND COMMAND
510 #error "no command to exec"
513 printf("Testing wxShell: ");
515 if ( wxShell(SHELL_COMMAND
) )
520 printf("Testing wxExecute: ");
522 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
527 #if 0 // no, it doesn't work (yet?)
528 printf("Testing async wxExecute: ");
530 if ( wxExecute(COMMAND
) != 0 )
531 puts("Ok (command launched).");
536 printf("Testing wxExecute with redirection:\n");
537 wxArrayString output
;
538 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
544 size_t count
= output
.GetCount();
545 for ( size_t n
= 0; n
< count
; n
++ )
547 printf("\t%s\n", output
[n
].c_str());
554 #endif // TEST_EXECUTE
556 // ----------------------------------------------------------------------------
558 // ----------------------------------------------------------------------------
563 #include "wx/ffile.h"
564 #include "wx/textfile.h"
566 static void TestFileRead()
568 puts("*** wxFile read test ***");
570 wxFile
file(_T("testdata.fc"));
571 if ( file
.IsOpened() )
573 printf("File length: %lu\n", file
.Length());
575 puts("File dump:\n----------");
577 static const off_t len
= 1024;
581 off_t nRead
= file
.Read(buf
, len
);
582 if ( nRead
== wxInvalidOffset
)
584 printf("Failed to read the file.");
588 fwrite(buf
, nRead
, 1, stdout
);
598 printf("ERROR: can't open test file.\n");
604 static void TestTextFileRead()
606 puts("*** wxTextFile read test ***");
608 wxTextFile
file(_T("testdata.fc"));
611 printf("Number of lines: %u\n", file
.GetLineCount());
612 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
616 puts("\nDumping the entire file:");
617 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
619 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
621 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
623 puts("\nAnd now backwards:");
624 for ( s
= file
.GetLastLine();
625 file
.GetCurrentLine() != 0;
626 s
= file
.GetPrevLine() )
628 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
630 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
634 printf("ERROR: can't open '%s'\n", file
.GetName());
640 static void TestFileCopy()
642 puts("*** Testing wxCopyFile ***");
644 static const wxChar
*filename1
= _T("testdata.fc");
645 static const wxChar
*filename2
= _T("test2");
646 if ( !wxCopyFile(filename1
, filename2
) )
648 puts("ERROR: failed to copy file");
652 wxFFile
f1(filename1
, "rb"),
655 if ( !f1
.IsOpened() || !f2
.IsOpened() )
657 puts("ERROR: failed to open file(s)");
662 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
664 puts("ERROR: failed to read file(s)");
668 if ( (s1
.length() != s2
.length()) ||
669 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
671 puts("ERROR: copy error!");
675 puts("File was copied ok.");
681 if ( !wxRemoveFile(filename2
) )
683 puts("ERROR: failed to remove the file");
691 // ----------------------------------------------------------------------------
693 // ----------------------------------------------------------------------------
697 #include "wx/confbase.h"
698 #include "wx/fileconf.h"
700 static const struct FileConfTestData
702 const wxChar
*name
; // value name
703 const wxChar
*value
; // the value from the file
706 { _T("value1"), _T("one") },
707 { _T("value2"), _T("two") },
708 { _T("novalue"), _T("default") },
711 static void TestFileConfRead()
713 puts("*** testing wxFileConfig loading/reading ***");
715 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
716 _T("testdata.fc"), wxEmptyString
,
717 wxCONFIG_USE_RELATIVE_PATH
);
719 // test simple reading
720 puts("\nReading config file:");
721 wxString
defValue(_T("default")), value
;
722 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
724 const FileConfTestData
& data
= fcTestData
[n
];
725 value
= fileconf
.Read(data
.name
, defValue
);
726 printf("\t%s = %s ", data
.name
, value
.c_str());
727 if ( value
== data
.value
)
733 printf("(ERROR: should be %s)\n", data
.value
);
737 // test enumerating the entries
738 puts("\nEnumerating all root entries:");
741 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
744 printf("\t%s = %s\n",
746 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
748 cont
= fileconf
.GetNextEntry(name
, dummy
);
752 #endif // TEST_FILECONF
754 // ----------------------------------------------------------------------------
756 // ----------------------------------------------------------------------------
760 #include "wx/filename.h"
762 static void DumpFileName(const wxFileName
& fn
)
764 wxString full
= fn
.GetFullPath();
766 wxString vol
, path
, name
, ext
;
767 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
769 wxPrintf(_T("Filename '%s' -> vol '%s', path '%s', name '%s', ext '%s'\n"),
770 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
773 static struct FileNameInfo
775 const wxChar
*fullname
;
776 const wxChar
*volume
;
785 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), TRUE
, wxPATH_UNIX
},
786 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), TRUE
, wxPATH_UNIX
},
787 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), TRUE
, wxPATH_UNIX
},
788 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), FALSE
, wxPATH_UNIX
},
789 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
790 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), TRUE
, wxPATH_UNIX
},
791 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), TRUE
, wxPATH_UNIX
},
792 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
793 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), TRUE
, wxPATH_UNIX
},
795 // Windows file names
796 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
797 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
798 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
799 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
800 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), TRUE
, wxPATH_DOS
},
801 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
804 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
805 { _T("Volume:Dir:Subdir:File"), _T("Volume"), _T("Dir:Subdir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
806 { _T("Volume:"), _T("Volume"), _T(""), _T(""), _T(""), TRUE
, wxPATH_MAC
},
807 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
808 { _T(":File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
809 { _T("File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
812 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
813 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
816 static void TestFileNameConstruction()
818 puts("*** testing wxFileName construction ***");
820 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
822 const FileNameInfo
& fni
= filenames
[n
];
824 wxFileName
fn(fni
.fullname
, fni
.format
);
826 wxString fullname
= fn
.GetFullPath(fni
.format
);
827 if ( fullname
!= fni
.fullname
)
829 printf("ERROR: fullname should be '%s'\n", fni
.fullname
);
832 bool isAbsolute
= fn
.IsAbsolute();
833 printf("'%s' is %s (%s)\n\t",
835 isAbsolute
? "absolute" : "relative",
836 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
838 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
840 puts("ERROR (couldn't be normalized)");
844 printf("normalized: '%s'\n", fn
.GetFullPath(fni
.format
).c_str());
851 static void TestFileNameSplit()
853 puts("*** testing wxFileName splitting ***");
855 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
857 const FileNameInfo
& fni
= filenames
[n
];
858 wxString volume
, path
, name
, ext
;
859 wxFileName::SplitPath(fni
.fullname
,
860 &volume
, &path
, &name
, &ext
, fni
.format
);
862 printf("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'",
864 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
866 if ( volume
!= fni
.volume
)
867 printf(" (ERROR: volume = '%s')", fni
.volume
);
868 if ( path
!= fni
.path
)
869 printf(" (ERROR: path = '%s')", fni
.path
);
870 if ( name
!= fni
.name
)
871 printf(" (ERROR: name = '%s')", fni
.name
);
872 if ( ext
!= fni
.ext
)
873 printf(" (ERROR: ext = '%s')", fni
.ext
);
879 static void TestFileNameTemp()
881 puts("*** testing wxFileName temp file creation ***");
883 static const char *tmpprefixes
[] =
889 "/tmp/foo/bar", // this one must be an error
892 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
894 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
897 printf("Prefix '%s'\t-> temp file '%s'\n",
898 tmpprefixes
[n
], path
.c_str());
900 if ( !wxRemoveFile(path
) )
902 wxLogWarning("Failed to remove temp file '%s'", path
.c_str());
908 static void TestFileNameMakeRelative()
910 puts("*** testing wxFileName::MakeRelativeTo() ***");
912 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
914 const FileNameInfo
& fni
= filenames
[n
];
916 wxFileName
fn(fni
.fullname
, fni
.format
);
918 // choose the base dir of the same format
920 switch ( fni
.format
)
932 // TODO: I don't know how this is supposed to work there
935 case wxPATH_NATIVE
: // make gcc happy
937 wxFAIL_MSG( "unexpected path format" );
940 printf("'%s' relative to '%s': ",
941 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
943 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
949 printf("'%s'\n", fn
.GetFullPath(fni
.format
).c_str());
954 static void TestFileNameComparison()
959 static void TestFileNameOperations()
964 static void TestFileNameCwd()
969 #endif // TEST_FILENAME
971 // ----------------------------------------------------------------------------
972 // wxFileName time functions
973 // ----------------------------------------------------------------------------
977 #include <wx/filename.h>
978 #include <wx/datetime.h>
980 static void TestFileGetTimes()
982 wxFileName
fn(_T("testdata.fc"));
984 wxDateTime dtAccess
, dtMod
, dtChange
;
985 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtChange
) )
987 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
991 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
993 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
994 wxPrintf(_T("Access: \t%s\n"), dtAccess
.Format(fmt
).c_str());
995 wxPrintf(_T("Mod/creation:\t%s\n"), dtMod
.Format(fmt
).c_str());
996 wxPrintf(_T("Change: \t%s\n"), dtChange
.Format(fmt
).c_str());
1000 static void TestFileSetTimes()
1002 wxFileName
fn(_T("testdata.fc"));
1006 wxPrintf(_T("ERROR: Touch() failed.\n"));
1010 #endif // TEST_FILETIME
1012 // ----------------------------------------------------------------------------
1014 // ----------------------------------------------------------------------------
1018 #include "wx/hash.h"
1022 Foo(int n_
) { n
= n_
; count
++; }
1027 static size_t count
;
1030 size_t Foo::count
= 0;
1032 WX_DECLARE_LIST(Foo
, wxListFoos
);
1033 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
1035 #include "wx/listimpl.cpp"
1037 WX_DEFINE_LIST(wxListFoos
);
1039 static void TestHash()
1041 puts("*** Testing wxHashTable ***\n");
1045 hash
.DeleteContents(TRUE
);
1047 printf("Hash created: %u foos in hash, %u foos totally\n",
1048 hash
.GetCount(), Foo::count
);
1050 static const int hashTestData
[] =
1052 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
1056 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1058 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
1061 printf("Hash filled: %u foos in hash, %u foos totally\n",
1062 hash
.GetCount(), Foo::count
);
1064 puts("Hash access test:");
1065 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1067 printf("\tGetting element with key %d, value %d: ",
1068 hashTestData
[n
], n
);
1069 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1072 printf("ERROR, not found.\n");
1076 printf("%d (%s)\n", foo
->n
,
1077 (size_t)foo
->n
== n
? "ok" : "ERROR");
1081 printf("\nTrying to get an element not in hash: ");
1083 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1085 puts("ERROR: found!");
1089 puts("ok (not found)");
1093 printf("Hash destroyed: %u foos left\n", Foo::count
);
1098 // ----------------------------------------------------------------------------
1100 // ----------------------------------------------------------------------------
1104 #include "wx/hashmap.h"
1106 // test compilation of basic map types
1107 WX_DECLARE_HASH_MAP( int*, int*, wxPointerHash
, wxPointerEqual
, myPtrHashMap
);
1108 WX_DECLARE_HASH_MAP( long, long, wxIntegerHash
, wxIntegerEqual
, myLongHashMap
);
1109 WX_DECLARE_HASH_MAP( unsigned long, unsigned, wxIntegerHash
, wxIntegerEqual
,
1110 myUnsignedHashMap
);
1111 WX_DECLARE_HASH_MAP( unsigned int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1113 WX_DECLARE_HASH_MAP( int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1115 WX_DECLARE_HASH_MAP( short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1117 WX_DECLARE_HASH_MAP( unsigned short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1119 WX_DECLARE_HASH_MAP( wxString
, wxString
, wxStringHash
, wxStringEqual
,
1122 typedef myStringHashMap::iterator Itor
;
1124 static void TestHashMap()
1126 puts("*** Testing wxHashMap ***\n");
1127 myStringHashMap
sh(0); // as small as possible
1130 const size_t count
= 10000;
1132 // init with some data
1133 for( i
= 0; i
< count
; ++i
)
1135 buf
.Printf(wxT("%d"), i
);
1136 sh
[buf
] = wxT("A") + buf
+ wxT("C");
1139 // test that insertion worked
1140 if( sh
.size() != count
)
1142 printf("*** ERROR: %u ELEMENTS, SHOULD BE %u ***\n", sh
.size(), count
);
1145 for( i
= 0; i
< count
; ++i
)
1147 buf
.Printf(wxT("%d"), i
);
1148 if( sh
[buf
] != wxT("A") + buf
+ wxT("C") )
1150 printf("*** ERROR INSERTION BROKEN! STOPPING NOW! ***\n");
1155 // check that iterators work
1157 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1161 printf("*** ERROR ITERATORS DO NOT TERMINATE! STOPPING NOW! ***\n");
1165 if( it
->second
!= sh
[it
->first
] )
1167 printf("*** ERROR ITERATORS BROKEN! STOPPING NOW! ***\n");
1172 if( sh
.size() != i
)
1174 printf("*** ERROR: %u ELEMENTS ITERATED, SHOULD BE %u ***\n", i
, count
);
1177 // test copy ctor, assignment operator
1178 myStringHashMap
h1( sh
), h2( 0 );
1181 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1183 if( h1
[it
->first
] != it
->second
)
1185 printf("*** ERROR: COPY CTOR BROKEN %s ***\n", it
->first
.c_str());
1188 if( h2
[it
->first
] != it
->second
)
1190 printf("*** ERROR: OPERATOR= BROKEN %s ***\n", it
->first
.c_str());
1195 for( i
= 0; i
< count
; ++i
)
1197 buf
.Printf(wxT("%d"), i
);
1198 size_t sz
= sh
.size();
1200 // test find() and erase(it)
1203 it
= sh
.find( buf
);
1204 if( it
!= sh
.end() )
1208 if( sh
.find( buf
) != sh
.end() )
1210 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1214 printf("*** ERROR: CANT FIND ELEMENT %u ***\n", i
);
1219 size_t c
= sh
.erase( buf
);
1221 printf("*** ERROR: SHOULD RETURN 1 ***\n");
1223 if( sh
.find( buf
) != sh
.end() )
1225 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1229 // count should decrease
1230 if( sh
.size() != sz
- 1 )
1232 printf("*** ERROR: COUNT DID NOT DECREASE ***\n");
1236 printf("*** Finished testing wxHashMap ***\n");
1241 // ----------------------------------------------------------------------------
1243 // ----------------------------------------------------------------------------
1247 #include "wx/list.h"
1249 WX_DECLARE_LIST(Bar
, wxListBars
);
1250 #include "wx/listimpl.cpp"
1251 WX_DEFINE_LIST(wxListBars
);
1253 static void TestListCtor()
1255 puts("*** Testing wxList construction ***\n");
1259 list1
.Append(new Bar(_T("first")));
1260 list1
.Append(new Bar(_T("second")));
1262 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1263 list1
.GetCount(), Bar::GetNumber());
1268 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1269 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1271 list1
.DeleteContents(TRUE
);
1274 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1279 // ----------------------------------------------------------------------------
1281 // ----------------------------------------------------------------------------
1285 #include "wx/intl.h"
1286 #include "wx/utils.h" // for wxSetEnv
1288 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1290 // find the name of the language from its value
1291 static const char *GetLangName(int lang
)
1293 static const char *languageNames
[] =
1314 "ARABIC_SAUDI_ARABIA",
1339 "CHINESE_SIMPLIFIED",
1340 "CHINESE_TRADITIONAL",
1343 "CHINESE_SINGAPORE",
1354 "ENGLISH_AUSTRALIA",
1358 "ENGLISH_CARIBBEAN",
1362 "ENGLISH_NEW_ZEALAND",
1363 "ENGLISH_PHILIPPINES",
1364 "ENGLISH_SOUTH_AFRICA",
1376 "FRENCH_LUXEMBOURG",
1385 "GERMAN_LIECHTENSTEIN",
1386 "GERMAN_LUXEMBOURG",
1427 "MALAY_BRUNEI_DARUSSALAM",
1439 "NORWEGIAN_NYNORSK",
1446 "PORTUGUESE_BRAZILIAN",
1471 "SPANISH_ARGENTINA",
1475 "SPANISH_COSTA_RICA",
1476 "SPANISH_DOMINICAN_REPUBLIC",
1478 "SPANISH_EL_SALVADOR",
1479 "SPANISH_GUATEMALA",
1483 "SPANISH_NICARAGUA",
1487 "SPANISH_PUERTO_RICO",
1490 "SPANISH_VENEZUELA",
1527 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1528 return languageNames
[lang
];
1533 static void TestDefaultLang()
1535 puts("*** Testing wxLocale::GetSystemLanguage ***");
1537 static const wxChar
*langStrings
[] =
1539 NULL
, // system default
1546 _T("de_DE.iso88591"),
1548 _T("?"), // invalid lang spec
1549 _T("klingonese"), // I bet on some systems it does exist...
1552 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1553 wxLocale::GetSystemEncodingName().c_str(),
1554 wxLocale::GetSystemEncoding());
1556 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1558 const char *langStr
= langStrings
[n
];
1561 // FIXME: this doesn't do anything at all under Windows, we need
1562 // to create a new wxLocale!
1563 wxSetEnv(_T("LC_ALL"), langStr
);
1566 int lang
= gs_localeDefault
.GetSystemLanguage();
1567 printf("Locale for '%s' is %s.\n",
1568 langStr
? langStr
: "system default", GetLangName(lang
));
1572 #endif // TEST_LOCALE
1574 // ----------------------------------------------------------------------------
1576 // ----------------------------------------------------------------------------
1580 #include "wx/mimetype.h"
1582 static void TestMimeEnum()
1584 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1586 wxArrayString mimetypes
;
1588 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1590 printf("*** All %u known filetypes: ***\n", count
);
1595 for ( size_t n
= 0; n
< count
; n
++ )
1597 wxFileType
*filetype
=
1598 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1601 printf("nothing known about the filetype '%s'!\n",
1602 mimetypes
[n
].c_str());
1606 filetype
->GetDescription(&desc
);
1607 filetype
->GetExtensions(exts
);
1609 filetype
->GetIcon(NULL
);
1612 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1615 extsAll
<< _T(", ");
1619 printf("\t%s: %s (%s)\n",
1620 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1626 static void TestMimeOverride()
1628 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1630 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1631 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1633 if ( wxFile::Exists(mailcap
) )
1634 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1636 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1638 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1641 if ( wxFile::Exists(mimetypes
) )
1642 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1644 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1646 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1652 static void TestMimeFilename()
1654 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1656 static const wxChar
*filenames
[] =
1663 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1665 const wxString fname
= filenames
[n
];
1666 wxString ext
= fname
.AfterLast(_T('.'));
1667 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1670 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1675 if ( !ft
->GetDescription(&desc
) )
1676 desc
= _T("<no description>");
1679 if ( !ft
->GetOpenCommand(&cmd
,
1680 wxFileType::MessageParameters(fname
, _T(""))) )
1681 cmd
= _T("<no command available>");
1683 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1684 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1693 static void TestMimeAssociate()
1695 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1697 wxFileTypeInfo
ftInfo(
1698 _T("application/x-xyz"),
1699 _T("xyzview '%s'"), // open cmd
1700 _T(""), // print cmd
1701 _T("XYZ File") // description
1702 _T(".xyz"), // extensions
1703 NULL
// end of extensions
1705 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1707 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1710 wxPuts(_T("ERROR: failed to create association!"));
1714 // TODO: read it back
1723 // ----------------------------------------------------------------------------
1724 // misc information functions
1725 // ----------------------------------------------------------------------------
1727 #ifdef TEST_INFO_FUNCTIONS
1729 #include "wx/utils.h"
1731 static void TestDiskInfo()
1733 puts("*** Testing wxGetDiskSpace() ***");
1738 printf("\nEnter a directory name: ");
1739 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1742 // kill the last '\n'
1743 pathname
[strlen(pathname
) - 1] = 0;
1745 wxLongLong total
, free
;
1746 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1748 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1752 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1753 (total
/ 1024).ToString().c_str(),
1754 (free
/ 1024).ToString().c_str(),
1760 static void TestOsInfo()
1762 puts("*** Testing OS info functions ***\n");
1765 wxGetOsVersion(&major
, &minor
);
1766 printf("Running under: %s, version %d.%d\n",
1767 wxGetOsDescription().c_str(), major
, minor
);
1769 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1771 printf("Host name is %s (%s).\n",
1772 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1777 static void TestUserInfo()
1779 puts("*** Testing user info functions ***\n");
1781 printf("User id is:\t%s\n", wxGetUserId().c_str());
1782 printf("User name is:\t%s\n", wxGetUserName().c_str());
1783 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1784 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1789 #endif // TEST_INFO_FUNCTIONS
1791 // ----------------------------------------------------------------------------
1793 // ----------------------------------------------------------------------------
1795 #ifdef TEST_LONGLONG
1797 #include "wx/longlong.h"
1798 #include "wx/timer.h"
1800 // make a 64 bit number from 4 16 bit ones
1801 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1803 // get a random 64 bit number
1804 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1806 static const long testLongs
[] =
1817 #if wxUSE_LONGLONG_WX
1818 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1819 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1820 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1821 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1822 #endif // wxUSE_LONGLONG_WX
1824 static void TestSpeed()
1826 static const long max
= 100000000;
1833 for ( n
= 0; n
< max
; n
++ )
1838 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1841 #if wxUSE_LONGLONG_NATIVE
1846 for ( n
= 0; n
< max
; n
++ )
1851 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1853 #endif // wxUSE_LONGLONG_NATIVE
1859 for ( n
= 0; n
< max
; n
++ )
1864 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1868 static void TestLongLongConversion()
1870 puts("*** Testing wxLongLong conversions ***\n");
1874 for ( size_t n
= 0; n
< 100000; n
++ )
1878 #if wxUSE_LONGLONG_NATIVE
1879 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1881 wxASSERT_MSG( a
== b
, "conversions failure" );
1883 puts("Can't do it without native long long type, test skipped.");
1886 #endif // wxUSE_LONGLONG_NATIVE
1888 if ( !(nTested
% 1000) )
1900 static void TestMultiplication()
1902 puts("*** Testing wxLongLong multiplication ***\n");
1906 for ( size_t n
= 0; n
< 100000; n
++ )
1911 #if wxUSE_LONGLONG_NATIVE
1912 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1913 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1915 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1916 #else // !wxUSE_LONGLONG_NATIVE
1917 puts("Can't do it without native long long type, test skipped.");
1920 #endif // wxUSE_LONGLONG_NATIVE
1922 if ( !(nTested
% 1000) )
1934 static void TestDivision()
1936 puts("*** Testing wxLongLong division ***\n");
1940 for ( size_t n
= 0; n
< 100000; n
++ )
1942 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1943 // multiplication will not overflow)
1944 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1946 // get a random long (not wxLongLong for now) to divide it with
1951 #if wxUSE_LONGLONG_NATIVE
1952 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1954 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1955 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1956 #else // !wxUSE_LONGLONG_NATIVE
1957 // verify the result
1958 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1959 #endif // wxUSE_LONGLONG_NATIVE
1961 if ( !(nTested
% 1000) )
1973 static void TestAddition()
1975 puts("*** Testing wxLongLong addition ***\n");
1979 for ( size_t n
= 0; n
< 100000; n
++ )
1985 #if wxUSE_LONGLONG_NATIVE
1986 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1987 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1988 "addition failure" );
1989 #else // !wxUSE_LONGLONG_NATIVE
1990 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1991 #endif // wxUSE_LONGLONG_NATIVE
1993 if ( !(nTested
% 1000) )
2005 static void TestBitOperations()
2007 puts("*** Testing wxLongLong bit operation ***\n");
2011 for ( size_t n
= 0; n
< 100000; n
++ )
2015 #if wxUSE_LONGLONG_NATIVE
2016 for ( size_t n
= 0; n
< 33; n
++ )
2019 #else // !wxUSE_LONGLONG_NATIVE
2020 puts("Can't do it without native long long type, test skipped.");
2023 #endif // wxUSE_LONGLONG_NATIVE
2025 if ( !(nTested
% 1000) )
2037 static void TestLongLongComparison()
2039 #if wxUSE_LONGLONG_WX
2040 puts("*** Testing wxLongLong comparison ***\n");
2042 static const long ls
[2] =
2048 wxLongLongWx lls
[2];
2052 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2056 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
2058 res
= lls
[m
] > testLongs
[n
];
2059 printf("0x%lx > 0x%lx is %s (%s)\n",
2060 ls
[m
], testLongs
[n
], res
? "true" : "false",
2061 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
2063 res
= lls
[m
] < testLongs
[n
];
2064 printf("0x%lx < 0x%lx is %s (%s)\n",
2065 ls
[m
], testLongs
[n
], res
? "true" : "false",
2066 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
2068 res
= lls
[m
] == testLongs
[n
];
2069 printf("0x%lx == 0x%lx is %s (%s)\n",
2070 ls
[m
], testLongs
[n
], res
? "true" : "false",
2071 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
2074 #endif // wxUSE_LONGLONG_WX
2077 static void TestLongLongPrint()
2079 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
2081 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2083 wxLongLong ll
= testLongs
[n
];
2084 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
2087 wxLongLong
ll(0x12345678, 0x87654321);
2088 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2091 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2097 #endif // TEST_LONGLONG
2099 // ----------------------------------------------------------------------------
2101 // ----------------------------------------------------------------------------
2103 #ifdef TEST_PATHLIST
2105 static void TestPathList()
2107 puts("*** Testing wxPathList ***\n");
2109 wxPathList pathlist
;
2110 pathlist
.AddEnvList("PATH");
2111 wxString path
= pathlist
.FindValidPath("ls");
2114 printf("ERROR: command not found in the path.\n");
2118 printf("Command found in the path as '%s'.\n", path
.c_str());
2122 #endif // TEST_PATHLIST
2124 // ----------------------------------------------------------------------------
2125 // regular expressions
2126 // ----------------------------------------------------------------------------
2130 #include "wx/regex.h"
2132 static void TestRegExCompile()
2134 wxPuts(_T("*** Testing RE compilation ***\n"));
2136 static struct RegExCompTestData
2138 const wxChar
*pattern
;
2140 } regExCompTestData
[] =
2142 { _T("foo"), TRUE
},
2143 { _T("foo("), FALSE
},
2144 { _T("foo(bar"), FALSE
},
2145 { _T("foo(bar)"), TRUE
},
2146 { _T("foo["), FALSE
},
2147 { _T("foo[bar"), FALSE
},
2148 { _T("foo[bar]"), TRUE
},
2149 { _T("foo{"), TRUE
},
2150 { _T("foo{1"), FALSE
},
2151 { _T("foo{bar"), TRUE
},
2152 { _T("foo{1}"), TRUE
},
2153 { _T("foo{1,2}"), TRUE
},
2154 { _T("foo{bar}"), TRUE
},
2155 { _T("foo*"), TRUE
},
2156 { _T("foo**"), FALSE
},
2157 { _T("foo+"), TRUE
},
2158 { _T("foo++"), FALSE
},
2159 { _T("foo?"), TRUE
},
2160 { _T("foo??"), FALSE
},
2161 { _T("foo?+"), FALSE
},
2165 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
2167 const RegExCompTestData
& data
= regExCompTestData
[n
];
2168 bool ok
= re
.Compile(data
.pattern
);
2170 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
2172 ok
? _T("") : _T("not "),
2173 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2177 static void TestRegExMatch()
2179 wxPuts(_T("*** Testing RE matching ***\n"));
2181 static struct RegExMatchTestData
2183 const wxChar
*pattern
;
2186 } regExMatchTestData
[] =
2188 { _T("foo"), _T("bar"), FALSE
},
2189 { _T("foo"), _T("foobar"), TRUE
},
2190 { _T("^foo"), _T("foobar"), TRUE
},
2191 { _T("^foo"), _T("barfoo"), FALSE
},
2192 { _T("bar$"), _T("barbar"), TRUE
},
2193 { _T("bar$"), _T("barbar "), FALSE
},
2196 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
2198 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
2200 wxRegEx
re(data
.pattern
);
2201 bool ok
= re
.Matches(data
.text
);
2203 wxPrintf(_T("'%s' %s %s (%s)\n"),
2205 ok
? _T("matches") : _T("doesn't match"),
2207 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2211 static void TestRegExSubmatch()
2213 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2215 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2216 if ( !re
.IsValid() )
2218 wxPuts(_T("ERROR: compilation failed."));
2222 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2224 if ( !re
.Matches(text
) )
2226 wxPuts(_T("ERROR: match expected."));
2230 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2232 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2233 re
.GetMatch(text
, 3).c_str(),
2234 re
.GetMatch(text
, 2).c_str(),
2235 re
.GetMatch(text
, 4).c_str(),
2236 re
.GetMatch(text
, 1).c_str());
2240 static void TestRegExReplacement()
2242 wxPuts(_T("*** Testing RE replacement ***"));
2244 static struct RegExReplTestData
2248 const wxChar
*result
;
2250 } regExReplTestData
[] =
2252 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2253 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2254 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2255 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2256 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2257 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2258 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2261 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2262 wxRegEx
re(pattern
);
2264 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2266 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2268 const RegExReplTestData
& data
= regExReplTestData
[n
];
2270 wxString text
= data
.text
;
2271 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2273 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2274 data
.text
, data
.repl
,
2275 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2277 if ( text
== data
.result
&& nRepl
== data
.count
)
2283 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2284 data
.count
, data
.result
);
2289 static void TestRegExInteractive()
2291 wxPuts(_T("*** Testing RE interactively ***"));
2296 printf("\nEnter a pattern: ");
2297 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2300 // kill the last '\n'
2301 pattern
[strlen(pattern
) - 1] = 0;
2304 if ( !re
.Compile(pattern
) )
2312 printf("Enter text to match: ");
2313 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2316 // kill the last '\n'
2317 text
[strlen(text
) - 1] = 0;
2319 if ( !re
.Matches(text
) )
2321 printf("No match.\n");
2325 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2328 for ( size_t n
= 1; ; n
++ )
2330 if ( !re
.GetMatch(&start
, &len
, n
) )
2335 printf("Subexpr %u matched '%s'\n",
2336 n
, wxString(text
+ start
, len
).c_str());
2343 #endif // TEST_REGEX
2345 // ----------------------------------------------------------------------------
2346 // registry and related stuff
2347 // ----------------------------------------------------------------------------
2349 // this is for MSW only
2352 #undef TEST_REGISTRY
2357 #include "wx/confbase.h"
2358 #include "wx/msw/regconf.h"
2360 static void TestRegConfWrite()
2362 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2363 regconf
.Write(_T("Hello"), wxString(_T("world")));
2366 #endif // TEST_REGCONF
2368 #ifdef TEST_REGISTRY
2370 #include "wx/msw/registry.h"
2372 // I chose this one because I liked its name, but it probably only exists under
2374 static const wxChar
*TESTKEY
=
2375 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2377 static void TestRegistryRead()
2379 puts("*** testing registry reading ***");
2381 wxRegKey
key(TESTKEY
);
2382 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2385 puts("ERROR: test key can't be opened, aborting test.");
2390 size_t nSubKeys
, nValues
;
2391 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2393 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2396 printf("Enumerating values:\n");
2400 bool cont
= key
.GetFirstValue(value
, dummy
);
2403 printf("Value '%s': type ", value
.c_str());
2404 switch ( key
.GetValueType(value
) )
2406 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2407 case wxRegKey::Type_String
: printf("SZ"); break;
2408 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2409 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2410 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2411 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2412 default: printf("other (unknown)"); break;
2415 printf(", value = ");
2416 if ( key
.IsNumericValue(value
) )
2419 key
.QueryValue(value
, &val
);
2425 key
.QueryValue(value
, val
);
2426 printf("'%s'", val
.c_str());
2428 key
.QueryRawValue(value
, val
);
2429 printf(" (raw value '%s')", val
.c_str());
2434 cont
= key
.GetNextValue(value
, dummy
);
2438 static void TestRegistryAssociation()
2441 The second call to deleteself genertaes an error message, with a
2442 messagebox saying .flo is crucial to system operation, while the .ddf
2443 call also fails, but with no error message
2448 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2450 key
= "ddxf_auto_file" ;
2451 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2453 key
= "ddxf_auto_file" ;
2454 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2457 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2459 key
= "program \"%1\"" ;
2461 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2463 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2465 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2467 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2471 #endif // TEST_REGISTRY
2473 // ----------------------------------------------------------------------------
2475 // ----------------------------------------------------------------------------
2479 #include "wx/socket.h"
2480 #include "wx/protocol/protocol.h"
2481 #include "wx/protocol/http.h"
2483 static void TestSocketServer()
2485 puts("*** Testing wxSocketServer ***\n");
2487 static const int PORT
= 3000;
2492 wxSocketServer
*server
= new wxSocketServer(addr
);
2493 if ( !server
->Ok() )
2495 puts("ERROR: failed to bind");
2502 printf("Server: waiting for connection on port %d...\n", PORT
);
2504 wxSocketBase
*socket
= server
->Accept();
2507 puts("ERROR: wxSocketServer::Accept() failed.");
2511 puts("Server: got a client.");
2513 server
->SetTimeout(60); // 1 min
2515 while ( socket
->IsConnected() )
2521 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2523 // don't log error if the client just close the connection
2524 if ( socket
->IsConnected() )
2526 puts("ERROR: in wxSocket::Read.");
2546 printf("Server: got '%s'.\n", s
.c_str());
2547 if ( s
== _T("bye") )
2554 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2555 socket
->Write("\r\n", 2);
2556 printf("Server: wrote '%s'.\n", s
.c_str());
2559 puts("Server: lost a client.");
2564 // same as "delete server" but is consistent with GUI programs
2568 static void TestSocketClient()
2570 puts("*** Testing wxSocketClient ***\n");
2572 static const char *hostname
= "www.wxwindows.org";
2575 addr
.Hostname(hostname
);
2578 printf("--- Attempting to connect to %s:80...\n", hostname
);
2580 wxSocketClient client
;
2581 if ( !client
.Connect(addr
) )
2583 printf("ERROR: failed to connect to %s\n", hostname
);
2587 printf("--- Connected to %s:%u...\n",
2588 addr
.Hostname().c_str(), addr
.Service());
2592 // could use simply "GET" here I suppose
2594 wxString::Format("GET http://%s/\r\n", hostname
);
2595 client
.Write(cmdGet
, cmdGet
.length());
2596 printf("--- Sent command '%s' to the server\n",
2597 MakePrintable(cmdGet
).c_str());
2598 client
.Read(buf
, WXSIZEOF(buf
));
2599 printf("--- Server replied:\n%s", buf
);
2603 #endif // TEST_SOCKETS
2605 // ----------------------------------------------------------------------------
2607 // ----------------------------------------------------------------------------
2611 #include "wx/protocol/ftp.h"
2615 #define FTP_ANONYMOUS
2617 #ifdef FTP_ANONYMOUS
2618 static const char *directory
= "/pub";
2619 static const char *filename
= "welcome.msg";
2621 static const char *directory
= "/etc";
2622 static const char *filename
= "issue";
2625 static bool TestFtpConnect()
2627 puts("*** Testing FTP connect ***");
2629 #ifdef FTP_ANONYMOUS
2630 static const char *hostname
= "ftp.wxwindows.org";
2632 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2633 #else // !FTP_ANONYMOUS
2634 static const char *hostname
= "localhost";
2637 fgets(user
, WXSIZEOF(user
), stdin
);
2638 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2642 printf("Password for %s: ", password
);
2643 fgets(password
, WXSIZEOF(password
), stdin
);
2644 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2645 ftp
.SetPassword(password
);
2647 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2648 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2650 if ( !ftp
.Connect(hostname
) )
2652 printf("ERROR: failed to connect to %s\n", hostname
);
2658 printf("--- Connected to %s, current directory is '%s'\n",
2659 hostname
, ftp
.Pwd().c_str());
2665 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2666 static void TestFtpWuFtpd()
2669 static const char *hostname
= "ftp.eudora.com";
2670 if ( !ftp
.Connect(hostname
) )
2672 printf("ERROR: failed to connect to %s\n", hostname
);
2676 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2677 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2680 printf("ERROR: couldn't get input stream for %s\n", filename
);
2684 size_t size
= in
->StreamSize();
2685 printf("Reading file %s (%u bytes)...", filename
, size
);
2687 char *data
= new char[size
];
2688 if ( !in
->Read(data
, size
) )
2690 puts("ERROR: read error");
2694 printf("Successfully retrieved the file.\n");
2703 static void TestFtpList()
2705 puts("*** Testing wxFTP file listing ***\n");
2708 if ( !ftp
.ChDir(directory
) )
2710 printf("ERROR: failed to cd to %s\n", directory
);
2713 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2715 // test NLIST and LIST
2716 wxArrayString files
;
2717 if ( !ftp
.GetFilesList(files
) )
2719 puts("ERROR: failed to get NLIST of files");
2723 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2724 size_t count
= files
.GetCount();
2725 for ( size_t n
= 0; n
< count
; n
++ )
2727 printf("\t%s\n", files
[n
].c_str());
2729 puts("End of the file list");
2732 if ( !ftp
.GetDirList(files
) )
2734 puts("ERROR: failed to get LIST of files");
2738 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2739 size_t count
= files
.GetCount();
2740 for ( size_t n
= 0; n
< count
; n
++ )
2742 printf("\t%s\n", files
[n
].c_str());
2744 puts("End of the file list");
2747 if ( !ftp
.ChDir(_T("..")) )
2749 puts("ERROR: failed to cd to ..");
2752 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2755 static void TestFtpDownload()
2757 puts("*** Testing wxFTP download ***\n");
2760 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2763 printf("ERROR: couldn't get input stream for %s\n", filename
);
2767 size_t size
= in
->StreamSize();
2768 printf("Reading file %s (%u bytes)...", filename
, size
);
2771 char *data
= new char[size
];
2772 if ( !in
->Read(data
, size
) )
2774 puts("ERROR: read error");
2778 printf("\nContents of %s:\n%s\n", filename
, data
);
2786 static void TestFtpFileSize()
2788 puts("*** Testing FTP SIZE command ***");
2790 if ( !ftp
.ChDir(directory
) )
2792 printf("ERROR: failed to cd to %s\n", directory
);
2795 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2797 if ( ftp
.FileExists(filename
) )
2799 int size
= ftp
.GetFileSize(filename
);
2801 printf("ERROR: couldn't get size of '%s'\n", filename
);
2803 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2807 printf("ERROR: '%s' doesn't exist\n", filename
);
2811 static void TestFtpMisc()
2813 puts("*** Testing miscellaneous wxFTP functions ***");
2815 if ( ftp
.SendCommand("STAT") != '2' )
2817 puts("ERROR: STAT failed");
2821 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2824 if ( ftp
.SendCommand("HELP SITE") != '2' )
2826 puts("ERROR: HELP SITE failed");
2830 printf("The list of site-specific commands:\n\n%s\n",
2831 ftp
.GetLastResult().c_str());
2835 static void TestFtpInteractive()
2837 puts("\n*** Interactive wxFTP test ***");
2843 printf("Enter FTP command: ");
2844 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2847 // kill the last '\n'
2848 buf
[strlen(buf
) - 1] = 0;
2850 // special handling of LIST and NLST as they require data connection
2851 wxString
start(buf
, 4);
2853 if ( start
== "LIST" || start
== "NLST" )
2856 if ( strlen(buf
) > 4 )
2859 wxArrayString files
;
2860 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2862 printf("ERROR: failed to get %s of files\n", start
.c_str());
2866 printf("--- %s of '%s' under '%s':\n",
2867 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2868 size_t count
= files
.GetCount();
2869 for ( size_t n
= 0; n
< count
; n
++ )
2871 printf("\t%s\n", files
[n
].c_str());
2873 puts("--- End of the file list");
2878 char ch
= ftp
.SendCommand(buf
);
2879 printf("Command %s", ch
? "succeeded" : "failed");
2882 printf(" (return code %c)", ch
);
2885 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2889 puts("\n*** done ***");
2892 static void TestFtpUpload()
2894 puts("*** Testing wxFTP uploading ***\n");
2897 static const char *file1
= "test1";
2898 static const char *file2
= "test2";
2899 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2902 printf("--- Uploading to %s ---\n", file1
);
2903 out
->Write("First hello", 11);
2907 // send a command to check the remote file
2908 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2910 printf("ERROR: STAT %s failed\n", file1
);
2914 printf("STAT %s returned:\n\n%s\n",
2915 file1
, ftp
.GetLastResult().c_str());
2918 out
= ftp
.GetOutputStream(file2
);
2921 printf("--- Uploading to %s ---\n", file1
);
2922 out
->Write("Second hello", 12);
2929 // ----------------------------------------------------------------------------
2931 // ----------------------------------------------------------------------------
2935 #include "wx/wfstream.h"
2936 #include "wx/mstream.h"
2938 static void TestFileStream()
2940 puts("*** Testing wxFileInputStream ***");
2942 static const wxChar
*filename
= _T("testdata.fs");
2944 wxFileOutputStream
fsOut(filename
);
2945 fsOut
.Write("foo", 3);
2948 wxFileInputStream
fsIn(filename
);
2949 printf("File stream size: %u\n", fsIn
.GetSize());
2950 while ( !fsIn
.Eof() )
2952 putchar(fsIn
.GetC());
2955 if ( !wxRemoveFile(filename
) )
2957 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2960 puts("\n*** wxFileInputStream test done ***");
2963 static void TestMemoryStream()
2965 puts("*** Testing wxMemoryInputStream ***");
2968 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2970 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2971 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2972 while ( !memInpStream
.Eof() )
2974 putchar(memInpStream
.GetC());
2977 puts("\n*** wxMemoryInputStream test done ***");
2980 #endif // TEST_STREAMS
2982 // ----------------------------------------------------------------------------
2984 // ----------------------------------------------------------------------------
2988 #include "wx/timer.h"
2989 #include "wx/utils.h"
2991 static void TestStopWatch()
2993 puts("*** Testing wxStopWatch ***\n");
2996 printf("Sleeping 3 seconds...");
2998 printf("\telapsed time: %ldms\n", sw
.Time());
3001 printf("Sleeping 2 more seconds...");
3003 printf("\telapsed time: %ldms\n", sw
.Time());
3006 printf("And 3 more seconds...");
3008 printf("\telapsed time: %ldms\n", sw
.Time());
3011 puts("\nChecking for 'backwards clock' bug...");
3012 for ( size_t n
= 0; n
< 70; n
++ )
3016 for ( size_t m
= 0; m
< 100000; m
++ )
3018 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
3020 puts("\ntime is negative - ERROR!");
3030 #endif // TEST_TIMER
3032 // ----------------------------------------------------------------------------
3034 // ----------------------------------------------------------------------------
3038 #include "wx/vcard.h"
3040 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
3043 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
3047 wxString(_T('\t'), level
).c_str(),
3048 vcObj
->GetName().c_str());
3051 switch ( vcObj
->GetType() )
3053 case wxVCardObject::String
:
3054 case wxVCardObject::UString
:
3057 vcObj
->GetValue(&val
);
3058 value
<< _T('"') << val
<< _T('"');
3062 case wxVCardObject::Int
:
3065 vcObj
->GetValue(&i
);
3066 value
.Printf(_T("%u"), i
);
3070 case wxVCardObject::Long
:
3073 vcObj
->GetValue(&l
);
3074 value
.Printf(_T("%lu"), l
);
3078 case wxVCardObject::None
:
3081 case wxVCardObject::Object
:
3082 value
= _T("<node>");
3086 value
= _T("<unknown value type>");
3090 printf(" = %s", value
.c_str());
3093 DumpVObject(level
+ 1, *vcObj
);
3096 vcObj
= vcard
.GetNextProp(&cookie
);
3100 static void DumpVCardAddresses(const wxVCard
& vcard
)
3102 puts("\nShowing all addresses from vCard:\n");
3106 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3110 int flags
= addr
->GetFlags();
3111 if ( flags
& wxVCardAddress::Domestic
)
3113 flagsStr
<< _T("domestic ");
3115 if ( flags
& wxVCardAddress::Intl
)
3117 flagsStr
<< _T("international ");
3119 if ( flags
& wxVCardAddress::Postal
)
3121 flagsStr
<< _T("postal ");
3123 if ( flags
& wxVCardAddress::Parcel
)
3125 flagsStr
<< _T("parcel ");
3127 if ( flags
& wxVCardAddress::Home
)
3129 flagsStr
<< _T("home ");
3131 if ( flags
& wxVCardAddress::Work
)
3133 flagsStr
<< _T("work ");
3136 printf("Address %u:\n"
3138 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3141 addr
->GetPostOffice().c_str(),
3142 addr
->GetExtAddress().c_str(),
3143 addr
->GetStreet().c_str(),
3144 addr
->GetLocality().c_str(),
3145 addr
->GetRegion().c_str(),
3146 addr
->GetPostalCode().c_str(),
3147 addr
->GetCountry().c_str()
3151 addr
= vcard
.GetNextAddress(&cookie
);
3155 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3157 puts("\nShowing all phone numbers from vCard:\n");
3161 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3165 int flags
= phone
->GetFlags();
3166 if ( flags
& wxVCardPhoneNumber::Voice
)
3168 flagsStr
<< _T("voice ");
3170 if ( flags
& wxVCardPhoneNumber::Fax
)
3172 flagsStr
<< _T("fax ");
3174 if ( flags
& wxVCardPhoneNumber::Cellular
)
3176 flagsStr
<< _T("cellular ");
3178 if ( flags
& wxVCardPhoneNumber::Modem
)
3180 flagsStr
<< _T("modem ");
3182 if ( flags
& wxVCardPhoneNumber::Home
)
3184 flagsStr
<< _T("home ");
3186 if ( flags
& wxVCardPhoneNumber::Work
)
3188 flagsStr
<< _T("work ");
3191 printf("Phone number %u:\n"
3196 phone
->GetNumber().c_str()
3200 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3204 static void TestVCardRead()
3206 puts("*** Testing wxVCard reading ***\n");
3208 wxVCard
vcard(_T("vcard.vcf"));
3209 if ( !vcard
.IsOk() )
3211 puts("ERROR: couldn't load vCard.");
3215 // read individual vCard properties
3216 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3220 vcObj
->GetValue(&value
);
3225 value
= _T("<none>");
3228 printf("Full name retrieved directly: %s\n", value
.c_str());
3231 if ( !vcard
.GetFullName(&value
) )
3233 value
= _T("<none>");
3236 printf("Full name from wxVCard API: %s\n", value
.c_str());
3238 // now show how to deal with multiply occuring properties
3239 DumpVCardAddresses(vcard
);
3240 DumpVCardPhoneNumbers(vcard
);
3242 // and finally show all
3243 puts("\nNow dumping the entire vCard:\n"
3244 "-----------------------------\n");
3246 DumpVObject(0, vcard
);
3250 static void TestVCardWrite()
3252 puts("*** Testing wxVCard writing ***\n");
3255 if ( !vcard
.IsOk() )
3257 puts("ERROR: couldn't create vCard.");
3262 vcard
.SetName("Zeitlin", "Vadim");
3263 vcard
.SetFullName("Vadim Zeitlin");
3264 vcard
.SetOrganization("wxWindows", "R&D");
3266 // just dump the vCard back
3267 puts("Entire vCard follows:\n");
3268 puts(vcard
.Write());
3272 #endif // TEST_VCARD
3274 // ----------------------------------------------------------------------------
3275 // wide char (Unicode) support
3276 // ----------------------------------------------------------------------------
3280 #include "wx/strconv.h"
3281 #include "wx/fontenc.h"
3282 #include "wx/encconv.h"
3283 #include "wx/buffer.h"
3285 static void TestUtf8()
3287 puts("*** Testing UTF8 support ***\n");
3289 static const char textInUtf8
[] =
3291 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3292 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3293 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3294 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3295 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3296 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3297 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3302 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3304 puts("ERROR: UTF-8 decoding failed.");
3308 // using wxEncodingConverter
3310 wxEncodingConverter ec
;
3311 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3312 ec
.Convert(wbuf
, buf
);
3313 #else // using wxCSConv
3314 wxCSConv
conv(_T("koi8-r"));
3315 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3317 puts("ERROR: conversion to KOI8-R failed.");
3322 printf("The resulting string (in koi8-r): %s\n", buf
);
3326 #endif // TEST_WCHAR
3328 // ----------------------------------------------------------------------------
3330 // ----------------------------------------------------------------------------
3334 #include "wx/filesys.h"
3335 #include "wx/fs_zip.h"
3336 #include "wx/zipstrm.h"
3338 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3340 static void TestZipStreamRead()
3342 puts("*** Testing ZIP reading ***\n");
3344 static const wxChar
*filename
= _T("foo");
3345 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3346 printf("Archive size: %u\n", istr
.GetSize());
3348 printf("Dumping the file '%s':\n", filename
);
3349 while ( !istr
.Eof() )
3351 putchar(istr
.GetC());
3355 puts("\n----- done ------");
3358 static void DumpZipDirectory(wxFileSystem
& fs
,
3359 const wxString
& dir
,
3360 const wxString
& indent
)
3362 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3363 TESTFILE_ZIP
, dir
.c_str());
3364 wxString wildcard
= prefix
+ _T("/*");
3366 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3367 while ( !dirname
.empty() )
3369 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3371 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3376 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3378 DumpZipDirectory(fs
, dirname
,
3379 indent
+ wxString(_T(' '), 4));
3381 dirname
= fs
.FindNext();
3384 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3385 while ( !filename
.empty() )
3387 if ( !filename
.StartsWith(prefix
, &filename
) )
3389 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3394 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3396 filename
= fs
.FindNext();
3400 static void TestZipFileSystem()
3402 puts("*** Testing ZIP file system ***\n");
3404 wxFileSystem::AddHandler(new wxZipFSHandler
);
3406 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3408 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3413 // ----------------------------------------------------------------------------
3415 // ----------------------------------------------------------------------------
3419 #include "wx/zstream.h"
3420 #include "wx/wfstream.h"
3422 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3423 static const char *TEST_DATA
= "hello and hello again";
3425 static void TestZlibStreamWrite()
3427 puts("*** Testing Zlib stream reading ***\n");
3429 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3430 wxZlibOutputStream
ostr(fileOutStream
, 0);
3431 printf("Compressing the test string... ");
3432 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3435 puts("(ERROR: failed)");
3442 puts("\n----- done ------");
3445 static void TestZlibStreamRead()
3447 puts("*** Testing Zlib stream reading ***\n");
3449 wxFileInputStream
fileInStream(FILENAME_GZ
);
3450 wxZlibInputStream
istr(fileInStream
);
3451 printf("Archive size: %u\n", istr
.GetSize());
3453 puts("Dumping the file:");
3454 while ( !istr
.Eof() )
3456 putchar(istr
.GetC());
3460 puts("\n----- done ------");
3465 // ----------------------------------------------------------------------------
3467 // ----------------------------------------------------------------------------
3469 #ifdef TEST_DATETIME
3473 #include "wx/date.h"
3474 #include "wx/datetime.h"
3479 wxDateTime::wxDateTime_t day
;
3480 wxDateTime::Month month
;
3482 wxDateTime::wxDateTime_t hour
, min
, sec
;
3484 wxDateTime::WeekDay wday
;
3485 time_t gmticks
, ticks
;
3487 void Init(const wxDateTime::Tm
& tm
)
3496 gmticks
= ticks
= -1;
3499 wxDateTime
DT() const
3500 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3502 bool SameDay(const wxDateTime::Tm
& tm
) const
3504 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3507 wxString
Format() const
3510 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3512 wxDateTime::GetMonthName(month
).c_str(),
3514 abs(wxDateTime::ConvertYearToBC(year
)),
3515 year
> 0 ? "AD" : "BC");
3519 wxString
FormatDate() const
3522 s
.Printf("%02d-%s-%4d%s",
3524 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3525 abs(wxDateTime::ConvertYearToBC(year
)),
3526 year
> 0 ? "AD" : "BC");
3531 static const Date testDates
[] =
3533 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3534 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3535 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3536 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3537 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3538 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3539 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3540 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3541 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3542 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3543 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3544 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3545 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3546 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3547 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3550 // this test miscellaneous static wxDateTime functions
3551 static void TestTimeStatic()
3553 puts("\n*** wxDateTime static methods test ***");
3555 // some info about the current date
3556 int year
= wxDateTime::GetCurrentYear();
3557 printf("Current year %d is %sa leap one and has %d days.\n",
3559 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3560 wxDateTime::GetNumberOfDays(year
));
3562 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3563 printf("Current month is '%s' ('%s') and it has %d days\n",
3564 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3565 wxDateTime::GetMonthName(month
).c_str(),
3566 wxDateTime::GetNumberOfDays(month
));
3569 static const size_t nYears
= 5;
3570 static const size_t years
[2][nYears
] =
3572 // first line: the years to test
3573 { 1990, 1976, 2000, 2030, 1984, },
3575 // second line: TRUE if leap, FALSE otherwise
3576 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3579 for ( size_t n
= 0; n
< nYears
; n
++ )
3581 int year
= years
[0][n
];
3582 bool should
= years
[1][n
] != 0,
3583 is
= wxDateTime::IsLeapYear(year
);
3585 printf("Year %d is %sa leap year (%s)\n",
3588 should
== is
? "ok" : "ERROR");
3590 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3594 // test constructing wxDateTime objects
3595 static void TestTimeSet()
3597 puts("\n*** wxDateTime construction test ***");
3599 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3601 const Date
& d1
= testDates
[n
];
3602 wxDateTime dt
= d1
.DT();
3605 d2
.Init(dt
.GetTm());
3607 wxString s1
= d1
.Format(),
3610 printf("Date: %s == %s (%s)\n",
3611 s1
.c_str(), s2
.c_str(),
3612 s1
== s2
? "ok" : "ERROR");
3616 // test time zones stuff
3617 static void TestTimeZones()
3619 puts("\n*** wxDateTime timezone test ***");
3621 wxDateTime now
= wxDateTime::Now();
3623 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3624 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3625 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3626 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3627 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3628 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3630 wxDateTime::Tm tm
= now
.GetTm();
3631 if ( wxDateTime(tm
) != now
)
3633 printf("ERROR: got %s instead of %s\n",
3634 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3638 // test some minimal support for the dates outside the standard range
3639 static void TestTimeRange()
3641 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3643 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3645 printf("Unix epoch:\t%s\n",
3646 wxDateTime(2440587.5).Format(fmt
).c_str());
3647 printf("Feb 29, 0: \t%s\n",
3648 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3649 printf("JDN 0: \t%s\n",
3650 wxDateTime(0.0).Format(fmt
).c_str());
3651 printf("Jan 1, 1AD:\t%s\n",
3652 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3653 printf("May 29, 2099:\t%s\n",
3654 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3657 static void TestTimeTicks()
3659 puts("\n*** wxDateTime ticks test ***");
3661 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3663 const Date
& d
= testDates
[n
];
3664 if ( d
.ticks
== -1 )
3667 wxDateTime dt
= d
.DT();
3668 long ticks
= (dt
.GetValue() / 1000).ToLong();
3669 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3670 if ( ticks
== d
.ticks
)
3676 printf(" (ERROR: should be %ld, delta = %ld)\n",
3677 d
.ticks
, ticks
- d
.ticks
);
3680 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3681 ticks
= (dt
.GetValue() / 1000).ToLong();
3682 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3683 if ( ticks
== d
.gmticks
)
3689 printf(" (ERROR: should be %ld, delta = %ld)\n",
3690 d
.gmticks
, ticks
- d
.gmticks
);
3697 // test conversions to JDN &c
3698 static void TestTimeJDN()
3700 puts("\n*** wxDateTime to JDN test ***");
3702 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3704 const Date
& d
= testDates
[n
];
3705 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3706 double jdn
= dt
.GetJulianDayNumber();
3708 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3715 printf(" (ERROR: should be %f, delta = %f)\n",
3716 d
.jdn
, jdn
- d
.jdn
);
3721 // test week days computation
3722 static void TestTimeWDays()
3724 puts("\n*** wxDateTime weekday test ***");
3726 // test GetWeekDay()
3728 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3730 const Date
& d
= testDates
[n
];
3731 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3733 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3736 wxDateTime::GetWeekDayName(wday
).c_str());
3737 if ( wday
== d
.wday
)
3743 printf(" (ERROR: should be %s)\n",
3744 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3750 // test SetToWeekDay()
3751 struct WeekDateTestData
3753 Date date
; // the real date (precomputed)
3754 int nWeek
; // its week index in the month
3755 wxDateTime::WeekDay wday
; // the weekday
3756 wxDateTime::Month month
; // the month
3757 int year
; // and the year
3759 wxString
Format() const
3762 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3764 case 1: which
= "first"; break;
3765 case 2: which
= "second"; break;
3766 case 3: which
= "third"; break;
3767 case 4: which
= "fourth"; break;
3768 case 5: which
= "fifth"; break;
3770 case -1: which
= "last"; break;
3775 which
+= " from end";
3778 s
.Printf("The %s %s of %s in %d",
3780 wxDateTime::GetWeekDayName(wday
).c_str(),
3781 wxDateTime::GetMonthName(month
).c_str(),
3788 // the array data was generated by the following python program
3790 from DateTime import *
3791 from whrandom import *
3792 from string import *
3794 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3795 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3797 week = DateTimeDelta(7)
3800 year = randint(1900, 2100)
3801 month = randint(1, 12)
3802 day = randint(1, 28)
3803 dt = DateTime(year, month, day)
3804 wday = dt.day_of_week
3806 countFromEnd = choice([-1, 1])
3809 while dt.month is month:
3810 dt = dt - countFromEnd * week
3811 weekNum = weekNum + countFromEnd
3813 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3815 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3816 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3819 static const WeekDateTestData weekDatesTestData
[] =
3821 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3822 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3823 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3824 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3825 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3826 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3827 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3828 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3829 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3830 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3831 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3832 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3833 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3834 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3835 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3836 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3837 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3838 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3839 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3840 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3843 static const char *fmt
= "%d-%b-%Y";
3846 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3848 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3850 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3852 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3854 const Date
& d
= wd
.date
;
3855 if ( d
.SameDay(dt
.GetTm()) )
3861 dt
.Set(d
.day
, d
.month
, d
.year
);
3863 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3868 // test the computation of (ISO) week numbers
3869 static void TestTimeWNumber()
3871 puts("\n*** wxDateTime week number test ***");
3873 struct WeekNumberTestData
3875 Date date
; // the date
3876 wxDateTime::wxDateTime_t week
; // the week number in the year
3877 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3878 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3879 wxDateTime::wxDateTime_t dnum
; // day number in the year
3882 // data generated with the following python script:
3884 from DateTime import *
3885 from whrandom import *
3886 from string import *
3888 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3889 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3891 def GetMonthWeek(dt):
3892 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3893 if weekNumMonth < 0:
3894 weekNumMonth = weekNumMonth + 53
3897 def GetLastSundayBefore(dt):
3898 if dt.iso_week[2] == 7:
3901 return dt - DateTimeDelta(dt.iso_week[2])
3904 year = randint(1900, 2100)
3905 month = randint(1, 12)
3906 day = randint(1, 28)
3907 dt = DateTime(year, month, day)
3908 dayNum = dt.day_of_year
3909 weekNum = dt.iso_week[1]
3910 weekNumMonth = GetMonthWeek(dt)
3913 dtSunday = GetLastSundayBefore(dt)
3915 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3916 weekNumMonth2 = weekNumMonth2 + 1
3917 dtSunday = dtSunday - DateTimeDelta(7)
3919 data = { 'day': rjust(`day`, 2), \
3920 'month': monthNames[month - 1], \
3922 'weekNum': rjust(`weekNum`, 2), \
3923 'weekNumMonth': weekNumMonth, \
3924 'weekNumMonth2': weekNumMonth2, \
3925 'dayNum': rjust(`dayNum`, 3) }
3927 print " { { %(day)s, "\
3928 "wxDateTime::%(month)s, "\
3931 "%(weekNumMonth)s, "\
3932 "%(weekNumMonth2)s, "\
3933 "%(dayNum)s }," % data
3936 static const WeekNumberTestData weekNumberTestDates
[] =
3938 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3939 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3940 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3941 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3942 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3943 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3944 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3945 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3946 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3947 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3948 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3949 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3950 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3951 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3952 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3953 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3954 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3955 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3956 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3957 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3960 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3962 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3963 const Date
& d
= wn
.date
;
3965 wxDateTime dt
= d
.DT();
3967 wxDateTime::wxDateTime_t
3968 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3969 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3970 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3971 dnum
= dt
.GetDayOfYear();
3973 printf("%s: the day number is %d",
3974 d
.FormatDate().c_str(), dnum
);
3975 if ( dnum
== wn
.dnum
)
3981 printf(" (ERROR: should be %d)", wn
.dnum
);
3984 printf(", week in month is %d", wmon
);
3985 if ( wmon
== wn
.wmon
)
3991 printf(" (ERROR: should be %d)", wn
.wmon
);
3994 printf(" or %d", wmon2
);
3995 if ( wmon2
== wn
.wmon2
)
4001 printf(" (ERROR: should be %d)", wn
.wmon2
);
4004 printf(", week in year is %d", week
);
4005 if ( week
== wn
.week
)
4011 printf(" (ERROR: should be %d)\n", wn
.week
);
4016 // test DST calculations
4017 static void TestTimeDST()
4019 puts("\n*** wxDateTime DST test ***");
4021 printf("DST is%s in effect now.\n\n",
4022 wxDateTime::Now().IsDST() ? "" : " not");
4024 // taken from http://www.energy.ca.gov/daylightsaving.html
4025 static const Date datesDST
[2][2004 - 1900 + 1] =
4028 { 1, wxDateTime::Apr
, 1990 },
4029 { 7, wxDateTime::Apr
, 1991 },
4030 { 5, wxDateTime::Apr
, 1992 },
4031 { 4, wxDateTime::Apr
, 1993 },
4032 { 3, wxDateTime::Apr
, 1994 },
4033 { 2, wxDateTime::Apr
, 1995 },
4034 { 7, wxDateTime::Apr
, 1996 },
4035 { 6, wxDateTime::Apr
, 1997 },
4036 { 5, wxDateTime::Apr
, 1998 },
4037 { 4, wxDateTime::Apr
, 1999 },
4038 { 2, wxDateTime::Apr
, 2000 },
4039 { 1, wxDateTime::Apr
, 2001 },
4040 { 7, wxDateTime::Apr
, 2002 },
4041 { 6, wxDateTime::Apr
, 2003 },
4042 { 4, wxDateTime::Apr
, 2004 },
4045 { 28, wxDateTime::Oct
, 1990 },
4046 { 27, wxDateTime::Oct
, 1991 },
4047 { 25, wxDateTime::Oct
, 1992 },
4048 { 31, wxDateTime::Oct
, 1993 },
4049 { 30, wxDateTime::Oct
, 1994 },
4050 { 29, wxDateTime::Oct
, 1995 },
4051 { 27, wxDateTime::Oct
, 1996 },
4052 { 26, wxDateTime::Oct
, 1997 },
4053 { 25, wxDateTime::Oct
, 1998 },
4054 { 31, wxDateTime::Oct
, 1999 },
4055 { 29, wxDateTime::Oct
, 2000 },
4056 { 28, wxDateTime::Oct
, 2001 },
4057 { 27, wxDateTime::Oct
, 2002 },
4058 { 26, wxDateTime::Oct
, 2003 },
4059 { 31, wxDateTime::Oct
, 2004 },
4064 for ( year
= 1990; year
< 2005; year
++ )
4066 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
4067 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
4069 printf("DST period in the US for year %d: from %s to %s",
4070 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
4072 size_t n
= year
- 1990;
4073 const Date
& dBegin
= datesDST
[0][n
];
4074 const Date
& dEnd
= datesDST
[1][n
];
4076 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
4082 printf(" (ERROR: should be %s %d to %s %d)\n",
4083 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
4084 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
4090 for ( year
= 1990; year
< 2005; year
++ )
4092 printf("DST period in Europe for year %d: from %s to %s\n",
4094 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
4095 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
4099 // test wxDateTime -> text conversion
4100 static void TestTimeFormat()
4102 puts("\n*** wxDateTime formatting test ***");
4104 // some information may be lost during conversion, so store what kind
4105 // of info should we recover after a round trip
4108 CompareNone
, // don't try comparing
4109 CompareBoth
, // dates and times should be identical
4110 CompareDate
, // dates only
4111 CompareTime
// time only
4116 CompareKind compareKind
;
4118 } formatTestFormats
[] =
4120 { CompareBoth
, "---> %c" },
4121 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
4122 { CompareBoth
, "Date is %x, time is %X" },
4123 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
4124 { CompareNone
, "The day of year: %j, the week of year: %W" },
4125 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
4128 static const Date formatTestDates
[] =
4130 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
4131 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
4133 // this test can't work for other centuries because it uses two digit
4134 // years in formats, so don't even try it
4135 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
4136 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
4137 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
4141 // an extra test (as it doesn't depend on date, don't do it in the loop)
4142 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
4144 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4148 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
4149 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4151 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4152 printf("%s", s
.c_str());
4154 // what can we recover?
4155 int kind
= formatTestFormats
[n
].compareKind
;
4159 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4162 // converion failed - should it have?
4163 if ( kind
== CompareNone
)
4166 puts(" (ERROR: conversion back failed)");
4170 // should have parsed the entire string
4171 puts(" (ERROR: conversion back stopped too soon)");
4175 bool equal
= FALSE
; // suppress compilaer warning
4183 equal
= dt
.IsSameDate(dt2
);
4187 equal
= dt
.IsSameTime(dt2
);
4193 printf(" (ERROR: got back '%s' instead of '%s')\n",
4194 dt2
.Format().c_str(), dt
.Format().c_str());
4205 // test text -> wxDateTime conversion
4206 static void TestTimeParse()
4208 puts("\n*** wxDateTime parse test ***");
4210 struct ParseTestData
4217 static const ParseTestData parseTestDates
[] =
4219 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4220 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4223 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4225 const char *format
= parseTestDates
[n
].format
;
4227 printf("%s => ", format
);
4230 if ( dt
.ParseRfc822Date(format
) )
4232 printf("%s ", dt
.Format().c_str());
4234 if ( parseTestDates
[n
].good
)
4236 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4243 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4248 puts("(ERROR: bad format)");
4253 printf("bad format (%s)\n",
4254 parseTestDates
[n
].good
? "ERROR" : "ok");
4259 static void TestDateTimeInteractive()
4261 puts("\n*** interactive wxDateTime tests ***");
4267 printf("Enter a date: ");
4268 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4271 // kill the last '\n'
4272 buf
[strlen(buf
) - 1] = 0;
4275 const char *p
= dt
.ParseDate(buf
);
4278 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4284 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4287 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4288 dt
.Format("%b %d, %Y").c_str(),
4290 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4291 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4292 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4295 puts("\n*** done ***");
4298 static void TestTimeMS()
4300 puts("*** testing millisecond-resolution support in wxDateTime ***");
4302 wxDateTime dt1
= wxDateTime::Now(),
4303 dt2
= wxDateTime::UNow();
4305 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4306 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4307 printf("Dummy loop: ");
4308 for ( int i
= 0; i
< 6000; i
++ )
4310 //for ( int j = 0; j < 10; j++ )
4313 s
.Printf("%g", sqrt(i
));
4322 dt2
= wxDateTime::UNow();
4323 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4325 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4327 puts("\n*** done ***");
4330 static void TestTimeArithmetics()
4332 puts("\n*** testing arithmetic operations on wxDateTime ***");
4334 static const struct ArithmData
4336 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4337 : span(sp
), name(nam
) { }
4341 } testArithmData
[] =
4343 ArithmData(wxDateSpan::Day(), "day"),
4344 ArithmData(wxDateSpan::Week(), "week"),
4345 ArithmData(wxDateSpan::Month(), "month"),
4346 ArithmData(wxDateSpan::Year(), "year"),
4347 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4350 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4352 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4354 wxDateSpan span
= testArithmData
[n
].span
;
4358 const char *name
= testArithmData
[n
].name
;
4359 printf("%s + %s = %s, %s - %s = %s\n",
4360 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4361 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4363 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4364 if ( dt1
- span
== dt
)
4370 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4373 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4374 if ( dt2
+ span
== dt
)
4380 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4383 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4384 if ( dt2
+ 2*span
== dt1
)
4390 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4397 static void TestTimeHolidays()
4399 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4401 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4402 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4403 dtEnd
= dtStart
.GetLastMonthDay();
4405 wxDateTimeArray hol
;
4406 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4408 const wxChar
*format
= "%d-%b-%Y (%a)";
4410 printf("All holidays between %s and %s:\n",
4411 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4413 size_t count
= hol
.GetCount();
4414 for ( size_t n
= 0; n
< count
; n
++ )
4416 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4422 static void TestTimeZoneBug()
4424 puts("\n*** testing for DST/timezone bug ***\n");
4426 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4427 for ( int i
= 0; i
< 31; i
++ )
4429 printf("Date %s: week day %s.\n",
4430 date
.Format(_T("%d-%m-%Y")).c_str(),
4431 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4433 date
+= wxDateSpan::Day();
4439 static void TestTimeSpanFormat()
4441 puts("\n*** wxTimeSpan tests ***");
4443 static const char *formats
[] =
4445 _T("(default) %H:%M:%S"),
4446 _T("%E weeks and %D days"),
4447 _T("%l milliseconds"),
4448 _T("(with ms) %H:%M:%S:%l"),
4449 _T("100%% of minutes is %M"), // test "%%"
4450 _T("%D days and %H hours"),
4451 _T("or also %S seconds"),
4454 wxTimeSpan
ts1(1, 2, 3, 4),
4456 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4458 printf("ts1 = %s\tts2 = %s\n",
4459 ts1
.Format(formats
[n
]).c_str(),
4460 ts2
.Format(formats
[n
]).c_str());
4468 // test compatibility with the old wxDate/wxTime classes
4469 static void TestTimeCompatibility()
4471 puts("\n*** wxDateTime compatibility test ***");
4473 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4474 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4476 double jdnNow
= wxDateTime::Now().GetJDN();
4477 long jdnMidnight
= (long)(jdnNow
- 0.5);
4478 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4480 jdnMidnight
= wxDate().Set().GetJulianDate();
4481 printf("wxDateTime for today: %s\n",
4482 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4484 int flags
= wxEUROPEAN
;//wxFULL;
4487 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4488 for ( int n
= 0; n
< 7; n
++ )
4490 printf("Previous %s is %s\n",
4491 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4492 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4498 #endif // TEST_DATETIME
4500 // ----------------------------------------------------------------------------
4502 // ----------------------------------------------------------------------------
4506 #include "wx/thread.h"
4508 static size_t gs_counter
= (size_t)-1;
4509 static wxCriticalSection gs_critsect
;
4510 static wxCondition gs_cond
;
4512 class MyJoinableThread
: public wxThread
4515 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4516 { m_n
= n
; Create(); }
4518 // thread execution starts here
4519 virtual ExitCode
Entry();
4525 wxThread::ExitCode
MyJoinableThread::Entry()
4527 unsigned long res
= 1;
4528 for ( size_t n
= 1; n
< m_n
; n
++ )
4532 // it's a loooong calculation :-)
4536 return (ExitCode
)res
;
4539 class MyDetachedThread
: public wxThread
4542 MyDetachedThread(size_t n
, char ch
)
4546 m_cancelled
= FALSE
;
4551 // thread execution starts here
4552 virtual ExitCode
Entry();
4555 virtual void OnExit();
4558 size_t m_n
; // number of characters to write
4559 char m_ch
; // character to write
4561 bool m_cancelled
; // FALSE if we exit normally
4564 wxThread::ExitCode
MyDetachedThread::Entry()
4567 wxCriticalSectionLocker
lock(gs_critsect
);
4568 if ( gs_counter
== (size_t)-1 )
4574 for ( size_t n
= 0; n
< m_n
; n
++ )
4576 if ( TestDestroy() )
4586 wxThread::Sleep(100);
4592 void MyDetachedThread::OnExit()
4594 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4596 wxCriticalSectionLocker
lock(gs_critsect
);
4597 if ( !--gs_counter
&& !m_cancelled
)
4601 static void TestDetachedThreads()
4603 puts("\n*** Testing detached threads ***");
4605 static const size_t nThreads
= 3;
4606 MyDetachedThread
*threads
[nThreads
];
4608 for ( n
= 0; n
< nThreads
; n
++ )
4610 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4613 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4614 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4616 for ( n
= 0; n
< nThreads
; n
++ )
4621 // wait until all threads terminate
4627 static void TestJoinableThreads()
4629 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4631 // calc 10! in the background
4632 MyJoinableThread
thread(10);
4635 printf("\nThread terminated with exit code %lu.\n",
4636 (unsigned long)thread
.Wait());
4639 static void TestThreadSuspend()
4641 puts("\n*** Testing thread suspend/resume functions ***");
4643 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4647 // this is for this demo only, in a real life program we'd use another
4648 // condition variable which would be signaled from wxThread::Entry() to
4649 // tell us that the thread really started running - but here just wait a
4650 // bit and hope that it will be enough (the problem is, of course, that
4651 // the thread might still not run when we call Pause() which will result
4653 wxThread::Sleep(300);
4655 for ( size_t n
= 0; n
< 3; n
++ )
4659 puts("\nThread suspended");
4662 // don't sleep but resume immediately the first time
4663 wxThread::Sleep(300);
4665 puts("Going to resume the thread");
4670 puts("Waiting until it terminates now");
4672 // wait until the thread terminates
4678 static void TestThreadDelete()
4680 // As above, using Sleep() is only for testing here - we must use some
4681 // synchronisation object instead to ensure that the thread is still
4682 // running when we delete it - deleting a detached thread which already
4683 // terminated will lead to a crash!
4685 puts("\n*** Testing thread delete function ***");
4687 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4691 puts("\nDeleted a thread which didn't start to run yet.");
4693 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4697 wxThread::Sleep(300);
4701 puts("\nDeleted a running thread.");
4703 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4707 wxThread::Sleep(300);
4713 puts("\nDeleted a sleeping thread.");
4715 MyJoinableThread
thread3(20);
4720 puts("\nDeleted a joinable thread.");
4722 MyJoinableThread
thread4(2);
4725 wxThread::Sleep(300);
4729 puts("\nDeleted a joinable thread which already terminated.");
4734 // wxCondition test code
4735 // ----------------------------------------------------------------------------
4737 class MyWaitingThread
: public wxThread
4740 MyWaitingThread(wxCondition
*condition
)
4742 m_condition
= condition
;
4747 virtual ExitCode
Entry()
4749 printf("Thread %lu has started running.", GetId());
4754 printf("Thread %lu starts to wait...\n", GetId());
4757 m_condition
->Wait();
4759 printf("Thread %lu finished to wait, exiting.\n", GetId());
4766 wxCondition
*m_condition
;
4769 static void TestThreadConditions()
4771 wxCondition condition
;
4773 // create and launch threads
4774 MyWaitingThread
*threads
[2];
4777 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4779 threads
[n
] = new MyWaitingThread(&condition
);
4782 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4787 // wait until all threads run
4788 printf("Main thread is waiting for the threads to start: ");
4791 size_t nRunning
= 0;
4792 while ( nRunning
< WXSIZEOF(threads
) )
4802 puts("\nMain thread: all threads started up.");
4807 printf("Main thread: about to signal the condition.\n");
4812 printf("Main thread: about to broadcast the condition.\n");
4814 condition
.Broadcast();
4816 // give them time to terminate (dirty)
4817 wxThread::Sleep(300);
4820 #endif // TEST_THREADS
4822 // ----------------------------------------------------------------------------
4824 // ----------------------------------------------------------------------------
4828 static void PrintArray(const char* name
, const wxArrayString
& array
)
4830 printf("Dump of the array '%s'\n", name
);
4832 size_t nCount
= array
.GetCount();
4833 for ( size_t n
= 0; n
< nCount
; n
++ )
4835 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4839 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4841 printf("Dump of the array '%s'\n", name
);
4843 size_t nCount
= array
.GetCount();
4844 for ( size_t n
= 0; n
< nCount
; n
++ )
4846 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4850 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4851 const wxString
& second
)
4853 return first
.length() - second
.length();
4856 int wxCMPFUNC_CONV
IntCompare(int *first
,
4859 return *first
- *second
;
4862 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4865 return *second
- *first
;
4868 static void TestArrayOfInts()
4870 puts("*** Testing wxArrayInt ***\n");
4881 puts("After sort:");
4885 puts("After reverse sort:");
4886 a
.Sort(IntRevCompare
);
4890 #include "wx/dynarray.h"
4892 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4893 #include "wx/arrimpl.cpp"
4894 WX_DEFINE_OBJARRAY(ArrayBars
);
4896 static void TestArrayOfObjects()
4898 puts("*** Testing wxObjArray ***\n");
4902 Bar
bar("second bar");
4904 printf("Initially: %u objects in the array, %u objects total.\n",
4905 bars
.GetCount(), Bar::GetNumber());
4907 bars
.Add(new Bar("first bar"));
4910 printf("Now: %u objects in the array, %u objects total.\n",
4911 bars
.GetCount(), Bar::GetNumber());
4915 printf("After Empty(): %u objects in the array, %u objects total.\n",
4916 bars
.GetCount(), Bar::GetNumber());
4919 printf("Finally: no more objects in the array, %u objects total.\n",
4923 #endif // TEST_ARRAYS
4925 // ----------------------------------------------------------------------------
4927 // ----------------------------------------------------------------------------
4931 #include "wx/timer.h"
4932 #include "wx/tokenzr.h"
4934 static void TestStringConstruction()
4936 puts("*** Testing wxString constructores ***");
4938 #define TEST_CTOR(args, res) \
4941 printf("wxString%s = %s ", #args, s.c_str()); \
4948 printf("(ERROR: should be %s)\n", res); \
4952 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4953 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4954 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4955 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4957 static const wxChar
*s
= _T("?really!");
4958 const wxChar
*start
= wxStrchr(s
, _T('r'));
4959 const wxChar
*end
= wxStrchr(s
, _T('!'));
4960 TEST_CTOR((start
, end
), _T("really"));
4965 static void TestString()
4975 for (int i
= 0; i
< 1000000; ++i
)
4979 c
= "! How'ya doin'?";
4982 c
= "Hello world! What's up?";
4987 printf ("TestString elapsed time: %ld\n", sw
.Time());
4990 static void TestPChar()
4998 for (int i
= 0; i
< 1000000; ++i
)
5000 strcpy (a
, "Hello");
5001 strcpy (b
, " world");
5002 strcpy (c
, "! How'ya doin'?");
5005 strcpy (c
, "Hello world! What's up?");
5006 if (strcmp (c
, a
) == 0)
5010 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
5013 static void TestStringSub()
5015 wxString
s("Hello, world!");
5017 puts("*** Testing wxString substring extraction ***");
5019 printf("String = '%s'\n", s
.c_str());
5020 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
5021 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
5022 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
5023 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
5024 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
5025 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
5027 static const wxChar
*prefixes
[] =
5031 _T("Hello, world!"),
5032 _T("Hello, world!!!"),
5038 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
5040 wxString prefix
= prefixes
[n
], rest
;
5041 bool rc
= s
.StartsWith(prefix
, &rest
);
5042 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
5045 printf(" (the rest is '%s')\n", rest
.c_str());
5056 static void TestStringFormat()
5058 puts("*** Testing wxString formatting ***");
5061 s
.Printf("%03d", 18);
5063 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
5064 printf("Number 18: %s\n", s
.c_str());
5069 // returns "not found" for npos, value for all others
5070 static wxString
PosToString(size_t res
)
5072 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
5073 : wxString::Format(_T("%u"), res
);
5077 static void TestStringFind()
5079 puts("*** Testing wxString find() functions ***");
5081 static const wxChar
*strToFind
= _T("ell");
5082 static const struct StringFindTest
5086 result
; // of searching "ell" in str
5089 { _T("Well, hello world"), 0, 1 },
5090 { _T("Well, hello world"), 6, 7 },
5091 { _T("Well, hello world"), 9, wxString::npos
},
5094 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
5096 const StringFindTest
& ft
= findTestData
[n
];
5097 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
5099 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
5100 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
5102 size_t resTrue
= ft
.result
;
5103 if ( res
== resTrue
)
5109 printf(_T("(ERROR: should be %s)\n"),
5110 PosToString(resTrue
).c_str());
5117 static void TestStringTokenizer()
5119 puts("*** Testing wxStringTokenizer ***");
5121 static const wxChar
*modeNames
[] =
5125 _T("return all empty"),
5130 static const struct StringTokenizerTest
5132 const wxChar
*str
; // string to tokenize
5133 const wxChar
*delims
; // delimiters to use
5134 size_t count
; // count of token
5135 wxStringTokenizerMode mode
; // how should we tokenize it
5136 } tokenizerTestData
[] =
5138 { _T(""), _T(" "), 0 },
5139 { _T("Hello, world"), _T(" "), 2 },
5140 { _T("Hello, world "), _T(" "), 2 },
5141 { _T("Hello, world"), _T(","), 2 },
5142 { _T("Hello, world!"), _T(",!"), 2 },
5143 { _T("Hello,, world!"), _T(",!"), 3 },
5144 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
5145 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
5146 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
5147 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
5148 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
5149 { _T("01/02/99"), _T("/-"), 3 },
5150 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
5153 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
5155 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
5156 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
5158 size_t count
= tkz
.CountTokens();
5159 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
5160 MakePrintable(tt
.str
).c_str(),
5162 MakePrintable(tt
.delims
).c_str(),
5163 modeNames
[tkz
.GetMode()]);
5164 if ( count
== tt
.count
)
5170 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
5175 // if we emulate strtok(), check that we do it correctly
5176 wxChar
*buf
, *s
= NULL
, *last
;
5178 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
5180 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
5181 wxStrcpy(buf
, tt
.str
);
5183 s
= wxStrtok(buf
, tt
.delims
, &last
);
5190 // now show the tokens themselves
5192 while ( tkz
.HasMoreTokens() )
5194 wxString token
= tkz
.GetNextToken();
5196 printf(_T("\ttoken %u: '%s'"),
5198 MakePrintable(token
).c_str());
5208 printf(" (ERROR: should be %s)\n", s
);
5211 s
= wxStrtok(NULL
, tt
.delims
, &last
);
5215 // nothing to compare with
5220 if ( count2
!= count
)
5222 puts(_T("\tERROR: token count mismatch"));
5231 static void TestStringReplace()
5233 puts("*** Testing wxString::replace ***");
5235 static const struct StringReplaceTestData
5237 const wxChar
*original
; // original test string
5238 size_t start
, len
; // the part to replace
5239 const wxChar
*replacement
; // the replacement string
5240 const wxChar
*result
; // and the expected result
5241 } stringReplaceTestData
[] =
5243 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
5244 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
5245 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
5246 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
5247 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
5250 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
5252 const StringReplaceTestData data
= stringReplaceTestData
[n
];
5254 wxString original
= data
.original
;
5255 original
.replace(data
.start
, data
.len
, data
.replacement
);
5257 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
5258 data
.original
, data
.start
, data
.len
, data
.replacement
,
5261 if ( original
== data
.result
)
5267 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
5274 static void TestStringMatch()
5276 wxPuts(_T("*** Testing wxString::Matches() ***"));
5278 static const struct StringMatchTestData
5281 const wxChar
*wildcard
;
5283 } stringMatchTestData
[] =
5285 { _T("foobar"), _T("foo*"), 1 },
5286 { _T("foobar"), _T("*oo*"), 1 },
5287 { _T("foobar"), _T("*bar"), 1 },
5288 { _T("foobar"), _T("??????"), 1 },
5289 { _T("foobar"), _T("f??b*"), 1 },
5290 { _T("foobar"), _T("f?b*"), 0 },
5291 { _T("foobar"), _T("*goo*"), 0 },
5292 { _T("foobar"), _T("*foo"), 0 },
5293 { _T("foobarfoo"), _T("*foo"), 1 },
5294 { _T(""), _T("*"), 1 },
5295 { _T(""), _T("?"), 0 },
5298 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
5300 const StringMatchTestData
& data
= stringMatchTestData
[n
];
5301 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
5302 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
5304 matches
? _T("matches") : _T("doesn't match"),
5306 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5312 #endif // TEST_STRINGS
5314 // ----------------------------------------------------------------------------
5316 // ----------------------------------------------------------------------------
5318 #ifdef TEST_SNGLINST
5319 #include "wx/snglinst.h"
5320 #endif // TEST_SNGLINST
5322 int main(int argc
, char **argv
)
5324 wxInitializer initializer
;
5327 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5332 #ifdef TEST_SNGLINST
5333 wxSingleInstanceChecker checker
;
5334 if ( checker
.Create(_T(".wxconsole.lock")) )
5336 if ( checker
.IsAnotherRunning() )
5338 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5343 // wait some time to give time to launch another instance
5344 wxPrintf(_T("Press \"Enter\" to continue..."));
5347 else // failed to create
5349 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5351 #endif // TEST_SNGLINST
5355 #endif // TEST_CHARSET
5358 TestCmdLineConvert();
5360 #if wxUSE_CMDLINE_PARSER
5361 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5363 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5364 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5365 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5366 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5368 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5369 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5370 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5371 wxCMD_LINE_VAL_NUMBER
},
5372 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5373 wxCMD_LINE_VAL_DATE
},
5375 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5376 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5381 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5383 parser
.AddOption("project_name", "", "full path to project file",
5384 wxCMD_LINE_VAL_STRING
,
5385 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5387 switch ( parser
.Parse() )
5390 wxLogMessage("Help was given, terminating.");
5394 ShowCmdLine(parser
);
5398 wxLogMessage("Syntax error detected, aborting.");
5401 #endif // wxUSE_CMDLINE_PARSER
5403 #endif // TEST_CMDLINE
5411 TestStringConstruction();
5414 TestStringTokenizer();
5415 TestStringReplace();
5421 #endif // TEST_STRINGS
5434 puts("*** Initially:");
5436 PrintArray("a1", a1
);
5438 wxArrayString
a2(a1
);
5439 PrintArray("a2", a2
);
5441 wxSortedArrayString
a3(a1
);
5442 PrintArray("a3", a3
);
5444 puts("*** After deleting a string from a1");
5447 PrintArray("a1", a1
);
5448 PrintArray("a2", a2
);
5449 PrintArray("a3", a3
);
5451 puts("*** After reassigning a1 to a2 and a3");
5453 PrintArray("a2", a2
);
5454 PrintArray("a3", a3
);
5456 puts("*** After sorting a1");
5458 PrintArray("a1", a1
);
5460 puts("*** After sorting a1 in reverse order");
5462 PrintArray("a1", a1
);
5464 puts("*** After sorting a1 by the string length");
5465 a1
.Sort(StringLenCompare
);
5466 PrintArray("a1", a1
);
5468 TestArrayOfObjects();
5474 #endif // TEST_ARRAYS
5484 #ifdef TEST_DLLLOADER
5486 #endif // TEST_DLLLOADER
5490 #endif // TEST_ENVIRON
5494 #endif // TEST_EXECUTE
5496 #ifdef TEST_FILECONF
5498 #endif // TEST_FILECONF
5506 #endif // TEST_LOCALE
5510 for ( size_t n
= 0; n
< 8000; n
++ )
5512 s
<< (char)('A' + (n
% 26));
5516 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5518 // this one shouldn't be truncated
5521 // but this one will because log functions use fixed size buffer
5522 // (note that it doesn't need '\n' at the end neither - will be added
5524 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5536 #ifdef TEST_FILENAME
5540 fn
.Assign("c:\\foo", "bar.baz");
5547 TestFileNameConstruction();
5548 TestFileNameMakeRelative();
5549 TestFileNameSplit();
5552 TestFileNameComparison();
5553 TestFileNameOperations();
5555 #endif // TEST_FILENAME
5557 #ifdef TEST_FILETIME
5560 #endif // TEST_FILETIME
5563 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5564 if ( TestFtpConnect() )
5575 if ( TEST_INTERACTIVE
)
5576 TestFtpInteractive();
5578 //else: connecting to the FTP server failed
5585 int nCPUs
= wxThread::GetCPUCount();
5586 printf("This system has %d CPUs\n", nCPUs
);
5588 wxThread::SetConcurrency(nCPUs
);
5592 TestDetachedThreads();
5593 TestJoinableThreads();
5594 TestThreadSuspend();
5598 TestThreadConditions();
5599 #endif // TEST_THREADS
5601 #ifdef TEST_LONGLONG
5602 // seed pseudo random generator
5603 srand((unsigned)time(NULL
));
5612 TestMultiplication();
5615 TestLongLongConversion();
5616 TestBitOperations();
5617 TestLongLongComparison();
5618 TestLongLongPrint();
5620 #endif // TEST_LONGLONG
5628 #endif // TEST_HASHMAP
5631 wxLog::AddTraceMask(_T("mime"));
5639 TestMimeAssociate();
5642 #ifdef TEST_INFO_FUNCTIONS
5649 #endif // TEST_INFO_FUNCTIONS
5651 #ifdef TEST_PATHLIST
5653 #endif // TEST_PATHLIST
5657 #endif // TEST_REGCONF
5660 // TODO: write a real test using src/regex/tests file
5665 TestRegExSubmatch();
5666 TestRegExReplacement();
5668 if ( TEST_INTERACTIVE
)
5669 TestRegExInteractive();
5671 #endif // TEST_REGEX
5673 #ifdef TEST_REGISTRY
5675 TestRegistryAssociation();
5676 #endif // TEST_REGISTRY
5681 #endif // TEST_SOCKETS
5686 #endif // TEST_STREAMS
5690 #endif // TEST_TIMER
5692 #ifdef TEST_DATETIME
5705 TestTimeArithmetics();
5708 TestTimeSpanFormat();
5714 if ( TEST_INTERACTIVE
)
5715 TestDateTimeInteractive();
5716 #endif // TEST_DATETIME
5719 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5721 #endif // TEST_USLEEP
5726 #endif // TEST_VCARD
5730 #endif // TEST_WCHAR
5733 TestZipStreamRead();
5734 TestZipFileSystem();
5738 TestZlibStreamWrite();
5739 TestZlibStreamRead();