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
85 // #define TEST_VCARD -- don't enable this (VZ)
92 static const bool TEST_ALL
= TRUE
;
96 static const bool TEST_ALL
= FALSE
;
99 // some tests are interactive, define this to run them
100 #ifdef TEST_INTERACTIVE
101 #undef TEST_INTERACTIVE
103 static const bool TEST_INTERACTIVE
= TRUE
;
105 static const bool TEST_INTERACTIVE
= FALSE
;
108 // ----------------------------------------------------------------------------
109 // test class for container objects
110 // ----------------------------------------------------------------------------
112 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
114 class Bar
// Foo is already taken in the hash test
117 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
118 ~Bar() { ms_bars
--; }
120 static size_t GetNumber() { return ms_bars
; }
122 const char *GetName() const { return m_name
; }
127 static size_t ms_bars
;
130 size_t Bar::ms_bars
= 0;
132 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
134 // ============================================================================
136 // ============================================================================
138 // ----------------------------------------------------------------------------
140 // ----------------------------------------------------------------------------
142 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
144 // replace TABs with \t and CRs with \n
145 static wxString
MakePrintable(const wxChar
*s
)
148 (void)str
.Replace(_T("\t"), _T("\\t"));
149 (void)str
.Replace(_T("\n"), _T("\\n"));
150 (void)str
.Replace(_T("\r"), _T("\\r"));
155 #endif // MakePrintable() is used
157 // ----------------------------------------------------------------------------
158 // wxFontMapper::CharsetToEncoding
159 // ----------------------------------------------------------------------------
163 #include "wx/fontmap.h"
165 static void TestCharset()
167 static const wxChar
*charsets
[] =
169 // some vali charsets
178 // and now some bogus ones
185 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
187 wxFontEncoding enc
= wxFontMapper::Get()->CharsetToEncoding(charsets
[n
]);
188 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
190 wxFontMapper::Get()->GetEncodingName(enc
).c_str(),
191 wxFontMapper::Get()->GetEncodingDescription(enc
).c_str());
195 #endif // TEST_CHARSET
197 // ----------------------------------------------------------------------------
199 // ----------------------------------------------------------------------------
203 #include "wx/cmdline.h"
204 #include "wx/datetime.h"
206 #if wxUSE_CMDLINE_PARSER
208 static void ShowCmdLine(const wxCmdLineParser
& parser
)
210 wxString s
= "Input files: ";
212 size_t count
= parser
.GetParamCount();
213 for ( size_t param
= 0; param
< count
; param
++ )
215 s
<< parser
.GetParam(param
) << ' ';
219 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
220 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
225 if ( parser
.Found("o", &strVal
) )
226 s
<< "Output file:\t" << strVal
<< '\n';
227 if ( parser
.Found("i", &strVal
) )
228 s
<< "Input dir:\t" << strVal
<< '\n';
229 if ( parser
.Found("s", &lVal
) )
230 s
<< "Size:\t" << lVal
<< '\n';
231 if ( parser
.Found("d", &dt
) )
232 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
233 if ( parser
.Found("project_name", &strVal
) )
234 s
<< "Project:\t" << strVal
<< '\n';
239 #endif // wxUSE_CMDLINE_PARSER
241 static void TestCmdLineConvert()
243 static const char *cmdlines
[] =
246 "-a \"-bstring 1\" -c\"string 2\" \"string 3\"",
247 "literal \\\" and \"\"",
250 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
252 const char *cmdline
= cmdlines
[n
];
253 printf("Parsing: %s\n", cmdline
);
254 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
256 size_t count
= args
.GetCount();
257 printf("\targc = %u\n", count
);
258 for ( size_t arg
= 0; arg
< count
; arg
++ )
260 printf("\targv[%u] = %s\n", arg
, args
[arg
].c_str());
265 #endif // TEST_CMDLINE
267 // ----------------------------------------------------------------------------
269 // ----------------------------------------------------------------------------
276 static const wxChar
*ROOTDIR
= _T("/");
277 static const wxChar
*TESTDIR
= _T("/usr");
278 #elif defined(__WXMSW__)
279 static const wxChar
*ROOTDIR
= _T("c:\\");
280 static const wxChar
*TESTDIR
= _T("d:\\");
282 #error "don't know where the root directory is"
285 static void TestDirEnumHelper(wxDir
& dir
,
286 int flags
= wxDIR_DEFAULT
,
287 const wxString
& filespec
= wxEmptyString
)
291 if ( !dir
.IsOpened() )
294 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
297 printf("\t%s\n", filename
.c_str());
299 cont
= dir
.GetNext(&filename
);
305 static void TestDirEnum()
307 puts("*** Testing wxDir::GetFirst/GetNext ***");
309 wxDir
dir(wxGetCwd());
311 puts("Enumerating everything in current directory:");
312 TestDirEnumHelper(dir
);
314 puts("Enumerating really everything in current directory:");
315 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
317 puts("Enumerating object files in current directory:");
318 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
320 puts("Enumerating directories in current directory:");
321 TestDirEnumHelper(dir
, wxDIR_DIRS
);
323 puts("Enumerating files in current directory:");
324 TestDirEnumHelper(dir
, wxDIR_FILES
);
326 puts("Enumerating files including hidden in current directory:");
327 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
331 puts("Enumerating everything in root directory:");
332 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
334 puts("Enumerating directories in root directory:");
335 TestDirEnumHelper(dir
, wxDIR_DIRS
);
337 puts("Enumerating files in root directory:");
338 TestDirEnumHelper(dir
, wxDIR_FILES
);
340 puts("Enumerating files including hidden in root directory:");
341 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
343 puts("Enumerating files in non existing directory:");
344 wxDir
dirNo("nosuchdir");
345 TestDirEnumHelper(dirNo
);
348 class DirPrintTraverser
: public wxDirTraverser
351 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
353 return wxDIR_CONTINUE
;
356 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
358 wxString path
, name
, ext
;
359 wxSplitPath(dirname
, &path
, &name
, &ext
);
362 name
<< _T('.') << ext
;
365 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
367 if ( wxIsPathSeparator(*p
) )
371 printf("%s%s\n", indent
.c_str(), name
.c_str());
373 return wxDIR_CONTINUE
;
377 static void TestDirTraverse()
379 puts("*** Testing wxDir::Traverse() ***");
383 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
384 printf("There are %u files under '%s'\n", n
, TESTDIR
);
387 printf("First one is '%s'\n", files
[0u].c_str());
388 printf(" last one is '%s'\n", files
[n
- 1].c_str());
391 // enum again with custom traverser
393 DirPrintTraverser traverser
;
394 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
399 // ----------------------------------------------------------------------------
401 // ----------------------------------------------------------------------------
403 #ifdef TEST_DLLLOADER
405 #include "wx/dynlib.h"
407 static void TestDllLoad()
409 #if defined(__WXMSW__)
410 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
411 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
412 #elif defined(__UNIX__)
413 // weird: using just libc.so does *not* work!
414 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
415 static const wxChar
*FUNC_NAME
= _T("strlen");
417 #error "don't know how to test wxDllLoader on this platform"
420 puts("*** testing wxDllLoader ***\n");
422 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
425 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
429 typedef int (*strlenType
)(const char *);
430 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
433 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
434 FUNC_NAME
, LIB_NAME
);
438 if ( pfnStrlen("foo") != 3 )
440 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
448 wxDllLoader::UnloadLibrary(dllHandle
);
452 #endif // TEST_DLLLOADER
454 // ----------------------------------------------------------------------------
456 // ----------------------------------------------------------------------------
460 #include "wx/utils.h"
462 static wxString
MyGetEnv(const wxString
& var
)
465 if ( !wxGetEnv(var
, &val
) )
468 val
= wxString(_T('\'')) + val
+ _T('\'');
473 static void TestEnvironment()
475 const wxChar
*var
= _T("wxTestVar");
477 puts("*** testing environment access functions ***");
479 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
480 wxSetEnv(var
, _T("value for wxTestVar"));
481 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
482 wxSetEnv(var
, _T("another value"));
483 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
485 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
486 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
489 #endif // TEST_ENVIRON
491 // ----------------------------------------------------------------------------
493 // ----------------------------------------------------------------------------
497 #include "wx/utils.h"
499 static void TestExecute()
501 puts("*** testing wxExecute ***");
504 #define COMMAND "cat -n ../../Makefile" // "echo hi"
505 #define SHELL_COMMAND "echo hi from shell"
506 #define REDIRECT_COMMAND COMMAND // "date"
507 #elif defined(__WXMSW__)
508 #define COMMAND "command.com -c 'echo hi'"
509 #define SHELL_COMMAND "echo hi"
510 #define REDIRECT_COMMAND COMMAND
512 #error "no command to exec"
515 printf("Testing wxShell: ");
517 if ( wxShell(SHELL_COMMAND
) )
522 printf("Testing wxExecute: ");
524 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
529 #if 0 // no, it doesn't work (yet?)
530 printf("Testing async wxExecute: ");
532 if ( wxExecute(COMMAND
) != 0 )
533 puts("Ok (command launched).");
538 printf("Testing wxExecute with redirection:\n");
539 wxArrayString output
;
540 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
546 size_t count
= output
.GetCount();
547 for ( size_t n
= 0; n
< count
; n
++ )
549 printf("\t%s\n", output
[n
].c_str());
556 #endif // TEST_EXECUTE
558 // ----------------------------------------------------------------------------
560 // ----------------------------------------------------------------------------
565 #include "wx/ffile.h"
566 #include "wx/textfile.h"
568 static void TestFileRead()
570 puts("*** wxFile read test ***");
572 wxFile
file(_T("testdata.fc"));
573 if ( file
.IsOpened() )
575 printf("File length: %lu\n", file
.Length());
577 puts("File dump:\n----------");
579 static const off_t len
= 1024;
583 off_t nRead
= file
.Read(buf
, len
);
584 if ( nRead
== wxInvalidOffset
)
586 printf("Failed to read the file.");
590 fwrite(buf
, nRead
, 1, stdout
);
600 printf("ERROR: can't open test file.\n");
606 static void TestTextFileRead()
608 puts("*** wxTextFile read test ***");
610 wxTextFile
file(_T("testdata.fc"));
613 printf("Number of lines: %u\n", file
.GetLineCount());
614 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
618 puts("\nDumping the entire file:");
619 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
621 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
623 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
625 puts("\nAnd now backwards:");
626 for ( s
= file
.GetLastLine();
627 file
.GetCurrentLine() != 0;
628 s
= file
.GetPrevLine() )
630 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
632 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
636 printf("ERROR: can't open '%s'\n", file
.GetName());
642 static void TestFileCopy()
644 puts("*** Testing wxCopyFile ***");
646 static const wxChar
*filename1
= _T("testdata.fc");
647 static const wxChar
*filename2
= _T("test2");
648 if ( !wxCopyFile(filename1
, filename2
) )
650 puts("ERROR: failed to copy file");
654 wxFFile
f1(filename1
, "rb"),
657 if ( !f1
.IsOpened() || !f2
.IsOpened() )
659 puts("ERROR: failed to open file(s)");
664 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
666 puts("ERROR: failed to read file(s)");
670 if ( (s1
.length() != s2
.length()) ||
671 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
673 puts("ERROR: copy error!");
677 puts("File was copied ok.");
683 if ( !wxRemoveFile(filename2
) )
685 puts("ERROR: failed to remove the file");
693 // ----------------------------------------------------------------------------
695 // ----------------------------------------------------------------------------
699 #include "wx/confbase.h"
700 #include "wx/fileconf.h"
702 static const struct FileConfTestData
704 const wxChar
*name
; // value name
705 const wxChar
*value
; // the value from the file
708 { _T("value1"), _T("one") },
709 { _T("value2"), _T("two") },
710 { _T("novalue"), _T("default") },
713 static void TestFileConfRead()
715 puts("*** testing wxFileConfig loading/reading ***");
717 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
718 _T("testdata.fc"), wxEmptyString
,
719 wxCONFIG_USE_RELATIVE_PATH
);
721 // test simple reading
722 puts("\nReading config file:");
723 wxString
defValue(_T("default")), value
;
724 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
726 const FileConfTestData
& data
= fcTestData
[n
];
727 value
= fileconf
.Read(data
.name
, defValue
);
728 printf("\t%s = %s ", data
.name
, value
.c_str());
729 if ( value
== data
.value
)
735 printf("(ERROR: should be %s)\n", data
.value
);
739 // test enumerating the entries
740 puts("\nEnumerating all root entries:");
743 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
746 printf("\t%s = %s\n",
748 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
750 cont
= fileconf
.GetNextEntry(name
, dummy
);
754 #endif // TEST_FILECONF
756 // ----------------------------------------------------------------------------
758 // ----------------------------------------------------------------------------
762 #include "wx/filename.h"
764 static void DumpFileName(const wxFileName
& fn
)
766 wxString full
= fn
.GetFullPath();
768 wxString vol
, path
, name
, ext
;
769 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
771 wxPrintf(_T("Filename '%s' -> vol '%s', path '%s', name '%s', ext '%s'\n"),
772 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
775 static struct FileNameInfo
777 const wxChar
*fullname
;
778 const wxChar
*volume
;
787 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), TRUE
, wxPATH_UNIX
},
788 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), TRUE
, wxPATH_UNIX
},
789 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), TRUE
, wxPATH_UNIX
},
790 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), FALSE
, wxPATH_UNIX
},
791 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
792 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), TRUE
, wxPATH_UNIX
},
793 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), TRUE
, wxPATH_UNIX
},
794 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
795 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), TRUE
, wxPATH_UNIX
},
797 // Windows file names
798 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
799 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
800 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
801 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
802 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), TRUE
, wxPATH_DOS
},
803 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
805 // wxFileName support for Mac file names is broken currently
808 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
809 { _T("Volume:Dir:Subdir:File"), _T("Volume"), _T("Dir:Subdir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
810 { _T("Volume:"), _T("Volume"), _T(""), _T(""), _T(""), TRUE
, wxPATH_MAC
},
811 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
812 { _T(":File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
813 { _T("File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
817 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
818 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
821 static void TestFileNameConstruction()
823 puts("*** testing wxFileName construction ***");
825 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
827 const FileNameInfo
& fni
= filenames
[n
];
829 wxFileName
fn(fni
.fullname
, fni
.format
);
831 wxString fullname
= fn
.GetFullPath(fni
.format
);
832 if ( fullname
!= fni
.fullname
)
834 printf("ERROR: fullname should be '%s'\n", fni
.fullname
);
837 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
838 printf("'%s' is %s (%s)\n\t",
840 isAbsolute
? "absolute" : "relative",
841 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
843 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
845 puts("ERROR (couldn't be normalized)");
849 printf("normalized: '%s'\n", fn
.GetFullPath(fni
.format
).c_str());
856 static void TestFileNameSplit()
858 puts("*** testing wxFileName splitting ***");
860 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
862 const FileNameInfo
& fni
= filenames
[n
];
863 wxString volume
, path
, name
, ext
;
864 wxFileName::SplitPath(fni
.fullname
,
865 &volume
, &path
, &name
, &ext
, fni
.format
);
867 printf("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'",
869 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
871 if ( volume
!= fni
.volume
)
872 printf(" (ERROR: volume = '%s')", fni
.volume
);
873 if ( path
!= fni
.path
)
874 printf(" (ERROR: path = '%s')", fni
.path
);
875 if ( name
!= fni
.name
)
876 printf(" (ERROR: name = '%s')", fni
.name
);
877 if ( ext
!= fni
.ext
)
878 printf(" (ERROR: ext = '%s')", fni
.ext
);
884 static void TestFileNameTemp()
886 puts("*** testing wxFileName temp file creation ***");
888 static const char *tmpprefixes
[] =
896 "/tmp/foo/bar", // this one must be an error
900 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
902 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
905 // "error" is not in upper case because it may be ok
906 printf("Prefix '%s'\t-> error\n", tmpprefixes
[n
]);
910 printf("Prefix '%s'\t-> temp file '%s'\n",
911 tmpprefixes
[n
], path
.c_str());
913 if ( !wxRemoveFile(path
) )
915 wxLogWarning("Failed to remove temp file '%s'", path
.c_str());
921 static void TestFileNameMakeRelative()
923 puts("*** testing wxFileName::MakeRelativeTo() ***");
925 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
927 const FileNameInfo
& fni
= filenames
[n
];
929 wxFileName
fn(fni
.fullname
, fni
.format
);
931 // choose the base dir of the same format
933 switch ( fni
.format
)
945 // TODO: I don't know how this is supposed to work there
948 case wxPATH_NATIVE
: // make gcc happy
950 wxFAIL_MSG( "unexpected path format" );
953 printf("'%s' relative to '%s': ",
954 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
956 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
962 printf("'%s'\n", fn
.GetFullPath(fni
.format
).c_str());
967 static void TestFileNameComparison()
972 static void TestFileNameOperations()
977 static void TestFileNameCwd()
982 #endif // TEST_FILENAME
984 // ----------------------------------------------------------------------------
985 // wxFileName time functions
986 // ----------------------------------------------------------------------------
990 #include <wx/filename.h>
991 #include <wx/datetime.h>
993 static void TestFileGetTimes()
995 wxFileName
fn(_T("testdata.fc"));
997 wxDateTime dtAccess
, dtMod
, dtCreate
;
998 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
1000 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
1004 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
1006 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
1007 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
1008 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
1009 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
1013 static void TestFileSetTimes()
1015 wxFileName
fn(_T("testdata.fc"));
1019 wxPrintf(_T("ERROR: Touch() failed.\n"));
1023 #endif // TEST_FILETIME
1025 // ----------------------------------------------------------------------------
1027 // ----------------------------------------------------------------------------
1031 #include "wx/hash.h"
1035 Foo(int n_
) { n
= n_
; count
++; }
1040 static size_t count
;
1043 size_t Foo::count
= 0;
1045 WX_DECLARE_LIST(Foo
, wxListFoos
);
1046 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
1048 #include "wx/listimpl.cpp"
1050 WX_DEFINE_LIST(wxListFoos
);
1052 static void TestHash()
1054 puts("*** Testing wxHashTable ***\n");
1058 hash
.DeleteContents(TRUE
);
1060 printf("Hash created: %u foos in hash, %u foos totally\n",
1061 hash
.GetCount(), Foo::count
);
1063 static const int hashTestData
[] =
1065 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
1069 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1071 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
1074 printf("Hash filled: %u foos in hash, %u foos totally\n",
1075 hash
.GetCount(), Foo::count
);
1077 puts("Hash access test:");
1078 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1080 printf("\tGetting element with key %d, value %d: ",
1081 hashTestData
[n
], n
);
1082 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1085 printf("ERROR, not found.\n");
1089 printf("%d (%s)\n", foo
->n
,
1090 (size_t)foo
->n
== n
? "ok" : "ERROR");
1094 printf("\nTrying to get an element not in hash: ");
1096 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1098 puts("ERROR: found!");
1102 puts("ok (not found)");
1106 printf("Hash destroyed: %u foos left\n", Foo::count
);
1111 // ----------------------------------------------------------------------------
1113 // ----------------------------------------------------------------------------
1117 #include "wx/hashmap.h"
1119 // test compilation of basic map types
1120 WX_DECLARE_HASH_MAP( int*, int*, wxPointerHash
, wxPointerEqual
, myPtrHashMap
);
1121 WX_DECLARE_HASH_MAP( long, long, wxIntegerHash
, wxIntegerEqual
, myLongHashMap
);
1122 WX_DECLARE_HASH_MAP( unsigned long, unsigned, wxIntegerHash
, wxIntegerEqual
,
1123 myUnsignedHashMap
);
1124 WX_DECLARE_HASH_MAP( unsigned int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1126 WX_DECLARE_HASH_MAP( int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1128 WX_DECLARE_HASH_MAP( short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1130 WX_DECLARE_HASH_MAP( unsigned short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1134 // WX_DECLARE_HASH_MAP( wxString, wxString, wxStringHash, wxStringEqual,
1135 // myStringHashMap );
1136 WX_DECLARE_STRING_HASH_MAP(wxString
, myStringHashMap
);
1138 typedef myStringHashMap::iterator Itor
;
1140 static void TestHashMap()
1142 puts("*** Testing wxHashMap ***\n");
1143 myStringHashMap
sh(0); // as small as possible
1146 const size_t count
= 10000;
1148 // init with some data
1149 for( i
= 0; i
< count
; ++i
)
1151 buf
.Printf(wxT("%d"), i
);
1152 sh
[buf
] = wxT("A") + buf
+ wxT("C");
1155 // test that insertion worked
1156 if( sh
.size() != count
)
1158 printf("*** ERROR: %u ELEMENTS, SHOULD BE %u ***\n", sh
.size(), count
);
1161 for( i
= 0; i
< count
; ++i
)
1163 buf
.Printf(wxT("%d"), i
);
1164 if( sh
[buf
] != wxT("A") + buf
+ wxT("C") )
1166 printf("*** ERROR INSERTION BROKEN! STOPPING NOW! ***\n");
1171 // check that iterators work
1173 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1177 printf("*** ERROR ITERATORS DO NOT TERMINATE! STOPPING NOW! ***\n");
1181 if( it
->second
!= sh
[it
->first
] )
1183 printf("*** ERROR ITERATORS BROKEN! STOPPING NOW! ***\n");
1188 if( sh
.size() != i
)
1190 printf("*** ERROR: %u ELEMENTS ITERATED, SHOULD BE %u ***\n", i
, count
);
1193 // test copy ctor, assignment operator
1194 myStringHashMap
h1( sh
), h2( 0 );
1197 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1199 if( h1
[it
->first
] != it
->second
)
1201 printf("*** ERROR: COPY CTOR BROKEN %s ***\n", it
->first
.c_str());
1204 if( h2
[it
->first
] != it
->second
)
1206 printf("*** ERROR: OPERATOR= BROKEN %s ***\n", it
->first
.c_str());
1211 for( i
= 0; i
< count
; ++i
)
1213 buf
.Printf(wxT("%d"), i
);
1214 size_t sz
= sh
.size();
1216 // test find() and erase(it)
1219 it
= sh
.find( buf
);
1220 if( it
!= sh
.end() )
1224 if( sh
.find( buf
) != sh
.end() )
1226 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1230 printf("*** ERROR: CANT FIND ELEMENT %u ***\n", i
);
1235 size_t c
= sh
.erase( buf
);
1237 printf("*** ERROR: SHOULD RETURN 1 ***\n");
1239 if( sh
.find( buf
) != sh
.end() )
1241 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1245 // count should decrease
1246 if( sh
.size() != sz
- 1 )
1248 printf("*** ERROR: COUNT DID NOT DECREASE ***\n");
1252 printf("*** Finished testing wxHashMap ***\n");
1255 #endif // TEST_HASHMAP
1257 // ----------------------------------------------------------------------------
1259 // ----------------------------------------------------------------------------
1263 #include "wx/list.h"
1265 WX_DECLARE_LIST(Bar
, wxListBars
);
1266 #include "wx/listimpl.cpp"
1267 WX_DEFINE_LIST(wxListBars
);
1269 static void TestListCtor()
1271 puts("*** Testing wxList construction ***\n");
1275 list1
.Append(new Bar(_T("first")));
1276 list1
.Append(new Bar(_T("second")));
1278 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1279 list1
.GetCount(), Bar::GetNumber());
1284 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1285 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1287 list1
.DeleteContents(TRUE
);
1290 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1295 // ----------------------------------------------------------------------------
1297 // ----------------------------------------------------------------------------
1301 #include "wx/intl.h"
1302 #include "wx/utils.h" // for wxSetEnv
1304 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1306 // find the name of the language from its value
1307 static const char *GetLangName(int lang
)
1309 static const char *languageNames
[] =
1330 "ARABIC_SAUDI_ARABIA",
1355 "CHINESE_SIMPLIFIED",
1356 "CHINESE_TRADITIONAL",
1359 "CHINESE_SINGAPORE",
1370 "ENGLISH_AUSTRALIA",
1374 "ENGLISH_CARIBBEAN",
1378 "ENGLISH_NEW_ZEALAND",
1379 "ENGLISH_PHILIPPINES",
1380 "ENGLISH_SOUTH_AFRICA",
1392 "FRENCH_LUXEMBOURG",
1401 "GERMAN_LIECHTENSTEIN",
1402 "GERMAN_LUXEMBOURG",
1443 "MALAY_BRUNEI_DARUSSALAM",
1455 "NORWEGIAN_NYNORSK",
1462 "PORTUGUESE_BRAZILIAN",
1487 "SPANISH_ARGENTINA",
1491 "SPANISH_COSTA_RICA",
1492 "SPANISH_DOMINICAN_REPUBLIC",
1494 "SPANISH_EL_SALVADOR",
1495 "SPANISH_GUATEMALA",
1499 "SPANISH_NICARAGUA",
1503 "SPANISH_PUERTO_RICO",
1506 "SPANISH_VENEZUELA",
1543 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1544 return languageNames
[lang
];
1549 static void TestDefaultLang()
1551 puts("*** Testing wxLocale::GetSystemLanguage ***");
1553 static const wxChar
*langStrings
[] =
1555 NULL
, // system default
1562 _T("de_DE.iso88591"),
1564 _T("?"), // invalid lang spec
1565 _T("klingonese"), // I bet on some systems it does exist...
1568 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1569 wxLocale::GetSystemEncodingName().c_str(),
1570 wxLocale::GetSystemEncoding());
1572 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1574 const char *langStr
= langStrings
[n
];
1577 // FIXME: this doesn't do anything at all under Windows, we need
1578 // to create a new wxLocale!
1579 wxSetEnv(_T("LC_ALL"), langStr
);
1582 int lang
= gs_localeDefault
.GetSystemLanguage();
1583 printf("Locale for '%s' is %s.\n",
1584 langStr
? langStr
: "system default", GetLangName(lang
));
1588 #endif // TEST_LOCALE
1590 // ----------------------------------------------------------------------------
1592 // ----------------------------------------------------------------------------
1596 #include "wx/mimetype.h"
1598 static void TestMimeEnum()
1600 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1602 wxArrayString mimetypes
;
1604 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1606 printf("*** All %u known filetypes: ***\n", count
);
1611 for ( size_t n
= 0; n
< count
; n
++ )
1613 wxFileType
*filetype
=
1614 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1617 printf("nothing known about the filetype '%s'!\n",
1618 mimetypes
[n
].c_str());
1622 filetype
->GetDescription(&desc
);
1623 filetype
->GetExtensions(exts
);
1625 filetype
->GetIcon(NULL
);
1628 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1631 extsAll
<< _T(", ");
1635 printf("\t%s: %s (%s)\n",
1636 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1642 static void TestMimeOverride()
1644 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1646 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1647 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1649 if ( wxFile::Exists(mailcap
) )
1650 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1652 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1654 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1657 if ( wxFile::Exists(mimetypes
) )
1658 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1660 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1662 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1668 static void TestMimeFilename()
1670 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1672 static const wxChar
*filenames
[] =
1679 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1681 const wxString fname
= filenames
[n
];
1682 wxString ext
= fname
.AfterLast(_T('.'));
1683 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1686 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1691 if ( !ft
->GetDescription(&desc
) )
1692 desc
= _T("<no description>");
1695 if ( !ft
->GetOpenCommand(&cmd
,
1696 wxFileType::MessageParameters(fname
, _T(""))) )
1697 cmd
= _T("<no command available>");
1699 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1700 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1709 static void TestMimeAssociate()
1711 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1713 wxFileTypeInfo
ftInfo(
1714 _T("application/x-xyz"),
1715 _T("xyzview '%s'"), // open cmd
1716 _T(""), // print cmd
1717 _T("XYZ File"), // description
1718 _T(".xyz"), // extensions
1719 NULL
// end of extensions
1721 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1723 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1726 wxPuts(_T("ERROR: failed to create association!"));
1730 // TODO: read it back
1739 // ----------------------------------------------------------------------------
1740 // misc information functions
1741 // ----------------------------------------------------------------------------
1743 #ifdef TEST_INFO_FUNCTIONS
1745 #include "wx/utils.h"
1747 static void TestDiskInfo()
1749 puts("*** Testing wxGetDiskSpace() ***");
1754 printf("\nEnter a directory name: ");
1755 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1758 // kill the last '\n'
1759 pathname
[strlen(pathname
) - 1] = 0;
1761 wxLongLong total
, free
;
1762 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1764 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1768 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1769 (total
/ 1024).ToString().c_str(),
1770 (free
/ 1024).ToString().c_str(),
1776 static void TestOsInfo()
1778 puts("*** Testing OS info functions ***\n");
1781 wxGetOsVersion(&major
, &minor
);
1782 printf("Running under: %s, version %d.%d\n",
1783 wxGetOsDescription().c_str(), major
, minor
);
1785 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1787 printf("Host name is %s (%s).\n",
1788 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1793 static void TestUserInfo()
1795 puts("*** Testing user info functions ***\n");
1797 printf("User id is:\t%s\n", wxGetUserId().c_str());
1798 printf("User name is:\t%s\n", wxGetUserName().c_str());
1799 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1800 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1805 #endif // TEST_INFO_FUNCTIONS
1807 // ----------------------------------------------------------------------------
1809 // ----------------------------------------------------------------------------
1811 #ifdef TEST_LONGLONG
1813 #include "wx/longlong.h"
1814 #include "wx/timer.h"
1816 // make a 64 bit number from 4 16 bit ones
1817 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1819 // get a random 64 bit number
1820 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1822 static const long testLongs
[] =
1833 #if wxUSE_LONGLONG_WX
1834 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1835 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1836 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1837 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1838 #endif // wxUSE_LONGLONG_WX
1840 static void TestSpeed()
1842 static const long max
= 100000000;
1849 for ( n
= 0; n
< max
; n
++ )
1854 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1857 #if wxUSE_LONGLONG_NATIVE
1862 for ( n
= 0; n
< max
; n
++ )
1867 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1869 #endif // wxUSE_LONGLONG_NATIVE
1875 for ( n
= 0; n
< max
; n
++ )
1880 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1884 static void TestLongLongConversion()
1886 puts("*** Testing wxLongLong conversions ***\n");
1890 for ( size_t n
= 0; n
< 100000; n
++ )
1894 #if wxUSE_LONGLONG_NATIVE
1895 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1897 wxASSERT_MSG( a
== b
, "conversions failure" );
1899 puts("Can't do it without native long long type, test skipped.");
1902 #endif // wxUSE_LONGLONG_NATIVE
1904 if ( !(nTested
% 1000) )
1916 static void TestMultiplication()
1918 puts("*** Testing wxLongLong multiplication ***\n");
1922 for ( size_t n
= 0; n
< 100000; n
++ )
1927 #if wxUSE_LONGLONG_NATIVE
1928 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1929 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1931 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1932 #else // !wxUSE_LONGLONG_NATIVE
1933 puts("Can't do it without native long long type, test skipped.");
1936 #endif // wxUSE_LONGLONG_NATIVE
1938 if ( !(nTested
% 1000) )
1950 static void TestDivision()
1952 puts("*** Testing wxLongLong division ***\n");
1956 for ( size_t n
= 0; n
< 100000; n
++ )
1958 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1959 // multiplication will not overflow)
1960 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1962 // get a random (but non null) long (not wxLongLong for now) to divide
1974 #if wxUSE_LONGLONG_NATIVE
1975 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1977 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1978 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1979 #else // !wxUSE_LONGLONG_NATIVE
1980 // verify the result
1981 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1982 #endif // wxUSE_LONGLONG_NATIVE
1984 if ( !(nTested
% 1000) )
1996 static void TestAddition()
1998 puts("*** Testing wxLongLong addition ***\n");
2002 for ( size_t n
= 0; n
< 100000; n
++ )
2008 #if wxUSE_LONGLONG_NATIVE
2009 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
2010 wxLongLongNative(b
.GetHi(), b
.GetLo()),
2011 "addition failure" );
2012 #else // !wxUSE_LONGLONG_NATIVE
2013 wxASSERT_MSG( c
- b
== a
, "addition failure" );
2014 #endif // wxUSE_LONGLONG_NATIVE
2016 if ( !(nTested
% 1000) )
2028 static void TestBitOperations()
2030 puts("*** Testing wxLongLong bit operation ***\n");
2034 for ( size_t n
= 0; n
< 100000; n
++ )
2038 #if wxUSE_LONGLONG_NATIVE
2039 for ( size_t n
= 0; n
< 33; n
++ )
2042 #else // !wxUSE_LONGLONG_NATIVE
2043 puts("Can't do it without native long long type, test skipped.");
2046 #endif // wxUSE_LONGLONG_NATIVE
2048 if ( !(nTested
% 1000) )
2060 static void TestLongLongComparison()
2062 #if wxUSE_LONGLONG_WX
2063 puts("*** Testing wxLongLong comparison ***\n");
2065 static const long ls
[2] =
2071 wxLongLongWx lls
[2];
2075 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2079 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
2081 res
= lls
[m
] > testLongs
[n
];
2082 printf("0x%lx > 0x%lx is %s (%s)\n",
2083 ls
[m
], testLongs
[n
], res
? "true" : "false",
2084 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
2086 res
= lls
[m
] < testLongs
[n
];
2087 printf("0x%lx < 0x%lx is %s (%s)\n",
2088 ls
[m
], testLongs
[n
], res
? "true" : "false",
2089 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
2091 res
= lls
[m
] == testLongs
[n
];
2092 printf("0x%lx == 0x%lx is %s (%s)\n",
2093 ls
[m
], testLongs
[n
], res
? "true" : "false",
2094 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
2097 #endif // wxUSE_LONGLONG_WX
2100 static void TestLongLongPrint()
2102 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
2104 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2106 wxLongLong ll
= testLongs
[n
];
2107 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
2110 wxLongLong
ll(0x12345678, 0x87654321);
2111 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2114 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2120 #endif // TEST_LONGLONG
2122 // ----------------------------------------------------------------------------
2124 // ----------------------------------------------------------------------------
2126 #ifdef TEST_PATHLIST
2128 static void TestPathList()
2130 puts("*** Testing wxPathList ***\n");
2132 wxPathList pathlist
;
2133 pathlist
.AddEnvList("PATH");
2134 wxString path
= pathlist
.FindValidPath("ls");
2137 printf("ERROR: command not found in the path.\n");
2141 printf("Command found in the path as '%s'.\n", path
.c_str());
2145 #endif // TEST_PATHLIST
2147 // ----------------------------------------------------------------------------
2148 // regular expressions
2149 // ----------------------------------------------------------------------------
2153 #include "wx/regex.h"
2155 static void TestRegExCompile()
2157 wxPuts(_T("*** Testing RE compilation ***\n"));
2159 static struct RegExCompTestData
2161 const wxChar
*pattern
;
2163 } regExCompTestData
[] =
2165 { _T("foo"), TRUE
},
2166 { _T("foo("), FALSE
},
2167 { _T("foo(bar"), FALSE
},
2168 { _T("foo(bar)"), TRUE
},
2169 { _T("foo["), FALSE
},
2170 { _T("foo[bar"), FALSE
},
2171 { _T("foo[bar]"), TRUE
},
2172 { _T("foo{"), TRUE
},
2173 { _T("foo{1"), FALSE
},
2174 { _T("foo{bar"), TRUE
},
2175 { _T("foo{1}"), TRUE
},
2176 { _T("foo{1,2}"), TRUE
},
2177 { _T("foo{bar}"), TRUE
},
2178 { _T("foo*"), TRUE
},
2179 { _T("foo**"), FALSE
},
2180 { _T("foo+"), TRUE
},
2181 { _T("foo++"), FALSE
},
2182 { _T("foo?"), TRUE
},
2183 { _T("foo??"), FALSE
},
2184 { _T("foo?+"), FALSE
},
2188 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
2190 const RegExCompTestData
& data
= regExCompTestData
[n
];
2191 bool ok
= re
.Compile(data
.pattern
);
2193 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
2195 ok
? _T("") : _T("not "),
2196 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2200 static void TestRegExMatch()
2202 wxPuts(_T("*** Testing RE matching ***\n"));
2204 static struct RegExMatchTestData
2206 const wxChar
*pattern
;
2209 } regExMatchTestData
[] =
2211 { _T("foo"), _T("bar"), FALSE
},
2212 { _T("foo"), _T("foobar"), TRUE
},
2213 { _T("^foo"), _T("foobar"), TRUE
},
2214 { _T("^foo"), _T("barfoo"), FALSE
},
2215 { _T("bar$"), _T("barbar"), TRUE
},
2216 { _T("bar$"), _T("barbar "), FALSE
},
2219 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
2221 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
2223 wxRegEx
re(data
.pattern
);
2224 bool ok
= re
.Matches(data
.text
);
2226 wxPrintf(_T("'%s' %s %s (%s)\n"),
2228 ok
? _T("matches") : _T("doesn't match"),
2230 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2234 static void TestRegExSubmatch()
2236 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2238 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2239 if ( !re
.IsValid() )
2241 wxPuts(_T("ERROR: compilation failed."));
2245 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2247 if ( !re
.Matches(text
) )
2249 wxPuts(_T("ERROR: match expected."));
2253 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2255 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2256 re
.GetMatch(text
, 3).c_str(),
2257 re
.GetMatch(text
, 2).c_str(),
2258 re
.GetMatch(text
, 4).c_str(),
2259 re
.GetMatch(text
, 1).c_str());
2263 static void TestRegExReplacement()
2265 wxPuts(_T("*** Testing RE replacement ***"));
2267 static struct RegExReplTestData
2271 const wxChar
*result
;
2273 } regExReplTestData
[] =
2275 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2276 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2277 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2278 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2279 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2280 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2281 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2284 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2285 wxRegEx
re(pattern
);
2287 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2289 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2291 const RegExReplTestData
& data
= regExReplTestData
[n
];
2293 wxString text
= data
.text
;
2294 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2296 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2297 data
.text
, data
.repl
,
2298 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2300 if ( text
== data
.result
&& nRepl
== data
.count
)
2306 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2307 data
.count
, data
.result
);
2312 static void TestRegExInteractive()
2314 wxPuts(_T("*** Testing RE interactively ***"));
2319 printf("\nEnter a pattern: ");
2320 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2323 // kill the last '\n'
2324 pattern
[strlen(pattern
) - 1] = 0;
2327 if ( !re
.Compile(pattern
) )
2335 printf("Enter text to match: ");
2336 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2339 // kill the last '\n'
2340 text
[strlen(text
) - 1] = 0;
2342 if ( !re
.Matches(text
) )
2344 printf("No match.\n");
2348 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2351 for ( size_t n
= 1; ; n
++ )
2353 if ( !re
.GetMatch(&start
, &len
, n
) )
2358 printf("Subexpr %u matched '%s'\n",
2359 n
, wxString(text
+ start
, len
).c_str());
2366 #endif // TEST_REGEX
2368 // ----------------------------------------------------------------------------
2370 // ----------------------------------------------------------------------------
2376 static void TestDbOpen()
2384 // ----------------------------------------------------------------------------
2385 // registry and related stuff
2386 // ----------------------------------------------------------------------------
2388 // this is for MSW only
2391 #undef TEST_REGISTRY
2396 #include "wx/confbase.h"
2397 #include "wx/msw/regconf.h"
2399 static void TestRegConfWrite()
2401 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2402 regconf
.Write(_T("Hello"), wxString(_T("world")));
2405 #endif // TEST_REGCONF
2407 #ifdef TEST_REGISTRY
2409 #include "wx/msw/registry.h"
2411 // I chose this one because I liked its name, but it probably only exists under
2413 static const wxChar
*TESTKEY
=
2414 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2416 static void TestRegistryRead()
2418 puts("*** testing registry reading ***");
2420 wxRegKey
key(TESTKEY
);
2421 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2424 puts("ERROR: test key can't be opened, aborting test.");
2429 size_t nSubKeys
, nValues
;
2430 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2432 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2435 printf("Enumerating values:\n");
2439 bool cont
= key
.GetFirstValue(value
, dummy
);
2442 printf("Value '%s': type ", value
.c_str());
2443 switch ( key
.GetValueType(value
) )
2445 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2446 case wxRegKey::Type_String
: printf("SZ"); break;
2447 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2448 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2449 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2450 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2451 default: printf("other (unknown)"); break;
2454 printf(", value = ");
2455 if ( key
.IsNumericValue(value
) )
2458 key
.QueryValue(value
, &val
);
2464 key
.QueryValue(value
, val
);
2465 printf("'%s'", val
.c_str());
2467 key
.QueryRawValue(value
, val
);
2468 printf(" (raw value '%s')", val
.c_str());
2473 cont
= key
.GetNextValue(value
, dummy
);
2477 static void TestRegistryAssociation()
2480 The second call to deleteself genertaes an error message, with a
2481 messagebox saying .flo is crucial to system operation, while the .ddf
2482 call also fails, but with no error message
2487 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2489 key
= "ddxf_auto_file" ;
2490 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2492 key
= "ddxf_auto_file" ;
2493 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2496 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2498 key
= "program \"%1\"" ;
2500 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2502 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2504 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2506 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2510 #endif // TEST_REGISTRY
2512 // ----------------------------------------------------------------------------
2514 // ----------------------------------------------------------------------------
2518 #include "wx/socket.h"
2519 #include "wx/protocol/protocol.h"
2520 #include "wx/protocol/http.h"
2522 static void TestSocketServer()
2524 puts("*** Testing wxSocketServer ***\n");
2526 static const int PORT
= 3000;
2531 wxSocketServer
*server
= new wxSocketServer(addr
);
2532 if ( !server
->Ok() )
2534 puts("ERROR: failed to bind");
2541 printf("Server: waiting for connection on port %d...\n", PORT
);
2543 wxSocketBase
*socket
= server
->Accept();
2546 puts("ERROR: wxSocketServer::Accept() failed.");
2550 puts("Server: got a client.");
2552 server
->SetTimeout(60); // 1 min
2554 while ( socket
->IsConnected() )
2560 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2562 // don't log error if the client just close the connection
2563 if ( socket
->IsConnected() )
2565 puts("ERROR: in wxSocket::Read.");
2585 printf("Server: got '%s'.\n", s
.c_str());
2586 if ( s
== _T("bye") )
2593 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2594 socket
->Write("\r\n", 2);
2595 printf("Server: wrote '%s'.\n", s
.c_str());
2598 puts("Server: lost a client.");
2603 // same as "delete server" but is consistent with GUI programs
2607 static void TestSocketClient()
2609 puts("*** Testing wxSocketClient ***\n");
2611 static const char *hostname
= "www.wxwindows.org";
2614 addr
.Hostname(hostname
);
2617 printf("--- Attempting to connect to %s:80...\n", hostname
);
2619 wxSocketClient client
;
2620 if ( !client
.Connect(addr
) )
2622 printf("ERROR: failed to connect to %s\n", hostname
);
2626 printf("--- Connected to %s:%u...\n",
2627 addr
.Hostname().c_str(), addr
.Service());
2631 // could use simply "GET" here I suppose
2633 wxString::Format("GET http://%s/\r\n", hostname
);
2634 client
.Write(cmdGet
, cmdGet
.length());
2635 printf("--- Sent command '%s' to the server\n",
2636 MakePrintable(cmdGet
).c_str());
2637 client
.Read(buf
, WXSIZEOF(buf
));
2638 printf("--- Server replied:\n%s", buf
);
2642 #endif // TEST_SOCKETS
2644 // ----------------------------------------------------------------------------
2646 // ----------------------------------------------------------------------------
2650 #include "wx/protocol/ftp.h"
2654 #define FTP_ANONYMOUS
2656 #ifdef FTP_ANONYMOUS
2657 static const char *directory
= "/pub";
2658 static const char *filename
= "welcome.msg";
2660 static const char *directory
= "/etc";
2661 static const char *filename
= "issue";
2664 static bool TestFtpConnect()
2666 puts("*** Testing FTP connect ***");
2668 #ifdef FTP_ANONYMOUS
2669 static const char *hostname
= "ftp.wxwindows.org";
2671 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2672 #else // !FTP_ANONYMOUS
2673 static const char *hostname
= "localhost";
2676 fgets(user
, WXSIZEOF(user
), stdin
);
2677 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2681 printf("Password for %s: ", password
);
2682 fgets(password
, WXSIZEOF(password
), stdin
);
2683 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2684 ftp
.SetPassword(password
);
2686 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2687 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2689 if ( !ftp
.Connect(hostname
) )
2691 printf("ERROR: failed to connect to %s\n", hostname
);
2697 printf("--- Connected to %s, current directory is '%s'\n",
2698 hostname
, ftp
.Pwd().c_str());
2704 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2705 static void TestFtpWuFtpd()
2708 static const char *hostname
= "ftp.eudora.com";
2709 if ( !ftp
.Connect(hostname
) )
2711 printf("ERROR: failed to connect to %s\n", hostname
);
2715 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2716 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2719 printf("ERROR: couldn't get input stream for %s\n", filename
);
2723 size_t size
= in
->StreamSize();
2724 printf("Reading file %s (%u bytes)...", filename
, size
);
2726 char *data
= new char[size
];
2727 if ( !in
->Read(data
, size
) )
2729 puts("ERROR: read error");
2733 printf("Successfully retrieved the file.\n");
2742 static void TestFtpList()
2744 puts("*** Testing wxFTP file listing ***\n");
2747 if ( !ftp
.ChDir(directory
) )
2749 printf("ERROR: failed to cd to %s\n", directory
);
2752 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2754 // test NLIST and LIST
2755 wxArrayString files
;
2756 if ( !ftp
.GetFilesList(files
) )
2758 puts("ERROR: failed to get NLIST of files");
2762 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2763 size_t count
= files
.GetCount();
2764 for ( size_t n
= 0; n
< count
; n
++ )
2766 printf("\t%s\n", files
[n
].c_str());
2768 puts("End of the file list");
2771 if ( !ftp
.GetDirList(files
) )
2773 puts("ERROR: failed to get LIST of files");
2777 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2778 size_t count
= files
.GetCount();
2779 for ( size_t n
= 0; n
< count
; n
++ )
2781 printf("\t%s\n", files
[n
].c_str());
2783 puts("End of the file list");
2786 if ( !ftp
.ChDir(_T("..")) )
2788 puts("ERROR: failed to cd to ..");
2791 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2794 static void TestFtpDownload()
2796 puts("*** Testing wxFTP download ***\n");
2799 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2802 printf("ERROR: couldn't get input stream for %s\n", filename
);
2806 size_t size
= in
->StreamSize();
2807 printf("Reading file %s (%u bytes)...", filename
, size
);
2810 char *data
= new char[size
];
2811 if ( !in
->Read(data
, size
) )
2813 puts("ERROR: read error");
2817 printf("\nContents of %s:\n%s\n", filename
, data
);
2825 static void TestFtpFileSize()
2827 puts("*** Testing FTP SIZE command ***");
2829 if ( !ftp
.ChDir(directory
) )
2831 printf("ERROR: failed to cd to %s\n", directory
);
2834 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2836 if ( ftp
.FileExists(filename
) )
2838 int size
= ftp
.GetFileSize(filename
);
2840 printf("ERROR: couldn't get size of '%s'\n", filename
);
2842 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2846 printf("ERROR: '%s' doesn't exist\n", filename
);
2850 static void TestFtpMisc()
2852 puts("*** Testing miscellaneous wxFTP functions ***");
2854 if ( ftp
.SendCommand("STAT") != '2' )
2856 puts("ERROR: STAT failed");
2860 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2863 if ( ftp
.SendCommand("HELP SITE") != '2' )
2865 puts("ERROR: HELP SITE failed");
2869 printf("The list of site-specific commands:\n\n%s\n",
2870 ftp
.GetLastResult().c_str());
2874 static void TestFtpInteractive()
2876 puts("\n*** Interactive wxFTP test ***");
2882 printf("Enter FTP command: ");
2883 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2886 // kill the last '\n'
2887 buf
[strlen(buf
) - 1] = 0;
2889 // special handling of LIST and NLST as they require data connection
2890 wxString
start(buf
, 4);
2892 if ( start
== "LIST" || start
== "NLST" )
2895 if ( strlen(buf
) > 4 )
2898 wxArrayString files
;
2899 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2901 printf("ERROR: failed to get %s of files\n", start
.c_str());
2905 printf("--- %s of '%s' under '%s':\n",
2906 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2907 size_t count
= files
.GetCount();
2908 for ( size_t n
= 0; n
< count
; n
++ )
2910 printf("\t%s\n", files
[n
].c_str());
2912 puts("--- End of the file list");
2917 char ch
= ftp
.SendCommand(buf
);
2918 printf("Command %s", ch
? "succeeded" : "failed");
2921 printf(" (return code %c)", ch
);
2924 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2928 puts("\n*** done ***");
2931 static void TestFtpUpload()
2933 puts("*** Testing wxFTP uploading ***\n");
2936 static const char *file1
= "test1";
2937 static const char *file2
= "test2";
2938 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2941 printf("--- Uploading to %s ---\n", file1
);
2942 out
->Write("First hello", 11);
2946 // send a command to check the remote file
2947 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2949 printf("ERROR: STAT %s failed\n", file1
);
2953 printf("STAT %s returned:\n\n%s\n",
2954 file1
, ftp
.GetLastResult().c_str());
2957 out
= ftp
.GetOutputStream(file2
);
2960 printf("--- Uploading to %s ---\n", file1
);
2961 out
->Write("Second hello", 12);
2968 // ----------------------------------------------------------------------------
2970 // ----------------------------------------------------------------------------
2974 #include "wx/wfstream.h"
2975 #include "wx/mstream.h"
2977 static void TestFileStream()
2979 puts("*** Testing wxFileInputStream ***");
2981 static const wxChar
*filename
= _T("testdata.fs");
2983 wxFileOutputStream
fsOut(filename
);
2984 fsOut
.Write("foo", 3);
2987 wxFileInputStream
fsIn(filename
);
2988 printf("File stream size: %u\n", fsIn
.GetSize());
2989 while ( !fsIn
.Eof() )
2991 putchar(fsIn
.GetC());
2994 if ( !wxRemoveFile(filename
) )
2996 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2999 puts("\n*** wxFileInputStream test done ***");
3002 static void TestMemoryStream()
3004 puts("*** Testing wxMemoryInputStream ***");
3007 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
3009 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
3010 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
3011 while ( !memInpStream
.Eof() )
3013 putchar(memInpStream
.GetC());
3016 puts("\n*** wxMemoryInputStream test done ***");
3019 #endif // TEST_STREAMS
3021 // ----------------------------------------------------------------------------
3023 // ----------------------------------------------------------------------------
3027 #include "wx/timer.h"
3028 #include "wx/utils.h"
3030 static void TestStopWatch()
3032 puts("*** Testing wxStopWatch ***\n");
3036 printf("Initially paused, after 2 seconds time is...");
3039 printf("\t%ldms\n", sw
.Time());
3041 printf("Resuming stopwatch and sleeping 3 seconds...");
3045 printf("\telapsed time: %ldms\n", sw
.Time());
3048 printf("Pausing agan and sleeping 2 more seconds...");
3051 printf("\telapsed time: %ldms\n", sw
.Time());
3054 printf("Finally resuming and sleeping 2 more seconds...");
3057 printf("\telapsed time: %ldms\n", sw
.Time());
3060 puts("\nChecking for 'backwards clock' bug...");
3061 for ( size_t n
= 0; n
< 70; n
++ )
3065 for ( size_t m
= 0; m
< 100000; m
++ )
3067 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
3069 puts("\ntime is negative - ERROR!");
3080 #endif // TEST_TIMER
3082 // ----------------------------------------------------------------------------
3084 // ----------------------------------------------------------------------------
3088 #include "wx/vcard.h"
3090 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
3093 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
3097 wxString(_T('\t'), level
).c_str(),
3098 vcObj
->GetName().c_str());
3101 switch ( vcObj
->GetType() )
3103 case wxVCardObject::String
:
3104 case wxVCardObject::UString
:
3107 vcObj
->GetValue(&val
);
3108 value
<< _T('"') << val
<< _T('"');
3112 case wxVCardObject::Int
:
3115 vcObj
->GetValue(&i
);
3116 value
.Printf(_T("%u"), i
);
3120 case wxVCardObject::Long
:
3123 vcObj
->GetValue(&l
);
3124 value
.Printf(_T("%lu"), l
);
3128 case wxVCardObject::None
:
3131 case wxVCardObject::Object
:
3132 value
= _T("<node>");
3136 value
= _T("<unknown value type>");
3140 printf(" = %s", value
.c_str());
3143 DumpVObject(level
+ 1, *vcObj
);
3146 vcObj
= vcard
.GetNextProp(&cookie
);
3150 static void DumpVCardAddresses(const wxVCard
& vcard
)
3152 puts("\nShowing all addresses from vCard:\n");
3156 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3160 int flags
= addr
->GetFlags();
3161 if ( flags
& wxVCardAddress::Domestic
)
3163 flagsStr
<< _T("domestic ");
3165 if ( flags
& wxVCardAddress::Intl
)
3167 flagsStr
<< _T("international ");
3169 if ( flags
& wxVCardAddress::Postal
)
3171 flagsStr
<< _T("postal ");
3173 if ( flags
& wxVCardAddress::Parcel
)
3175 flagsStr
<< _T("parcel ");
3177 if ( flags
& wxVCardAddress::Home
)
3179 flagsStr
<< _T("home ");
3181 if ( flags
& wxVCardAddress::Work
)
3183 flagsStr
<< _T("work ");
3186 printf("Address %u:\n"
3188 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3191 addr
->GetPostOffice().c_str(),
3192 addr
->GetExtAddress().c_str(),
3193 addr
->GetStreet().c_str(),
3194 addr
->GetLocality().c_str(),
3195 addr
->GetRegion().c_str(),
3196 addr
->GetPostalCode().c_str(),
3197 addr
->GetCountry().c_str()
3201 addr
= vcard
.GetNextAddress(&cookie
);
3205 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3207 puts("\nShowing all phone numbers from vCard:\n");
3211 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3215 int flags
= phone
->GetFlags();
3216 if ( flags
& wxVCardPhoneNumber::Voice
)
3218 flagsStr
<< _T("voice ");
3220 if ( flags
& wxVCardPhoneNumber::Fax
)
3222 flagsStr
<< _T("fax ");
3224 if ( flags
& wxVCardPhoneNumber::Cellular
)
3226 flagsStr
<< _T("cellular ");
3228 if ( flags
& wxVCardPhoneNumber::Modem
)
3230 flagsStr
<< _T("modem ");
3232 if ( flags
& wxVCardPhoneNumber::Home
)
3234 flagsStr
<< _T("home ");
3236 if ( flags
& wxVCardPhoneNumber::Work
)
3238 flagsStr
<< _T("work ");
3241 printf("Phone number %u:\n"
3246 phone
->GetNumber().c_str()
3250 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3254 static void TestVCardRead()
3256 puts("*** Testing wxVCard reading ***\n");
3258 wxVCard
vcard(_T("vcard.vcf"));
3259 if ( !vcard
.IsOk() )
3261 puts("ERROR: couldn't load vCard.");
3265 // read individual vCard properties
3266 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3270 vcObj
->GetValue(&value
);
3275 value
= _T("<none>");
3278 printf("Full name retrieved directly: %s\n", value
.c_str());
3281 if ( !vcard
.GetFullName(&value
) )
3283 value
= _T("<none>");
3286 printf("Full name from wxVCard API: %s\n", value
.c_str());
3288 // now show how to deal with multiply occuring properties
3289 DumpVCardAddresses(vcard
);
3290 DumpVCardPhoneNumbers(vcard
);
3292 // and finally show all
3293 puts("\nNow dumping the entire vCard:\n"
3294 "-----------------------------\n");
3296 DumpVObject(0, vcard
);
3300 static void TestVCardWrite()
3302 puts("*** Testing wxVCard writing ***\n");
3305 if ( !vcard
.IsOk() )
3307 puts("ERROR: couldn't create vCard.");
3312 vcard
.SetName("Zeitlin", "Vadim");
3313 vcard
.SetFullName("Vadim Zeitlin");
3314 vcard
.SetOrganization("wxWindows", "R&D");
3316 // just dump the vCard back
3317 puts("Entire vCard follows:\n");
3318 puts(vcard
.Write());
3322 #endif // TEST_VCARD
3324 // ----------------------------------------------------------------------------
3326 // ----------------------------------------------------------------------------
3334 #include "wx/volume.h"
3336 static const wxChar
*volumeKinds
[] =
3342 _T("network volume"),
3346 static void TestFSVolume()
3348 wxPuts(_T("*** Testing wxFSVolume class ***"));
3350 wxArrayString volumes
= wxFSVolume::GetVolumes();
3351 size_t count
= volumes
.GetCount();
3355 wxPuts(_T("ERROR: no mounted volumes?"));
3359 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3361 for ( size_t n
= 0; n
< count
; n
++ )
3363 wxFSVolume
vol(volumes
[n
]);
3366 wxPuts(_T("ERROR: couldn't create volume"));
3370 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3372 vol
.GetDisplayName().c_str(),
3373 vol
.GetName().c_str(),
3374 volumeKinds
[vol
.GetKind()],
3375 vol
.IsWritable() ? _T("rw") : _T("ro"),
3376 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3381 #endif // TEST_VOLUME
3383 // ----------------------------------------------------------------------------
3384 // wide char (Unicode) support
3385 // ----------------------------------------------------------------------------
3389 #include "wx/strconv.h"
3390 #include "wx/fontenc.h"
3391 #include "wx/encconv.h"
3392 #include "wx/buffer.h"
3394 static const char textInUtf8
[] =
3396 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3397 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3398 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3399 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3400 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3401 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3402 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3405 static void TestUtf8()
3407 puts("*** Testing UTF8 support ***\n");
3411 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3413 puts("ERROR: UTF-8 decoding failed.");
3417 wxCSConv
conv(_T("koi8-r"));
3418 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3420 puts("ERROR: conversion to KOI8-R failed.");
3424 printf("The resulting string (in KOI8-R): %s\n", buf
);
3428 if ( wxConvUTF8
.WC2MB(buf
, L
"Ã la", WXSIZEOF(buf
)) <= 0 )
3430 puts("ERROR: conversion to UTF-8 failed.");
3434 printf("The string in UTF-8: %s\n", buf
);
3440 static void TestEncodingConverter()
3442 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3444 // using wxEncodingConverter should give the same result as above
3447 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3449 puts("ERROR: UTF-8 decoding failed.");
3453 wxEncodingConverter ec
;
3454 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3455 ec
.Convert(wbuf
, buf
);
3456 printf("The same string obtained using wxEC: %s\n", buf
);
3462 #endif // TEST_WCHAR
3464 // ----------------------------------------------------------------------------
3466 // ----------------------------------------------------------------------------
3470 #include "wx/filesys.h"
3471 #include "wx/fs_zip.h"
3472 #include "wx/zipstrm.h"
3474 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3476 static void TestZipStreamRead()
3478 puts("*** Testing ZIP reading ***\n");
3480 static const wxChar
*filename
= _T("foo");
3481 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3482 printf("Archive size: %u\n", istr
.GetSize());
3484 printf("Dumping the file '%s':\n", filename
);
3485 while ( !istr
.Eof() )
3487 putchar(istr
.GetC());
3491 puts("\n----- done ------");
3494 static void DumpZipDirectory(wxFileSystem
& fs
,
3495 const wxString
& dir
,
3496 const wxString
& indent
)
3498 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3499 TESTFILE_ZIP
, dir
.c_str());
3500 wxString wildcard
= prefix
+ _T("/*");
3502 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3503 while ( !dirname
.empty() )
3505 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3507 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3512 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3514 DumpZipDirectory(fs
, dirname
,
3515 indent
+ wxString(_T(' '), 4));
3517 dirname
= fs
.FindNext();
3520 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3521 while ( !filename
.empty() )
3523 if ( !filename
.StartsWith(prefix
, &filename
) )
3525 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3530 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3532 filename
= fs
.FindNext();
3536 static void TestZipFileSystem()
3538 puts("*** Testing ZIP file system ***\n");
3540 wxFileSystem::AddHandler(new wxZipFSHandler
);
3542 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3544 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3549 // ----------------------------------------------------------------------------
3551 // ----------------------------------------------------------------------------
3555 #include "wx/zstream.h"
3556 #include "wx/wfstream.h"
3558 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3559 static const char *TEST_DATA
= "hello and hello again";
3561 static void TestZlibStreamWrite()
3563 puts("*** Testing Zlib stream reading ***\n");
3565 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3566 wxZlibOutputStream
ostr(fileOutStream
, 0);
3567 printf("Compressing the test string... ");
3568 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3571 puts("(ERROR: failed)");
3578 puts("\n----- done ------");
3581 static void TestZlibStreamRead()
3583 puts("*** Testing Zlib stream reading ***\n");
3585 wxFileInputStream
fileInStream(FILENAME_GZ
);
3586 wxZlibInputStream
istr(fileInStream
);
3587 printf("Archive size: %u\n", istr
.GetSize());
3589 puts("Dumping the file:");
3590 while ( !istr
.Eof() )
3592 putchar(istr
.GetC());
3596 puts("\n----- done ------");
3601 // ----------------------------------------------------------------------------
3603 // ----------------------------------------------------------------------------
3605 #ifdef TEST_DATETIME
3609 #include "wx/date.h"
3610 #include "wx/datetime.h"
3615 wxDateTime::wxDateTime_t day
;
3616 wxDateTime::Month month
;
3618 wxDateTime::wxDateTime_t hour
, min
, sec
;
3620 wxDateTime::WeekDay wday
;
3621 time_t gmticks
, ticks
;
3623 void Init(const wxDateTime::Tm
& tm
)
3632 gmticks
= ticks
= -1;
3635 wxDateTime
DT() const
3636 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3638 bool SameDay(const wxDateTime::Tm
& tm
) const
3640 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3643 wxString
Format() const
3646 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3648 wxDateTime::GetMonthName(month
).c_str(),
3650 abs(wxDateTime::ConvertYearToBC(year
)),
3651 year
> 0 ? "AD" : "BC");
3655 wxString
FormatDate() const
3658 s
.Printf("%02d-%s-%4d%s",
3660 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3661 abs(wxDateTime::ConvertYearToBC(year
)),
3662 year
> 0 ? "AD" : "BC");
3667 static const Date testDates
[] =
3669 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3670 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3671 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3672 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3673 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3674 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3675 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3676 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3677 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3678 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3679 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3680 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3681 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3682 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3683 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3686 // this test miscellaneous static wxDateTime functions
3687 static void TestTimeStatic()
3689 puts("\n*** wxDateTime static methods test ***");
3691 // some info about the current date
3692 int year
= wxDateTime::GetCurrentYear();
3693 printf("Current year %d is %sa leap one and has %d days.\n",
3695 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3696 wxDateTime::GetNumberOfDays(year
));
3698 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3699 printf("Current month is '%s' ('%s') and it has %d days\n",
3700 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3701 wxDateTime::GetMonthName(month
).c_str(),
3702 wxDateTime::GetNumberOfDays(month
));
3705 static const size_t nYears
= 5;
3706 static const size_t years
[2][nYears
] =
3708 // first line: the years to test
3709 { 1990, 1976, 2000, 2030, 1984, },
3711 // second line: TRUE if leap, FALSE otherwise
3712 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3715 for ( size_t n
= 0; n
< nYears
; n
++ )
3717 int year
= years
[0][n
];
3718 bool should
= years
[1][n
] != 0,
3719 is
= wxDateTime::IsLeapYear(year
);
3721 printf("Year %d is %sa leap year (%s)\n",
3724 should
== is
? "ok" : "ERROR");
3726 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3730 // test constructing wxDateTime objects
3731 static void TestTimeSet()
3733 puts("\n*** wxDateTime construction test ***");
3735 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3737 const Date
& d1
= testDates
[n
];
3738 wxDateTime dt
= d1
.DT();
3741 d2
.Init(dt
.GetTm());
3743 wxString s1
= d1
.Format(),
3746 printf("Date: %s == %s (%s)\n",
3747 s1
.c_str(), s2
.c_str(),
3748 s1
== s2
? "ok" : "ERROR");
3752 // test time zones stuff
3753 static void TestTimeZones()
3755 puts("\n*** wxDateTime timezone test ***");
3757 wxDateTime now
= wxDateTime::Now();
3759 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3760 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3761 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3762 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3763 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3764 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3766 wxDateTime::Tm tm
= now
.GetTm();
3767 if ( wxDateTime(tm
) != now
)
3769 printf("ERROR: got %s instead of %s\n",
3770 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3774 // test some minimal support for the dates outside the standard range
3775 static void TestTimeRange()
3777 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3779 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3781 printf("Unix epoch:\t%s\n",
3782 wxDateTime(2440587.5).Format(fmt
).c_str());
3783 printf("Feb 29, 0: \t%s\n",
3784 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3785 printf("JDN 0: \t%s\n",
3786 wxDateTime(0.0).Format(fmt
).c_str());
3787 printf("Jan 1, 1AD:\t%s\n",
3788 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3789 printf("May 29, 2099:\t%s\n",
3790 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3793 static void TestTimeTicks()
3795 puts("\n*** wxDateTime ticks test ***");
3797 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3799 const Date
& d
= testDates
[n
];
3800 if ( d
.ticks
== -1 )
3803 wxDateTime dt
= d
.DT();
3804 long ticks
= (dt
.GetValue() / 1000).ToLong();
3805 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3806 if ( ticks
== d
.ticks
)
3812 printf(" (ERROR: should be %ld, delta = %ld)\n",
3813 d
.ticks
, ticks
- d
.ticks
);
3816 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3817 ticks
= (dt
.GetValue() / 1000).ToLong();
3818 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3819 if ( ticks
== d
.gmticks
)
3825 printf(" (ERROR: should be %ld, delta = %ld)\n",
3826 d
.gmticks
, ticks
- d
.gmticks
);
3833 // test conversions to JDN &c
3834 static void TestTimeJDN()
3836 puts("\n*** wxDateTime to JDN test ***");
3838 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3840 const Date
& d
= testDates
[n
];
3841 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3842 double jdn
= dt
.GetJulianDayNumber();
3844 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3851 printf(" (ERROR: should be %f, delta = %f)\n",
3852 d
.jdn
, jdn
- d
.jdn
);
3857 // test week days computation
3858 static void TestTimeWDays()
3860 puts("\n*** wxDateTime weekday test ***");
3862 // test GetWeekDay()
3864 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3866 const Date
& d
= testDates
[n
];
3867 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3869 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3872 wxDateTime::GetWeekDayName(wday
).c_str());
3873 if ( wday
== d
.wday
)
3879 printf(" (ERROR: should be %s)\n",
3880 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3886 // test SetToWeekDay()
3887 struct WeekDateTestData
3889 Date date
; // the real date (precomputed)
3890 int nWeek
; // its week index in the month
3891 wxDateTime::WeekDay wday
; // the weekday
3892 wxDateTime::Month month
; // the month
3893 int year
; // and the year
3895 wxString
Format() const
3898 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3900 case 1: which
= "first"; break;
3901 case 2: which
= "second"; break;
3902 case 3: which
= "third"; break;
3903 case 4: which
= "fourth"; break;
3904 case 5: which
= "fifth"; break;
3906 case -1: which
= "last"; break;
3911 which
+= " from end";
3914 s
.Printf("The %s %s of %s in %d",
3916 wxDateTime::GetWeekDayName(wday
).c_str(),
3917 wxDateTime::GetMonthName(month
).c_str(),
3924 // the array data was generated by the following python program
3926 from DateTime import *
3927 from whrandom import *
3928 from string import *
3930 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3931 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3933 week = DateTimeDelta(7)
3936 year = randint(1900, 2100)
3937 month = randint(1, 12)
3938 day = randint(1, 28)
3939 dt = DateTime(year, month, day)
3940 wday = dt.day_of_week
3942 countFromEnd = choice([-1, 1])
3945 while dt.month is month:
3946 dt = dt - countFromEnd * week
3947 weekNum = weekNum + countFromEnd
3949 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3951 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3952 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3955 static const WeekDateTestData weekDatesTestData
[] =
3957 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3958 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3959 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3960 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3961 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3962 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3963 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3964 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3965 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3966 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3967 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3968 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3969 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3970 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3971 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3972 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3973 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3974 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3975 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3976 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3979 static const char *fmt
= "%d-%b-%Y";
3982 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3984 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3986 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3988 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3990 const Date
& d
= wd
.date
;
3991 if ( d
.SameDay(dt
.GetTm()) )
3997 dt
.Set(d
.day
, d
.month
, d
.year
);
3999 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
4004 // test the computation of (ISO) week numbers
4005 static void TestTimeWNumber()
4007 puts("\n*** wxDateTime week number test ***");
4009 struct WeekNumberTestData
4011 Date date
; // the date
4012 wxDateTime::wxDateTime_t week
; // the week number in the year
4013 wxDateTime::wxDateTime_t wmon
; // the week number in the month
4014 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
4015 wxDateTime::wxDateTime_t dnum
; // day number in the year
4018 // data generated with the following python script:
4020 from DateTime import *
4021 from whrandom import *
4022 from string import *
4024 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4025 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4027 def GetMonthWeek(dt):
4028 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
4029 if weekNumMonth < 0:
4030 weekNumMonth = weekNumMonth + 53
4033 def GetLastSundayBefore(dt):
4034 if dt.iso_week[2] == 7:
4037 return dt - DateTimeDelta(dt.iso_week[2])
4040 year = randint(1900, 2100)
4041 month = randint(1, 12)
4042 day = randint(1, 28)
4043 dt = DateTime(year, month, day)
4044 dayNum = dt.day_of_year
4045 weekNum = dt.iso_week[1]
4046 weekNumMonth = GetMonthWeek(dt)
4049 dtSunday = GetLastSundayBefore(dt)
4051 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
4052 weekNumMonth2 = weekNumMonth2 + 1
4053 dtSunday = dtSunday - DateTimeDelta(7)
4055 data = { 'day': rjust(`day`, 2), \
4056 'month': monthNames[month - 1], \
4058 'weekNum': rjust(`weekNum`, 2), \
4059 'weekNumMonth': weekNumMonth, \
4060 'weekNumMonth2': weekNumMonth2, \
4061 'dayNum': rjust(`dayNum`, 3) }
4063 print " { { %(day)s, "\
4064 "wxDateTime::%(month)s, "\
4067 "%(weekNumMonth)s, "\
4068 "%(weekNumMonth2)s, "\
4069 "%(dayNum)s }," % data
4072 static const WeekNumberTestData weekNumberTestDates
[] =
4074 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
4075 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
4076 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
4077 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
4078 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
4079 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
4080 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
4081 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
4082 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
4083 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
4084 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
4085 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
4086 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
4087 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
4088 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
4089 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
4090 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
4091 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
4092 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
4093 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
4096 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
4098 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
4099 const Date
& d
= wn
.date
;
4101 wxDateTime dt
= d
.DT();
4103 wxDateTime::wxDateTime_t
4104 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
4105 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4106 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4107 dnum
= dt
.GetDayOfYear();
4109 printf("%s: the day number is %d",
4110 d
.FormatDate().c_str(), dnum
);
4111 if ( dnum
== wn
.dnum
)
4117 printf(" (ERROR: should be %d)", wn
.dnum
);
4120 printf(", week in month is %d", wmon
);
4121 if ( wmon
== wn
.wmon
)
4127 printf(" (ERROR: should be %d)", wn
.wmon
);
4130 printf(" or %d", wmon2
);
4131 if ( wmon2
== wn
.wmon2
)
4137 printf(" (ERROR: should be %d)", wn
.wmon2
);
4140 printf(", week in year is %d", week
);
4141 if ( week
== wn
.week
)
4147 printf(" (ERROR: should be %d)\n", wn
.week
);
4152 // test DST calculations
4153 static void TestTimeDST()
4155 puts("\n*** wxDateTime DST test ***");
4157 printf("DST is%s in effect now.\n\n",
4158 wxDateTime::Now().IsDST() ? "" : " not");
4160 // taken from http://www.energy.ca.gov/daylightsaving.html
4161 static const Date datesDST
[2][2004 - 1900 + 1] =
4164 { 1, wxDateTime::Apr
, 1990 },
4165 { 7, wxDateTime::Apr
, 1991 },
4166 { 5, wxDateTime::Apr
, 1992 },
4167 { 4, wxDateTime::Apr
, 1993 },
4168 { 3, wxDateTime::Apr
, 1994 },
4169 { 2, wxDateTime::Apr
, 1995 },
4170 { 7, wxDateTime::Apr
, 1996 },
4171 { 6, wxDateTime::Apr
, 1997 },
4172 { 5, wxDateTime::Apr
, 1998 },
4173 { 4, wxDateTime::Apr
, 1999 },
4174 { 2, wxDateTime::Apr
, 2000 },
4175 { 1, wxDateTime::Apr
, 2001 },
4176 { 7, wxDateTime::Apr
, 2002 },
4177 { 6, wxDateTime::Apr
, 2003 },
4178 { 4, wxDateTime::Apr
, 2004 },
4181 { 28, wxDateTime::Oct
, 1990 },
4182 { 27, wxDateTime::Oct
, 1991 },
4183 { 25, wxDateTime::Oct
, 1992 },
4184 { 31, wxDateTime::Oct
, 1993 },
4185 { 30, wxDateTime::Oct
, 1994 },
4186 { 29, wxDateTime::Oct
, 1995 },
4187 { 27, wxDateTime::Oct
, 1996 },
4188 { 26, wxDateTime::Oct
, 1997 },
4189 { 25, wxDateTime::Oct
, 1998 },
4190 { 31, wxDateTime::Oct
, 1999 },
4191 { 29, wxDateTime::Oct
, 2000 },
4192 { 28, wxDateTime::Oct
, 2001 },
4193 { 27, wxDateTime::Oct
, 2002 },
4194 { 26, wxDateTime::Oct
, 2003 },
4195 { 31, wxDateTime::Oct
, 2004 },
4200 for ( year
= 1990; year
< 2005; year
++ )
4202 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
4203 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
4205 printf("DST period in the US for year %d: from %s to %s",
4206 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
4208 size_t n
= year
- 1990;
4209 const Date
& dBegin
= datesDST
[0][n
];
4210 const Date
& dEnd
= datesDST
[1][n
];
4212 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
4218 printf(" (ERROR: should be %s %d to %s %d)\n",
4219 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
4220 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
4226 for ( year
= 1990; year
< 2005; year
++ )
4228 printf("DST period in Europe for year %d: from %s to %s\n",
4230 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
4231 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
4235 // test wxDateTime -> text conversion
4236 static void TestTimeFormat()
4238 puts("\n*** wxDateTime formatting test ***");
4240 // some information may be lost during conversion, so store what kind
4241 // of info should we recover after a round trip
4244 CompareNone
, // don't try comparing
4245 CompareBoth
, // dates and times should be identical
4246 CompareDate
, // dates only
4247 CompareTime
// time only
4252 CompareKind compareKind
;
4254 } formatTestFormats
[] =
4256 { CompareBoth
, "---> %c" },
4257 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
4258 { CompareBoth
, "Date is %x, time is %X" },
4259 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
4260 { CompareNone
, "The day of year: %j, the week of year: %W" },
4261 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
4264 static const Date formatTestDates
[] =
4266 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
4267 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
4269 // this test can't work for other centuries because it uses two digit
4270 // years in formats, so don't even try it
4271 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
4272 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
4273 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
4277 // an extra test (as it doesn't depend on date, don't do it in the loop)
4278 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
4280 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4284 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
4285 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4287 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4288 printf("%s", s
.c_str());
4290 // what can we recover?
4291 int kind
= formatTestFormats
[n
].compareKind
;
4295 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4298 // converion failed - should it have?
4299 if ( kind
== CompareNone
)
4302 puts(" (ERROR: conversion back failed)");
4306 // should have parsed the entire string
4307 puts(" (ERROR: conversion back stopped too soon)");
4311 bool equal
= FALSE
; // suppress compilaer warning
4319 equal
= dt
.IsSameDate(dt2
);
4323 equal
= dt
.IsSameTime(dt2
);
4329 printf(" (ERROR: got back '%s' instead of '%s')\n",
4330 dt2
.Format().c_str(), dt
.Format().c_str());
4341 // test text -> wxDateTime conversion
4342 static void TestTimeParse()
4344 puts("\n*** wxDateTime parse test ***");
4346 struct ParseTestData
4353 static const ParseTestData parseTestDates
[] =
4355 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4356 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4359 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4361 const char *format
= parseTestDates
[n
].format
;
4363 printf("%s => ", format
);
4366 if ( dt
.ParseRfc822Date(format
) )
4368 printf("%s ", dt
.Format().c_str());
4370 if ( parseTestDates
[n
].good
)
4372 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4379 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4384 puts("(ERROR: bad format)");
4389 printf("bad format (%s)\n",
4390 parseTestDates
[n
].good
? "ERROR" : "ok");
4395 static void TestDateTimeInteractive()
4397 puts("\n*** interactive wxDateTime tests ***");
4403 printf("Enter a date: ");
4404 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4407 // kill the last '\n'
4408 buf
[strlen(buf
) - 1] = 0;
4411 const char *p
= dt
.ParseDate(buf
);
4414 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4420 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4423 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4424 dt
.Format("%b %d, %Y").c_str(),
4426 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4427 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4428 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4431 puts("\n*** done ***");
4434 static void TestTimeMS()
4436 puts("*** testing millisecond-resolution support in wxDateTime ***");
4438 wxDateTime dt1
= wxDateTime::Now(),
4439 dt2
= wxDateTime::UNow();
4441 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4442 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4443 printf("Dummy loop: ");
4444 for ( int i
= 0; i
< 6000; i
++ )
4446 //for ( int j = 0; j < 10; j++ )
4449 s
.Printf("%g", sqrt(i
));
4458 dt2
= wxDateTime::UNow();
4459 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4461 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4463 puts("\n*** done ***");
4466 static void TestTimeArithmetics()
4468 puts("\n*** testing arithmetic operations on wxDateTime ***");
4470 static const struct ArithmData
4472 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4473 : span(sp
), name(nam
) { }
4477 } testArithmData
[] =
4479 ArithmData(wxDateSpan::Day(), "day"),
4480 ArithmData(wxDateSpan::Week(), "week"),
4481 ArithmData(wxDateSpan::Month(), "month"),
4482 ArithmData(wxDateSpan::Year(), "year"),
4483 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4486 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4488 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4490 wxDateSpan span
= testArithmData
[n
].span
;
4494 const char *name
= testArithmData
[n
].name
;
4495 printf("%s + %s = %s, %s - %s = %s\n",
4496 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4497 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4499 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4500 if ( dt1
- span
== dt
)
4506 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4509 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4510 if ( dt2
+ span
== dt
)
4516 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4519 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4520 if ( dt2
+ 2*span
== dt1
)
4526 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4533 static void TestTimeHolidays()
4535 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4537 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4538 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4539 dtEnd
= dtStart
.GetLastMonthDay();
4541 wxDateTimeArray hol
;
4542 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4544 const wxChar
*format
= "%d-%b-%Y (%a)";
4546 printf("All holidays between %s and %s:\n",
4547 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4549 size_t count
= hol
.GetCount();
4550 for ( size_t n
= 0; n
< count
; n
++ )
4552 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4558 static void TestTimeZoneBug()
4560 puts("\n*** testing for DST/timezone bug ***\n");
4562 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4563 for ( int i
= 0; i
< 31; i
++ )
4565 printf("Date %s: week day %s.\n",
4566 date
.Format(_T("%d-%m-%Y")).c_str(),
4567 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4569 date
+= wxDateSpan::Day();
4575 static void TestTimeSpanFormat()
4577 puts("\n*** wxTimeSpan tests ***");
4579 static const char *formats
[] =
4581 _T("(default) %H:%M:%S"),
4582 _T("%E weeks and %D days"),
4583 _T("%l milliseconds"),
4584 _T("(with ms) %H:%M:%S:%l"),
4585 _T("100%% of minutes is %M"), // test "%%"
4586 _T("%D days and %H hours"),
4587 _T("or also %S seconds"),
4590 wxTimeSpan
ts1(1, 2, 3, 4),
4592 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4594 printf("ts1 = %s\tts2 = %s\n",
4595 ts1
.Format(formats
[n
]).c_str(),
4596 ts2
.Format(formats
[n
]).c_str());
4604 // test compatibility with the old wxDate/wxTime classes
4605 static void TestTimeCompatibility()
4607 puts("\n*** wxDateTime compatibility test ***");
4609 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4610 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4612 double jdnNow
= wxDateTime::Now().GetJDN();
4613 long jdnMidnight
= (long)(jdnNow
- 0.5);
4614 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4616 jdnMidnight
= wxDate().Set().GetJulianDate();
4617 printf("wxDateTime for today: %s\n",
4618 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4620 int flags
= wxEUROPEAN
;//wxFULL;
4623 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4624 for ( int n
= 0; n
< 7; n
++ )
4626 printf("Previous %s is %s\n",
4627 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4628 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4634 #endif // TEST_DATETIME
4636 // ----------------------------------------------------------------------------
4638 // ----------------------------------------------------------------------------
4642 #include "wx/thread.h"
4644 static size_t gs_counter
= (size_t)-1;
4645 static wxCriticalSection gs_critsect
;
4646 static wxSemaphore gs_cond
;
4648 class MyJoinableThread
: public wxThread
4651 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4652 { m_n
= n
; Create(); }
4654 // thread execution starts here
4655 virtual ExitCode
Entry();
4661 wxThread::ExitCode
MyJoinableThread::Entry()
4663 unsigned long res
= 1;
4664 for ( size_t n
= 1; n
< m_n
; n
++ )
4668 // it's a loooong calculation :-)
4672 return (ExitCode
)res
;
4675 class MyDetachedThread
: public wxThread
4678 MyDetachedThread(size_t n
, char ch
)
4682 m_cancelled
= FALSE
;
4687 // thread execution starts here
4688 virtual ExitCode
Entry();
4691 virtual void OnExit();
4694 size_t m_n
; // number of characters to write
4695 char m_ch
; // character to write
4697 bool m_cancelled
; // FALSE if we exit normally
4700 wxThread::ExitCode
MyDetachedThread::Entry()
4703 wxCriticalSectionLocker
lock(gs_critsect
);
4704 if ( gs_counter
== (size_t)-1 )
4710 for ( size_t n
= 0; n
< m_n
; n
++ )
4712 if ( TestDestroy() )
4722 wxThread::Sleep(100);
4728 void MyDetachedThread::OnExit()
4730 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4732 wxCriticalSectionLocker
lock(gs_critsect
);
4733 if ( !--gs_counter
&& !m_cancelled
)
4737 static void TestDetachedThreads()
4739 puts("\n*** Testing detached threads ***");
4741 static const size_t nThreads
= 3;
4742 MyDetachedThread
*threads
[nThreads
];
4744 for ( n
= 0; n
< nThreads
; n
++ )
4746 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4749 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4750 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4752 for ( n
= 0; n
< nThreads
; n
++ )
4757 // wait until all threads terminate
4763 static void TestJoinableThreads()
4765 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4767 // calc 10! in the background
4768 MyJoinableThread
thread(10);
4771 printf("\nThread terminated with exit code %lu.\n",
4772 (unsigned long)thread
.Wait());
4775 static void TestThreadSuspend()
4777 puts("\n*** Testing thread suspend/resume functions ***");
4779 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4783 // this is for this demo only, in a real life program we'd use another
4784 // condition variable which would be signaled from wxThread::Entry() to
4785 // tell us that the thread really started running - but here just wait a
4786 // bit and hope that it will be enough (the problem is, of course, that
4787 // the thread might still not run when we call Pause() which will result
4789 wxThread::Sleep(300);
4791 for ( size_t n
= 0; n
< 3; n
++ )
4795 puts("\nThread suspended");
4798 // don't sleep but resume immediately the first time
4799 wxThread::Sleep(300);
4801 puts("Going to resume the thread");
4806 puts("Waiting until it terminates now");
4808 // wait until the thread terminates
4814 static void TestThreadDelete()
4816 // As above, using Sleep() is only for testing here - we must use some
4817 // synchronisation object instead to ensure that the thread is still
4818 // running when we delete it - deleting a detached thread which already
4819 // terminated will lead to a crash!
4821 puts("\n*** Testing thread delete function ***");
4823 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4827 puts("\nDeleted a thread which didn't start to run yet.");
4829 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4833 wxThread::Sleep(300);
4837 puts("\nDeleted a running thread.");
4839 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4843 wxThread::Sleep(300);
4849 puts("\nDeleted a sleeping thread.");
4851 MyJoinableThread
thread3(20);
4856 puts("\nDeleted a joinable thread.");
4858 MyJoinableThread
thread4(2);
4861 wxThread::Sleep(300);
4865 puts("\nDeleted a joinable thread which already terminated.");
4870 class MyWaitingThread
: public wxThread
4873 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
4876 m_condition
= condition
;
4881 virtual ExitCode
Entry()
4883 printf("Thread %lu has started running.\n", GetId());
4888 printf("Thread %lu starts to wait...\n", GetId());
4892 m_condition
->Wait();
4895 printf("Thread %lu finished to wait, exiting.\n", GetId());
4903 wxCondition
*m_condition
;
4906 static void TestThreadConditions()
4909 wxCondition
condition(mutex
);
4911 // otherwise its difficult to understand which log messages pertain to
4913 //wxLogTrace("thread", "Local condition var is %08x, gs_cond = %08x",
4914 // condition.GetId(), gs_cond.GetId());
4916 // create and launch threads
4917 MyWaitingThread
*threads
[10];
4920 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4922 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
4925 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4930 // wait until all threads run
4931 puts("Main thread is waiting for the other threads to start");
4934 size_t nRunning
= 0;
4935 while ( nRunning
< WXSIZEOF(threads
) )
4941 printf("Main thread: %u already running\n", nRunning
);
4945 puts("Main thread: all threads started up.");
4948 wxThread::Sleep(500);
4951 // now wake one of them up
4952 printf("Main thread: about to signal the condition.\n");
4957 wxThread::Sleep(200);
4959 // wake all the (remaining) threads up, so that they can exit
4960 printf("Main thread: about to broadcast the condition.\n");
4962 condition
.Broadcast();
4964 // give them time to terminate (dirty!)
4965 wxThread::Sleep(500);
4968 #include "wx/utils.h"
4970 class MyExecThread
: public wxThread
4973 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
4979 virtual ExitCode
Entry()
4981 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
4988 static void TestThreadExec()
4990 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
4992 MyExecThread
thread(_T("true"));
4995 wxPrintf(_T("Main program exit code: %ld.\n"),
4996 wxExecute(_T("false"), wxEXEC_SYNC
));
4998 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
5002 #include "wx/datetime.h"
5004 class MySemaphoreThread
: public wxThread
5007 MySemaphoreThread(int i
, wxSemaphore
*sem
)
5008 : wxThread(wxTHREAD_JOINABLE
),
5015 virtual ExitCode
Entry()
5017 wxPrintf(_T("%s: Thread %d starting to wait for semaphore...\n"),
5018 wxDateTime::Now().FormatTime().c_str(), m_i
);
5022 wxPrintf(_T("%s: Thread %d acquired the semaphore.\n"),
5023 wxDateTime::Now().FormatTime().c_str(), m_i
);
5027 wxPrintf(_T("%s: Thread %d releasing the semaphore.\n"),
5028 wxDateTime::Now().FormatTime().c_str(), m_i
);
5040 WX_DEFINE_ARRAY(wxThread
*, ArrayThreads
);
5042 static void TestSemaphore()
5044 wxPuts(_T("*** Testing wxSemaphore class. ***"));
5046 static const int SEM_LIMIT
= 3;
5048 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
5049 ArrayThreads threads
;
5051 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
5053 threads
.Add(new MySemaphoreThread(i
, &sem
));
5054 threads
.Last()->Run();
5057 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
5064 #endif // TEST_THREADS
5066 // ----------------------------------------------------------------------------
5068 // ----------------------------------------------------------------------------
5072 #include "wx/dynarray.h"
5074 #define DefineCompare(name, T) \
5076 int wxCMPFUNC_CONV name ## CompareValues(T first, T second) \
5078 return first - second; \
5081 int wxCMPFUNC_CONV name ## Compare(T* first, T* second) \
5083 return *first - *second; \
5086 int wxCMPFUNC_CONV name ## RevCompare(T* first, T* second) \
5088 return *second - *first; \
5091 DefineCompare(Short, short);
5092 DefineCompare(Int
, int);
5094 // test compilation of all macros
5095 WX_DEFINE_ARRAY(short, wxArrayShort
);
5096 WX_DEFINE_SORTED_ARRAY(short, wxSortedArrayShortNoCmp
);
5097 WX_DEFINE_SORTED_ARRAY_CMP(short, ShortCompareValues
, wxSortedArrayShort
);
5098 WX_DEFINE_SORTED_ARRAY_CMP(int, IntCompareValues
, wxSortedArrayInt
);
5100 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
5101 #include "wx/arrimpl.cpp"
5102 WX_DEFINE_OBJARRAY(ArrayBars
);
5104 static void PrintArray(const char* name
, const wxArrayString
& array
)
5106 printf("Dump of the array '%s'\n", name
);
5108 size_t nCount
= array
.GetCount();
5109 for ( size_t n
= 0; n
< nCount
; n
++ )
5111 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
5115 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
5116 const wxString
& second
)
5118 return first
.length() - second
.length();
5121 #define TestArrayOf(name) \
5123 static void PrintArray(const char* name, const wxSortedArray##name & array) \
5125 printf("Dump of the array '%s'\n", name); \
5127 size_t nCount = array.GetCount(); \
5128 for ( size_t n = 0; n < nCount; n++ ) \
5130 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5134 static void PrintArray(const char* name, const wxArray##name & array) \
5136 printf("Dump of the array '%s'\n", name); \
5138 size_t nCount = array.GetCount(); \
5139 for ( size_t n = 0; n < nCount; n++ ) \
5141 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5145 static void TestArrayOf ## name ## s() \
5147 printf("*** Testing wxArray%s ***\n", #name); \
5155 puts("Initially:"); \
5156 PrintArray("a", a); \
5158 puts("After sort:"); \
5159 a.Sort(name ## Compare); \
5160 PrintArray("a", a); \
5162 puts("After reverse sort:"); \
5163 a.Sort(name ## RevCompare); \
5164 PrintArray("a", a); \
5166 wxSortedArray##name b; \
5172 puts("Sorted array initially:"); \
5173 PrintArray("b", b); \
5179 static void TestArrayOfObjects()
5181 puts("*** Testing wxObjArray ***\n");
5185 Bar
bar("second bar");
5187 printf("Initially: %u objects in the array, %u objects total.\n",
5188 bars
.GetCount(), Bar::GetNumber());
5190 bars
.Add(new Bar("first bar"));
5193 printf("Now: %u objects in the array, %u objects total.\n",
5194 bars
.GetCount(), Bar::GetNumber());
5198 printf("After Empty(): %u objects in the array, %u objects total.\n",
5199 bars
.GetCount(), Bar::GetNumber());
5202 printf("Finally: no more objects in the array, %u objects total.\n",
5206 #endif // TEST_ARRAYS
5208 // ----------------------------------------------------------------------------
5210 // ----------------------------------------------------------------------------
5214 #include "wx/timer.h"
5215 #include "wx/tokenzr.h"
5217 static void TestStringConstruction()
5219 puts("*** Testing wxString constructores ***");
5221 #define TEST_CTOR(args, res) \
5224 printf("wxString%s = %s ", #args, s.c_str()); \
5231 printf("(ERROR: should be %s)\n", res); \
5235 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
5236 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
5237 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
5238 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
5240 static const wxChar
*s
= _T("?really!");
5241 const wxChar
*start
= wxStrchr(s
, _T('r'));
5242 const wxChar
*end
= wxStrchr(s
, _T('!'));
5243 TEST_CTOR((start
, end
), _T("really"));
5248 static void TestString()
5258 for (int i
= 0; i
< 1000000; ++i
)
5262 c
= "! How'ya doin'?";
5265 c
= "Hello world! What's up?";
5270 printf ("TestString elapsed time: %ld\n", sw
.Time());
5273 static void TestPChar()
5281 for (int i
= 0; i
< 1000000; ++i
)
5283 strcpy (a
, "Hello");
5284 strcpy (b
, " world");
5285 strcpy (c
, "! How'ya doin'?");
5288 strcpy (c
, "Hello world! What's up?");
5289 if (strcmp (c
, a
) == 0)
5293 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
5296 static void TestStringSub()
5298 wxString
s("Hello, world!");
5300 puts("*** Testing wxString substring extraction ***");
5302 printf("String = '%s'\n", s
.c_str());
5303 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
5304 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
5305 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
5306 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
5307 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
5308 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
5310 static const wxChar
*prefixes
[] =
5314 _T("Hello, world!"),
5315 _T("Hello, world!!!"),
5321 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
5323 wxString prefix
= prefixes
[n
], rest
;
5324 bool rc
= s
.StartsWith(prefix
, &rest
);
5325 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
5328 printf(" (the rest is '%s')\n", rest
.c_str());
5339 static void TestStringFormat()
5341 puts("*** Testing wxString formatting ***");
5344 s
.Printf("%03d", 18);
5346 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
5347 printf("Number 18: %s\n", s
.c_str());
5352 // returns "not found" for npos, value for all others
5353 static wxString
PosToString(size_t res
)
5355 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
5356 : wxString::Format(_T("%u"), res
);
5360 static void TestStringFind()
5362 puts("*** Testing wxString find() functions ***");
5364 static const wxChar
*strToFind
= _T("ell");
5365 static const struct StringFindTest
5369 result
; // of searching "ell" in str
5372 { _T("Well, hello world"), 0, 1 },
5373 { _T("Well, hello world"), 6, 7 },
5374 { _T("Well, hello world"), 9, wxString::npos
},
5377 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
5379 const StringFindTest
& ft
= findTestData
[n
];
5380 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
5382 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
5383 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
5385 size_t resTrue
= ft
.result
;
5386 if ( res
== resTrue
)
5392 printf(_T("(ERROR: should be %s)\n"),
5393 PosToString(resTrue
).c_str());
5400 static void TestStringTokenizer()
5402 puts("*** Testing wxStringTokenizer ***");
5404 static const wxChar
*modeNames
[] =
5408 _T("return all empty"),
5413 static const struct StringTokenizerTest
5415 const wxChar
*str
; // string to tokenize
5416 const wxChar
*delims
; // delimiters to use
5417 size_t count
; // count of token
5418 wxStringTokenizerMode mode
; // how should we tokenize it
5419 } tokenizerTestData
[] =
5421 { _T(""), _T(" "), 0 },
5422 { _T("Hello, world"), _T(" "), 2 },
5423 { _T("Hello, world "), _T(" "), 2 },
5424 { _T("Hello, world"), _T(","), 2 },
5425 { _T("Hello, world!"), _T(",!"), 2 },
5426 { _T("Hello,, world!"), _T(",!"), 3 },
5427 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
5428 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
5429 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
5430 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
5431 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
5432 { _T("01/02/99"), _T("/-"), 3 },
5433 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
5436 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
5438 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
5439 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
5441 size_t count
= tkz
.CountTokens();
5442 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
5443 MakePrintable(tt
.str
).c_str(),
5445 MakePrintable(tt
.delims
).c_str(),
5446 modeNames
[tkz
.GetMode()]);
5447 if ( count
== tt
.count
)
5453 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
5458 // if we emulate strtok(), check that we do it correctly
5459 wxChar
*buf
, *s
= NULL
, *last
;
5461 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
5463 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
5464 wxStrcpy(buf
, tt
.str
);
5466 s
= wxStrtok(buf
, tt
.delims
, &last
);
5473 // now show the tokens themselves
5475 while ( tkz
.HasMoreTokens() )
5477 wxString token
= tkz
.GetNextToken();
5479 printf(_T("\ttoken %u: '%s'"),
5481 MakePrintable(token
).c_str());
5491 printf(" (ERROR: should be %s)\n", s
);
5494 s
= wxStrtok(NULL
, tt
.delims
, &last
);
5498 // nothing to compare with
5503 if ( count2
!= count
)
5505 puts(_T("\tERROR: token count mismatch"));
5514 static void TestStringReplace()
5516 puts("*** Testing wxString::replace ***");
5518 static const struct StringReplaceTestData
5520 const wxChar
*original
; // original test string
5521 size_t start
, len
; // the part to replace
5522 const wxChar
*replacement
; // the replacement string
5523 const wxChar
*result
; // and the expected result
5524 } stringReplaceTestData
[] =
5526 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
5527 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
5528 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
5529 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
5530 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
5533 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
5535 const StringReplaceTestData data
= stringReplaceTestData
[n
];
5537 wxString original
= data
.original
;
5538 original
.replace(data
.start
, data
.len
, data
.replacement
);
5540 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
5541 data
.original
, data
.start
, data
.len
, data
.replacement
,
5544 if ( original
== data
.result
)
5550 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
5557 static void TestStringMatch()
5559 wxPuts(_T("*** Testing wxString::Matches() ***"));
5561 static const struct StringMatchTestData
5564 const wxChar
*wildcard
;
5566 } stringMatchTestData
[] =
5568 { _T("foobar"), _T("foo*"), 1 },
5569 { _T("foobar"), _T("*oo*"), 1 },
5570 { _T("foobar"), _T("*bar"), 1 },
5571 { _T("foobar"), _T("??????"), 1 },
5572 { _T("foobar"), _T("f??b*"), 1 },
5573 { _T("foobar"), _T("f?b*"), 0 },
5574 { _T("foobar"), _T("*goo*"), 0 },
5575 { _T("foobar"), _T("*foo"), 0 },
5576 { _T("foobarfoo"), _T("*foo"), 1 },
5577 { _T(""), _T("*"), 1 },
5578 { _T(""), _T("?"), 0 },
5581 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
5583 const StringMatchTestData
& data
= stringMatchTestData
[n
];
5584 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
5585 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
5587 matches
? _T("matches") : _T("doesn't match"),
5589 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5595 #endif // TEST_STRINGS
5597 // ----------------------------------------------------------------------------
5599 // ----------------------------------------------------------------------------
5601 #ifdef TEST_SNGLINST
5602 #include "wx/snglinst.h"
5603 #endif // TEST_SNGLINST
5605 int main(int argc
, char **argv
)
5607 wxInitializer initializer
;
5610 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5615 #ifdef TEST_SNGLINST
5616 wxSingleInstanceChecker checker
;
5617 if ( checker
.Create(_T(".wxconsole.lock")) )
5619 if ( checker
.IsAnotherRunning() )
5621 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5626 // wait some time to give time to launch another instance
5627 wxPrintf(_T("Press \"Enter\" to continue..."));
5630 else // failed to create
5632 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5634 #endif // TEST_SNGLINST
5638 #endif // TEST_CHARSET
5641 TestCmdLineConvert();
5643 #if wxUSE_CMDLINE_PARSER
5644 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5646 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5647 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5648 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5649 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5651 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5652 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5653 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5654 wxCMD_LINE_VAL_NUMBER
},
5655 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5656 wxCMD_LINE_VAL_DATE
},
5658 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5659 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5664 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5666 parser
.AddOption("project_name", "", "full path to project file",
5667 wxCMD_LINE_VAL_STRING
,
5668 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5670 switch ( parser
.Parse() )
5673 wxLogMessage("Help was given, terminating.");
5677 ShowCmdLine(parser
);
5681 wxLogMessage("Syntax error detected, aborting.");
5684 #endif // wxUSE_CMDLINE_PARSER
5686 #endif // TEST_CMDLINE
5694 TestStringConstruction();
5697 TestStringTokenizer();
5698 TestStringReplace();
5704 #endif // TEST_STRINGS
5717 puts("*** Initially:");
5719 PrintArray("a1", a1
);
5721 wxArrayString
a2(a1
);
5722 PrintArray("a2", a2
);
5724 wxSortedArrayString
a3(a1
);
5725 PrintArray("a3", a3
);
5727 puts("*** After deleting a string from a1");
5730 PrintArray("a1", a1
);
5731 PrintArray("a2", a2
);
5732 PrintArray("a3", a3
);
5734 puts("*** After reassigning a1 to a2 and a3");
5736 PrintArray("a2", a2
);
5737 PrintArray("a3", a3
);
5739 puts("*** After sorting a1");
5741 PrintArray("a1", a1
);
5743 puts("*** After sorting a1 in reverse order");
5745 PrintArray("a1", a1
);
5747 puts("*** After sorting a1 by the string length");
5748 a1
.Sort(StringLenCompare
);
5749 PrintArray("a1", a1
);
5751 TestArrayOfObjects();
5752 TestArrayOfShorts();
5756 #endif // TEST_ARRAYS
5766 #ifdef TEST_DLLLOADER
5768 #endif // TEST_DLLLOADER
5772 #endif // TEST_ENVIRON
5776 #endif // TEST_EXECUTE
5778 #ifdef TEST_FILECONF
5780 #endif // TEST_FILECONF
5788 #endif // TEST_LOCALE
5792 for ( size_t n
= 0; n
< 8000; n
++ )
5794 s
<< (char)('A' + (n
% 26));
5798 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5800 // this one shouldn't be truncated
5803 // but this one will because log functions use fixed size buffer
5804 // (note that it doesn't need '\n' at the end neither - will be added
5806 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5818 #ifdef TEST_FILENAME
5822 fn
.Assign("c:\\foo", "bar.baz");
5829 TestFileNameConstruction();
5830 TestFileNameMakeRelative();
5831 TestFileNameSplit();
5834 TestFileNameComparison();
5835 TestFileNameOperations();
5837 #endif // TEST_FILENAME
5839 #ifdef TEST_FILETIME
5842 #endif // TEST_FILETIME
5845 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5846 if ( TestFtpConnect() )
5857 if ( TEST_INTERACTIVE
)
5858 TestFtpInteractive();
5860 //else: connecting to the FTP server failed
5866 #ifdef TEST_LONGLONG
5867 // seed pseudo random generator
5868 srand((unsigned)time(NULL
));
5877 TestMultiplication();
5880 TestLongLongConversion();
5881 TestBitOperations();
5882 TestLongLongComparison();
5883 TestLongLongPrint();
5885 #endif // TEST_LONGLONG
5893 #endif // TEST_HASHMAP
5896 wxLog::AddTraceMask(_T("mime"));
5904 TestMimeAssociate();
5907 #ifdef TEST_INFO_FUNCTIONS
5913 if ( TEST_INTERACTIVE
)
5916 #endif // TEST_INFO_FUNCTIONS
5918 #ifdef TEST_PATHLIST
5920 #endif // TEST_PATHLIST
5928 #endif // TEST_REGCONF
5931 // TODO: write a real test using src/regex/tests file
5936 TestRegExSubmatch();
5937 TestRegExReplacement();
5939 if ( TEST_INTERACTIVE
)
5940 TestRegExInteractive();
5942 #endif // TEST_REGEX
5944 #ifdef TEST_REGISTRY
5946 TestRegistryAssociation();
5947 #endif // TEST_REGISTRY
5952 #endif // TEST_SOCKETS
5957 #endif // TEST_STREAMS
5960 int nCPUs
= wxThread::GetCPUCount();
5961 printf("This system has %d CPUs\n", nCPUs
);
5963 wxThread::SetConcurrency(nCPUs
);
5967 TestDetachedThreads();
5968 TestJoinableThreads();
5969 TestThreadSuspend();
5971 TestThreadConditions();
5976 #endif // TEST_THREADS
5980 #endif // TEST_TIMER
5982 #ifdef TEST_DATETIME
5995 TestTimeArithmetics();
5998 TestTimeSpanFormat();
6004 if ( TEST_INTERACTIVE
)
6005 TestDateTimeInteractive();
6006 #endif // TEST_DATETIME
6009 puts("Sleeping for 3 seconds... z-z-z-z-z...");
6011 #endif // TEST_USLEEP
6016 #endif // TEST_VCARD
6020 #endif // TEST_VOLUME
6024 TestEncodingConverter();
6025 #endif // TEST_WCHAR
6028 TestZipStreamRead();
6029 TestZipFileSystem();
6033 TestZlibStreamWrite();
6034 TestZlibStreamRead();