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 // ----------------------------------------------------------------------------
42 // what to test (in alphabetic order)? uncomment the line below to do all tests
50 #define TEST_DLLLOADER
59 #define TEST_INFO_FUNCTIONS
75 // #define TEST_VCARD -- don't enable this (VZ)
84 #include "wx/snglinst.h"
85 #endif // TEST_SNGLINST
87 // ----------------------------------------------------------------------------
88 // test class for container objects
89 // ----------------------------------------------------------------------------
91 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
93 class Bar
// Foo is already taken in the hash test
96 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
99 static size_t GetNumber() { return ms_bars
; }
101 const char *GetName() const { return m_name
; }
106 static size_t ms_bars
;
109 size_t Bar::ms_bars
= 0;
111 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
113 // ============================================================================
115 // ============================================================================
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
121 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
123 // replace TABs with \t and CRs with \n
124 static wxString
MakePrintable(const wxChar
*s
)
127 (void)str
.Replace(_T("\t"), _T("\\t"));
128 (void)str
.Replace(_T("\n"), _T("\\n"));
129 (void)str
.Replace(_T("\r"), _T("\\r"));
134 #endif // MakePrintable() is used
136 // ----------------------------------------------------------------------------
137 // wxFontMapper::CharsetToEncoding
138 // ----------------------------------------------------------------------------
142 #include "wx/fontmap.h"
144 static void TestCharset()
146 static const wxChar
*charsets
[] =
148 // some vali charsets
157 // and now some bogus ones
164 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
166 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(charsets
[n
]);
167 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
169 wxTheFontMapper
->GetEncodingName(enc
).c_str(),
170 wxTheFontMapper
->GetEncodingDescription(enc
).c_str());
174 #endif // TEST_CHARSET
176 // ----------------------------------------------------------------------------
178 // ----------------------------------------------------------------------------
182 #include "wx/cmdline.h"
183 #include "wx/datetime.h"
185 #if wxUSE_CMDLINE_PARSER
187 static void ShowCmdLine(const wxCmdLineParser
& parser
)
189 wxString s
= "Input files: ";
191 size_t count
= parser
.GetParamCount();
192 for ( size_t param
= 0; param
< count
; param
++ )
194 s
<< parser
.GetParam(param
) << ' ';
198 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
199 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
204 if ( parser
.Found("o", &strVal
) )
205 s
<< "Output file:\t" << strVal
<< '\n';
206 if ( parser
.Found("i", &strVal
) )
207 s
<< "Input dir:\t" << strVal
<< '\n';
208 if ( parser
.Found("s", &lVal
) )
209 s
<< "Size:\t" << lVal
<< '\n';
210 if ( parser
.Found("d", &dt
) )
211 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
212 if ( parser
.Found("project_name", &strVal
) )
213 s
<< "Project:\t" << strVal
<< '\n';
218 #endif // wxUSE_CMDLINE_PARSER
220 static void TestCmdLineConvert()
222 static const char *cmdlines
[] =
225 "-a \"-bstring 1\" -c\"string 2\" \"string 3\"",
226 "literal \\\" and \"\"",
229 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
231 const char *cmdline
= cmdlines
[n
];
232 printf("Parsing: %s\n", cmdline
);
233 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
235 size_t count
= args
.GetCount();
236 printf("\targc = %u\n", count
);
237 for ( size_t arg
= 0; arg
< count
; arg
++ )
239 printf("\targv[%u] = %s\n", arg
, args
[arg
]);
244 #endif // TEST_CMDLINE
246 // ----------------------------------------------------------------------------
248 // ----------------------------------------------------------------------------
255 static const wxChar
*ROOTDIR
= _T("/");
256 static const wxChar
*TESTDIR
= _T("/usr");
257 #elif defined(__WXMSW__)
258 static const wxChar
*ROOTDIR
= _T("c:\\");
259 static const wxChar
*TESTDIR
= _T("d:\\");
261 #error "don't know where the root directory is"
264 static void TestDirEnumHelper(wxDir
& dir
,
265 int flags
= wxDIR_DEFAULT
,
266 const wxString
& filespec
= wxEmptyString
)
270 if ( !dir
.IsOpened() )
273 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
276 printf("\t%s\n", filename
.c_str());
278 cont
= dir
.GetNext(&filename
);
284 static void TestDirEnum()
286 puts("*** Testing wxDir::GetFirst/GetNext ***");
288 wxDir
dir(wxGetCwd());
290 puts("Enumerating everything in current directory:");
291 TestDirEnumHelper(dir
);
293 puts("Enumerating really everything in current directory:");
294 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
296 puts("Enumerating object files in current directory:");
297 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
299 puts("Enumerating directories in current directory:");
300 TestDirEnumHelper(dir
, wxDIR_DIRS
);
302 puts("Enumerating files in current directory:");
303 TestDirEnumHelper(dir
, wxDIR_FILES
);
305 puts("Enumerating files including hidden in current directory:");
306 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
310 puts("Enumerating everything in root directory:");
311 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
313 puts("Enumerating directories in root directory:");
314 TestDirEnumHelper(dir
, wxDIR_DIRS
);
316 puts("Enumerating files in root directory:");
317 TestDirEnumHelper(dir
, wxDIR_FILES
);
319 puts("Enumerating files including hidden in root directory:");
320 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
322 puts("Enumerating files in non existing directory:");
323 wxDir
dirNo("nosuchdir");
324 TestDirEnumHelper(dirNo
);
327 class DirPrintTraverser
: public wxDirTraverser
330 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
332 return wxDIR_CONTINUE
;
335 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
337 wxString path
, name
, ext
;
338 wxSplitPath(dirname
, &path
, &name
, &ext
);
341 name
<< _T('.') << ext
;
344 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
346 if ( wxIsPathSeparator(*p
) )
350 printf("%s%s\n", indent
.c_str(), name
.c_str());
352 return wxDIR_CONTINUE
;
356 static void TestDirTraverse()
358 puts("*** Testing wxDir::Traverse() ***");
362 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
363 printf("There are %u files under '%s'\n", n
, TESTDIR
);
366 printf("First one is '%s'\n", files
[0u].c_str());
367 printf(" last one is '%s'\n", files
[n
- 1].c_str());
370 // enum again with custom traverser
372 DirPrintTraverser traverser
;
373 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
378 // ----------------------------------------------------------------------------
380 // ----------------------------------------------------------------------------
382 #ifdef TEST_DLLLOADER
384 #include "wx/dynlib.h"
386 static void TestDllLoad()
388 #if defined(__WXMSW__)
389 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
390 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
391 #elif defined(__UNIX__)
392 // weird: using just libc.so does *not* work!
393 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
394 static const wxChar
*FUNC_NAME
= _T("strlen");
396 #error "don't know how to test wxDllLoader on this platform"
399 puts("*** testing wxDllLoader ***\n");
401 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
404 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
408 typedef int (*strlenType
)(const char *);
409 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
412 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
413 FUNC_NAME
, LIB_NAME
);
417 if ( pfnStrlen("foo") != 3 )
419 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
427 wxDllLoader::UnloadLibrary(dllHandle
);
431 #endif // TEST_DLLLOADER
433 // ----------------------------------------------------------------------------
435 // ----------------------------------------------------------------------------
439 #include "wx/utils.h"
441 static wxString
MyGetEnv(const wxString
& var
)
444 if ( !wxGetEnv(var
, &val
) )
447 val
= wxString(_T('\'')) + val
+ _T('\'');
452 static void TestEnvironment()
454 const wxChar
*var
= _T("wxTestVar");
456 puts("*** testing environment access functions ***");
458 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
459 wxSetEnv(var
, _T("value for wxTestVar"));
460 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
461 wxSetEnv(var
, _T("another value"));
462 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
464 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
465 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
468 #endif // TEST_ENVIRON
470 // ----------------------------------------------------------------------------
472 // ----------------------------------------------------------------------------
476 #include "wx/utils.h"
478 static void TestExecute()
480 puts("*** testing wxExecute ***");
483 #define COMMAND "cat -n ../../Makefile" // "echo hi"
484 #define SHELL_COMMAND "echo hi from shell"
485 #define REDIRECT_COMMAND COMMAND // "date"
486 #elif defined(__WXMSW__)
487 #define COMMAND "command.com -c 'echo hi'"
488 #define SHELL_COMMAND "echo hi"
489 #define REDIRECT_COMMAND COMMAND
491 #error "no command to exec"
494 printf("Testing wxShell: ");
496 if ( wxShell(SHELL_COMMAND
) )
501 printf("Testing wxExecute: ");
503 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
508 #if 0 // no, it doesn't work (yet?)
509 printf("Testing async wxExecute: ");
511 if ( wxExecute(COMMAND
) != 0 )
512 puts("Ok (command launched).");
517 printf("Testing wxExecute with redirection:\n");
518 wxArrayString output
;
519 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
525 size_t count
= output
.GetCount();
526 for ( size_t n
= 0; n
< count
; n
++ )
528 printf("\t%s\n", output
[n
].c_str());
535 #endif // TEST_EXECUTE
537 // ----------------------------------------------------------------------------
539 // ----------------------------------------------------------------------------
544 #include "wx/ffile.h"
545 #include "wx/textfile.h"
547 static void TestFileRead()
549 puts("*** wxFile read test ***");
551 wxFile
file(_T("testdata.fc"));
552 if ( file
.IsOpened() )
554 printf("File length: %lu\n", file
.Length());
556 puts("File dump:\n----------");
558 static const off_t len
= 1024;
562 off_t nRead
= file
.Read(buf
, len
);
563 if ( nRead
== wxInvalidOffset
)
565 printf("Failed to read the file.");
569 fwrite(buf
, nRead
, 1, stdout
);
579 printf("ERROR: can't open test file.\n");
585 static void TestTextFileRead()
587 puts("*** wxTextFile read test ***");
589 wxTextFile
file(_T("testdata.fc"));
592 printf("Number of lines: %u\n", file
.GetLineCount());
593 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
597 puts("\nDumping the entire file:");
598 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
600 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
602 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
604 puts("\nAnd now backwards:");
605 for ( s
= file
.GetLastLine();
606 file
.GetCurrentLine() != 0;
607 s
= file
.GetPrevLine() )
609 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
611 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
615 printf("ERROR: can't open '%s'\n", file
.GetName());
621 static void TestFileCopy()
623 puts("*** Testing wxCopyFile ***");
625 static const wxChar
*filename1
= _T("testdata.fc");
626 static const wxChar
*filename2
= _T("test2");
627 if ( !wxCopyFile(filename1
, filename2
) )
629 puts("ERROR: failed to copy file");
633 wxFFile
f1(filename1
, "rb"),
636 if ( !f1
.IsOpened() || !f2
.IsOpened() )
638 puts("ERROR: failed to open file(s)");
643 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
645 puts("ERROR: failed to read file(s)");
649 if ( (s1
.length() != s2
.length()) ||
650 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
652 puts("ERROR: copy error!");
656 puts("File was copied ok.");
662 if ( !wxRemoveFile(filename2
) )
664 puts("ERROR: failed to remove the file");
672 // ----------------------------------------------------------------------------
674 // ----------------------------------------------------------------------------
678 #include "wx/confbase.h"
679 #include "wx/fileconf.h"
681 static const struct FileConfTestData
683 const wxChar
*name
; // value name
684 const wxChar
*value
; // the value from the file
687 { _T("value1"), _T("one") },
688 { _T("value2"), _T("two") },
689 { _T("novalue"), _T("default") },
692 static void TestFileConfRead()
694 puts("*** testing wxFileConfig loading/reading ***");
696 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
697 _T("testdata.fc"), wxEmptyString
,
698 wxCONFIG_USE_RELATIVE_PATH
);
700 // test simple reading
701 puts("\nReading config file:");
702 wxString
defValue(_T("default")), value
;
703 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
705 const FileConfTestData
& data
= fcTestData
[n
];
706 value
= fileconf
.Read(data
.name
, defValue
);
707 printf("\t%s = %s ", data
.name
, value
.c_str());
708 if ( value
== data
.value
)
714 printf("(ERROR: should be %s)\n", data
.value
);
718 // test enumerating the entries
719 puts("\nEnumerating all root entries:");
722 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
725 printf("\t%s = %s\n",
727 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
729 cont
= fileconf
.GetNextEntry(name
, dummy
);
733 #endif // TEST_FILECONF
735 // ----------------------------------------------------------------------------
737 // ----------------------------------------------------------------------------
741 #include "wx/filename.h"
743 static void DumpFileName(const wxFileName
& fn
)
745 wxString full
= fn
.GetFullPath();
747 wxString vol
, path
, name
, ext
;
748 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
750 wxPrintf(_T("Filename '%s' -> vol '%s', path '%s', name '%s', ext '%s'\n"),
751 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
754 static struct FileNameInfo
756 const wxChar
*fullname
;
757 const wxChar
*volume
;
766 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), TRUE
, wxPATH_UNIX
},
767 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), TRUE
, wxPATH_UNIX
},
768 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), TRUE
, wxPATH_UNIX
},
769 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), FALSE
, wxPATH_UNIX
},
770 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
771 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), TRUE
, wxPATH_UNIX
},
772 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), TRUE
, wxPATH_UNIX
},
773 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
774 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), TRUE
, wxPATH_UNIX
},
776 // Windows file names
777 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
778 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
779 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
780 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
781 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), TRUE
, wxPATH_DOS
},
782 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
785 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
786 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
787 { _T(":File"), _T(""), _T(""), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
788 { _T("File"), _T(""), _T(""), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
791 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
792 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
795 static void TestFileNameConstruction()
797 puts("*** testing wxFileName construction ***");
799 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
801 const FileNameInfo
& fni
= filenames
[n
];
803 wxFileName
fn(fni
.fullname
, fni
.format
);
805 wxString fullname
= fn
.GetFullPath(fni
.format
);
806 if ( fullname
!= fni
.fullname
)
808 printf("ERROR: fullname should be '%s'\n", fni
.fullname
);
811 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
812 printf("'%s' is %s (%s)\n\t",
814 isAbsolute
? "absolute" : "relative",
815 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
817 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
819 puts("ERROR (couldn't be normalized)");
823 printf("normalized: '%s'\n", fn
.GetFullPath(fni
.format
).c_str());
830 static void TestFileNameSplit()
832 puts("*** testing wxFileName splitting ***");
834 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
836 const FileNameInfo
& fni
= filenames
[n
];
837 wxString volume
, path
, name
, ext
;
838 wxFileName::SplitPath(fni
.fullname
,
839 &volume
, &path
, &name
, &ext
, fni
.format
);
841 printf("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'",
843 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
845 if ( volume
!= fni
.volume
)
846 printf(" (ERROR: volume = '%s')", fni
.volume
);
847 if ( path
!= fni
.path
)
848 printf(" (ERROR: path = '%s')", fni
.path
);
849 if ( name
!= fni
.name
)
850 printf(" (ERROR: name = '%s')", fni
.name
);
851 if ( ext
!= fni
.ext
)
852 printf(" (ERROR: ext = '%s')", fni
.ext
);
858 static void TestFileNameTemp()
860 puts("*** testing wxFileName temp file creation ***");
862 static const char *tmpprefixes
[] =
868 "/tmp/foo/bar", // this one must be an error
871 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
873 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
876 printf("Prefix '%s'\t-> temp file '%s'\n",
877 tmpprefixes
[n
], path
.c_str());
879 if ( !wxRemoveFile(path
) )
881 wxLogWarning("Failed to remove temp file '%s'", path
.c_str());
887 static void TestFileNameMakeRelative()
889 puts("*** testing wxFileName::MakeRelativeTo() ***");
891 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
893 const FileNameInfo
& fni
= filenames
[n
];
895 wxFileName
fn(fni
.fullname
, fni
.format
);
897 // choose the base dir of the same format
899 switch ( fni
.format
)
911 // TODO: I don't know how this is supposed to work there
915 printf("'%s' relative to '%s': ",
916 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
918 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
924 printf("'%s'\n", fn
.GetFullPath(fni
.format
).c_str());
929 static void TestFileNameComparison()
934 static void TestFileNameOperations()
939 static void TestFileNameCwd()
944 #endif // TEST_FILENAME
946 // ----------------------------------------------------------------------------
947 // wxFileName time functions
948 // ----------------------------------------------------------------------------
952 #include <wx/filename.h>
953 #include <wx/datetime.h>
955 static void TestFileGetTimes()
957 wxFileName
fn(_T("testdata.fc"));
959 wxDateTime dtAccess
, dtMod
, dtChange
;
960 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtChange
) )
962 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
966 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
968 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
969 wxPrintf(_T("Access: \t%s\n"), dtAccess
.Format(fmt
).c_str());
970 wxPrintf(_T("Mod/creation:\t%s\n"), dtMod
.Format(fmt
).c_str());
971 wxPrintf(_T("Change: \t%s\n"), dtChange
.Format(fmt
).c_str());
975 static void TestFileSetTimes()
977 wxFileName
fn(_T("testdata.fc"));
979 wxDateTime dtAccess
, dtMod
, dtChange
;
982 wxPrintf(_T("ERROR: Touch() failed.\n"));
986 #endif // TEST_FILETIME
988 // ----------------------------------------------------------------------------
990 // ----------------------------------------------------------------------------
998 Foo(int n_
) { n
= n_
; count
++; }
1003 static size_t count
;
1006 size_t Foo::count
= 0;
1008 WX_DECLARE_LIST(Foo
, wxListFoos
);
1009 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
1011 #include "wx/listimpl.cpp"
1013 WX_DEFINE_LIST(wxListFoos
);
1015 static void TestHash()
1017 puts("*** Testing wxHashTable ***\n");
1021 hash
.DeleteContents(TRUE
);
1023 printf("Hash created: %u foos in hash, %u foos totally\n",
1024 hash
.GetCount(), Foo::count
);
1026 static const int hashTestData
[] =
1028 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
1032 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1034 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
1037 printf("Hash filled: %u foos in hash, %u foos totally\n",
1038 hash
.GetCount(), Foo::count
);
1040 puts("Hash access test:");
1041 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1043 printf("\tGetting element with key %d, value %d: ",
1044 hashTestData
[n
], n
);
1045 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1048 printf("ERROR, not found.\n");
1052 printf("%d (%s)\n", foo
->n
,
1053 (size_t)foo
->n
== n
? "ok" : "ERROR");
1057 printf("\nTrying to get an element not in hash: ");
1059 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1061 puts("ERROR: found!");
1065 puts("ok (not found)");
1069 printf("Hash destroyed: %u foos left\n", Foo::count
);
1074 // ----------------------------------------------------------------------------
1076 // ----------------------------------------------------------------------------
1080 #include "wx/list.h"
1082 WX_DECLARE_LIST(Bar
, wxListBars
);
1083 #include "wx/listimpl.cpp"
1084 WX_DEFINE_LIST(wxListBars
);
1086 static void TestListCtor()
1088 puts("*** Testing wxList construction ***\n");
1092 list1
.Append(new Bar(_T("first")));
1093 list1
.Append(new Bar(_T("second")));
1095 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1096 list1
.GetCount(), Bar::GetNumber());
1101 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1102 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1104 list1
.DeleteContents(TRUE
);
1107 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1112 // ----------------------------------------------------------------------------
1114 // ----------------------------------------------------------------------------
1118 #include "wx/intl.h"
1119 #include "wx/utils.h" // for wxSetEnv
1121 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1123 // find the name of the language from its value
1124 static const char *GetLangName(int lang
)
1126 static const char *languageNames
[] =
1147 "ARABIC_SAUDI_ARABIA",
1172 "CHINESE_SIMPLIFIED",
1173 "CHINESE_TRADITIONAL",
1176 "CHINESE_SINGAPORE",
1187 "ENGLISH_AUSTRALIA",
1191 "ENGLISH_CARIBBEAN",
1195 "ENGLISH_NEW_ZEALAND",
1196 "ENGLISH_PHILIPPINES",
1197 "ENGLISH_SOUTH_AFRICA",
1209 "FRENCH_LUXEMBOURG",
1218 "GERMAN_LIECHTENSTEIN",
1219 "GERMAN_LUXEMBOURG",
1260 "MALAY_BRUNEI_DARUSSALAM",
1272 "NORWEGIAN_NYNORSK",
1279 "PORTUGUESE_BRAZILIAN",
1304 "SPANISH_ARGENTINA",
1308 "SPANISH_COSTA_RICA",
1309 "SPANISH_DOMINICAN_REPUBLIC",
1311 "SPANISH_EL_SALVADOR",
1312 "SPANISH_GUATEMALA",
1316 "SPANISH_NICARAGUA",
1320 "SPANISH_PUERTO_RICO",
1323 "SPANISH_VENEZUELA",
1360 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1361 return languageNames
[lang
];
1366 static void TestDefaultLang()
1368 puts("*** Testing wxLocale::GetSystemLanguage ***");
1370 static const wxChar
*langStrings
[] =
1372 NULL
, // system default
1379 _T("de_DE.iso88591"),
1381 _T("?"), // invalid lang spec
1382 _T("klingonese"), // I bet on some systems it does exist...
1385 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1386 wxLocale::GetSystemEncodingName().c_str(),
1387 wxLocale::GetSystemEncoding());
1389 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1391 const char *langStr
= langStrings
[n
];
1394 // FIXME: this doesn't do anything at all under Windows, we need
1395 // to create a new wxLocale!
1396 wxSetEnv(_T("LC_ALL"), langStr
);
1399 int lang
= gs_localeDefault
.GetSystemLanguage();
1400 printf("Locale for '%s' is %s.\n",
1401 langStr
? langStr
: "system default", GetLangName(lang
));
1405 #endif // TEST_LOCALE
1407 // ----------------------------------------------------------------------------
1409 // ----------------------------------------------------------------------------
1413 #include "wx/mimetype.h"
1415 static void TestMimeEnum()
1417 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1419 wxArrayString mimetypes
;
1421 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1423 printf("*** All %u known filetypes: ***\n", count
);
1428 for ( size_t n
= 0; n
< count
; n
++ )
1430 wxFileType
*filetype
=
1431 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1434 printf("nothing known about the filetype '%s'!\n",
1435 mimetypes
[n
].c_str());
1439 filetype
->GetDescription(&desc
);
1440 filetype
->GetExtensions(exts
);
1442 filetype
->GetIcon(NULL
);
1445 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1448 extsAll
<< _T(", ");
1452 printf("\t%s: %s (%s)\n",
1453 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1459 static void TestMimeOverride()
1461 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1463 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1464 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1466 if ( wxFile::Exists(mailcap
) )
1467 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1469 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1471 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1474 if ( wxFile::Exists(mimetypes
) )
1475 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1477 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1479 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1485 static void TestMimeFilename()
1487 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1489 static const wxChar
*filenames
[] =
1496 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1498 const wxString fname
= filenames
[n
];
1499 wxString ext
= fname
.AfterLast(_T('.'));
1500 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1503 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1508 if ( !ft
->GetDescription(&desc
) )
1509 desc
= _T("<no description>");
1512 if ( !ft
->GetOpenCommand(&cmd
,
1513 wxFileType::MessageParameters(fname
, _T(""))) )
1514 cmd
= _T("<no command available>");
1516 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1517 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1526 static void TestMimeAssociate()
1528 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1530 wxFileTypeInfo
ftInfo(
1531 _T("application/x-xyz"),
1532 _T("xyzview '%s'"), // open cmd
1533 _T(""), // print cmd
1534 _T("XYZ File") // description
1535 _T(".xyz"), // extensions
1536 NULL
// end of extensions
1538 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1540 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1543 wxPuts(_T("ERROR: failed to create association!"));
1547 // TODO: read it back
1556 // ----------------------------------------------------------------------------
1557 // misc information functions
1558 // ----------------------------------------------------------------------------
1560 #ifdef TEST_INFO_FUNCTIONS
1562 #include "wx/utils.h"
1564 static void TestDiskInfo()
1566 puts("*** Testing wxGetDiskSpace() ***");
1571 printf("\nEnter a directory name: ");
1572 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1575 // kill the last '\n'
1576 pathname
[strlen(pathname
) - 1] = 0;
1578 wxLongLong total
, free
;
1579 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1581 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1585 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1586 (total
/ 1024).ToString().c_str(),
1587 (free
/ 1024).ToString().c_str(),
1593 static void TestOsInfo()
1595 puts("*** Testing OS info functions ***\n");
1598 wxGetOsVersion(&major
, &minor
);
1599 printf("Running under: %s, version %d.%d\n",
1600 wxGetOsDescription().c_str(), major
, minor
);
1602 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1604 printf("Host name is %s (%s).\n",
1605 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1610 static void TestUserInfo()
1612 puts("*** Testing user info functions ***\n");
1614 printf("User id is:\t%s\n", wxGetUserId().c_str());
1615 printf("User name is:\t%s\n", wxGetUserName().c_str());
1616 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1617 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1622 #endif // TEST_INFO_FUNCTIONS
1624 // ----------------------------------------------------------------------------
1626 // ----------------------------------------------------------------------------
1628 #ifdef TEST_LONGLONG
1630 #include "wx/longlong.h"
1631 #include "wx/timer.h"
1633 // make a 64 bit number from 4 16 bit ones
1634 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1636 // get a random 64 bit number
1637 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1639 static const long testLongs
[] =
1650 #if wxUSE_LONGLONG_WX
1651 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1652 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1653 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1654 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1655 #endif // wxUSE_LONGLONG_WX
1657 static void TestSpeed()
1659 static const long max
= 100000000;
1666 for ( n
= 0; n
< max
; n
++ )
1671 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1674 #if wxUSE_LONGLONG_NATIVE
1679 for ( n
= 0; n
< max
; n
++ )
1684 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1686 #endif // wxUSE_LONGLONG_NATIVE
1692 for ( n
= 0; n
< max
; n
++ )
1697 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1701 static void TestLongLongConversion()
1703 puts("*** Testing wxLongLong conversions ***\n");
1707 for ( size_t n
= 0; n
< 100000; n
++ )
1711 #if wxUSE_LONGLONG_NATIVE
1712 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1714 wxASSERT_MSG( a
== b
, "conversions failure" );
1716 puts("Can't do it without native long long type, test skipped.");
1719 #endif // wxUSE_LONGLONG_NATIVE
1721 if ( !(nTested
% 1000) )
1733 static void TestMultiplication()
1735 puts("*** Testing wxLongLong multiplication ***\n");
1739 for ( size_t n
= 0; n
< 100000; n
++ )
1744 #if wxUSE_LONGLONG_NATIVE
1745 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1746 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1748 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1749 #else // !wxUSE_LONGLONG_NATIVE
1750 puts("Can't do it without native long long type, test skipped.");
1753 #endif // wxUSE_LONGLONG_NATIVE
1755 if ( !(nTested
% 1000) )
1767 static void TestDivision()
1769 puts("*** Testing wxLongLong division ***\n");
1773 for ( size_t n
= 0; n
< 100000; n
++ )
1775 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1776 // multiplication will not overflow)
1777 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1779 // get a random long (not wxLongLong for now) to divide it with
1784 #if wxUSE_LONGLONG_NATIVE
1785 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1787 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1788 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1789 #else // !wxUSE_LONGLONG_NATIVE
1790 // verify the result
1791 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1792 #endif // wxUSE_LONGLONG_NATIVE
1794 if ( !(nTested
% 1000) )
1806 static void TestAddition()
1808 puts("*** Testing wxLongLong addition ***\n");
1812 for ( size_t n
= 0; n
< 100000; n
++ )
1818 #if wxUSE_LONGLONG_NATIVE
1819 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1820 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1821 "addition failure" );
1822 #else // !wxUSE_LONGLONG_NATIVE
1823 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1824 #endif // wxUSE_LONGLONG_NATIVE
1826 if ( !(nTested
% 1000) )
1838 static void TestBitOperations()
1840 puts("*** Testing wxLongLong bit operation ***\n");
1844 for ( size_t n
= 0; n
< 100000; n
++ )
1848 #if wxUSE_LONGLONG_NATIVE
1849 for ( size_t n
= 0; n
< 33; n
++ )
1852 #else // !wxUSE_LONGLONG_NATIVE
1853 puts("Can't do it without native long long type, test skipped.");
1856 #endif // wxUSE_LONGLONG_NATIVE
1858 if ( !(nTested
% 1000) )
1870 static void TestLongLongComparison()
1872 #if wxUSE_LONGLONG_WX
1873 puts("*** Testing wxLongLong comparison ***\n");
1875 static const long ls
[2] =
1881 wxLongLongWx lls
[2];
1885 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1889 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1891 res
= lls
[m
] > testLongs
[n
];
1892 printf("0x%lx > 0x%lx is %s (%s)\n",
1893 ls
[m
], testLongs
[n
], res
? "true" : "false",
1894 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1896 res
= lls
[m
] < testLongs
[n
];
1897 printf("0x%lx < 0x%lx is %s (%s)\n",
1898 ls
[m
], testLongs
[n
], res
? "true" : "false",
1899 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1901 res
= lls
[m
] == testLongs
[n
];
1902 printf("0x%lx == 0x%lx is %s (%s)\n",
1903 ls
[m
], testLongs
[n
], res
? "true" : "false",
1904 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1907 #endif // wxUSE_LONGLONG_WX
1910 static void TestLongLongPrint()
1912 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
1914 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1916 wxLongLong ll
= testLongs
[n
];
1917 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
1920 wxLongLong
ll(0x12345678, 0x87654321);
1921 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1924 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1930 #endif // TEST_LONGLONG
1932 // ----------------------------------------------------------------------------
1934 // ----------------------------------------------------------------------------
1936 #ifdef TEST_PATHLIST
1938 static void TestPathList()
1940 puts("*** Testing wxPathList ***\n");
1942 wxPathList pathlist
;
1943 pathlist
.AddEnvList("PATH");
1944 wxString path
= pathlist
.FindValidPath("ls");
1947 printf("ERROR: command not found in the path.\n");
1951 printf("Command found in the path as '%s'.\n", path
.c_str());
1955 #endif // TEST_PATHLIST
1957 // ----------------------------------------------------------------------------
1958 // regular expressions
1959 // ----------------------------------------------------------------------------
1963 #include "wx/regex.h"
1965 static void TestRegExCompile()
1967 wxPuts(_T("*** Testing RE compilation ***\n"));
1969 static struct RegExCompTestData
1971 const wxChar
*pattern
;
1973 } regExCompTestData
[] =
1975 { _T("foo"), TRUE
},
1976 { _T("foo("), FALSE
},
1977 { _T("foo(bar"), FALSE
},
1978 { _T("foo(bar)"), TRUE
},
1979 { _T("foo["), FALSE
},
1980 { _T("foo[bar"), FALSE
},
1981 { _T("foo[bar]"), TRUE
},
1982 { _T("foo{"), TRUE
},
1983 { _T("foo{1"), FALSE
},
1984 { _T("foo{bar"), TRUE
},
1985 { _T("foo{1}"), TRUE
},
1986 { _T("foo{1,2}"), TRUE
},
1987 { _T("foo{bar}"), TRUE
},
1988 { _T("foo*"), TRUE
},
1989 { _T("foo**"), FALSE
},
1990 { _T("foo+"), TRUE
},
1991 { _T("foo++"), FALSE
},
1992 { _T("foo?"), TRUE
},
1993 { _T("foo??"), FALSE
},
1994 { _T("foo?+"), FALSE
},
1998 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
2000 const RegExCompTestData
& data
= regExCompTestData
[n
];
2001 bool ok
= re
.Compile(data
.pattern
);
2003 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
2005 ok
? _T("") : _T("not "),
2006 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2010 static void TestRegExMatch()
2012 wxPuts(_T("*** Testing RE matching ***\n"));
2014 static struct RegExMatchTestData
2016 const wxChar
*pattern
;
2019 } regExMatchTestData
[] =
2021 { _T("foo"), _T("bar"), FALSE
},
2022 { _T("foo"), _T("foobar"), TRUE
},
2023 { _T("^foo"), _T("foobar"), TRUE
},
2024 { _T("^foo"), _T("barfoo"), FALSE
},
2025 { _T("bar$"), _T("barbar"), TRUE
},
2026 { _T("bar$"), _T("barbar "), FALSE
},
2029 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
2031 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
2033 wxRegEx
re(data
.pattern
);
2034 bool ok
= re
.Matches(data
.text
);
2036 wxPrintf(_T("'%s' %s %s (%s)\n"),
2038 ok
? _T("matches") : _T("doesn't match"),
2040 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2044 static void TestRegExSubmatch()
2046 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2048 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2049 if ( !re
.IsValid() )
2051 wxPuts(_T("ERROR: compilation failed."));
2055 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2057 if ( !re
.Matches(text
) )
2059 wxPuts(_T("ERROR: match expected."));
2063 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2065 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2066 re
.GetMatch(text
, 3).c_str(),
2067 re
.GetMatch(text
, 2).c_str(),
2068 re
.GetMatch(text
, 4).c_str(),
2069 re
.GetMatch(text
, 1).c_str());
2073 static void TestRegExReplacement()
2075 wxPuts(_T("*** Testing RE replacement ***"));
2077 static struct RegExReplTestData
2081 const wxChar
*result
;
2083 } regExReplTestData
[] =
2085 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2086 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2087 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2088 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2089 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2090 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2091 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2094 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2095 wxRegEx re
= pattern
;
2097 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2099 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2101 const RegExReplTestData
& data
= regExReplTestData
[n
];
2103 wxString text
= data
.text
;
2104 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2106 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2107 data
.text
, data
.repl
,
2108 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2110 if ( text
== data
.result
&& nRepl
== data
.count
)
2116 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2117 data
.count
, data
.result
);
2122 static void TestRegExInteractive()
2124 wxPuts(_T("*** Testing RE interactively ***"));
2129 printf("\nEnter a pattern: ");
2130 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2133 // kill the last '\n'
2134 pattern
[strlen(pattern
) - 1] = 0;
2137 if ( !re
.Compile(pattern
) )
2145 printf("Enter text to match: ");
2146 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2149 // kill the last '\n'
2150 text
[strlen(text
) - 1] = 0;
2152 if ( !re
.Matches(text
) )
2154 printf("No match.\n");
2158 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2161 for ( size_t n
= 1; ; n
++ )
2163 if ( !re
.GetMatch(&start
, &len
, n
) )
2168 printf("Subexpr %u matched '%s'\n",
2169 n
, wxString(text
+ start
, len
).c_str());
2176 #endif // TEST_REGEX
2178 // ----------------------------------------------------------------------------
2179 // registry and related stuff
2180 // ----------------------------------------------------------------------------
2182 // this is for MSW only
2185 #undef TEST_REGISTRY
2190 #include "wx/confbase.h"
2191 #include "wx/msw/regconf.h"
2193 static void TestRegConfWrite()
2195 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2196 regconf
.Write(_T("Hello"), wxString(_T("world")));
2199 #endif // TEST_REGCONF
2201 #ifdef TEST_REGISTRY
2203 #include "wx/msw/registry.h"
2205 // I chose this one because I liked its name, but it probably only exists under
2207 static const wxChar
*TESTKEY
=
2208 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2210 static void TestRegistryRead()
2212 puts("*** testing registry reading ***");
2214 wxRegKey
key(TESTKEY
);
2215 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2218 puts("ERROR: test key can't be opened, aborting test.");
2223 size_t nSubKeys
, nValues
;
2224 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2226 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2229 printf("Enumerating values:\n");
2233 bool cont
= key
.GetFirstValue(value
, dummy
);
2236 printf("Value '%s': type ", value
.c_str());
2237 switch ( key
.GetValueType(value
) )
2239 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2240 case wxRegKey::Type_String
: printf("SZ"); break;
2241 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2242 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2243 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2244 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2245 default: printf("other (unknown)"); break;
2248 printf(", value = ");
2249 if ( key
.IsNumericValue(value
) )
2252 key
.QueryValue(value
, &val
);
2258 key
.QueryValue(value
, val
);
2259 printf("'%s'", val
.c_str());
2261 key
.QueryRawValue(value
, val
);
2262 printf(" (raw value '%s')", val
.c_str());
2267 cont
= key
.GetNextValue(value
, dummy
);
2271 static void TestRegistryAssociation()
2274 The second call to deleteself genertaes an error message, with a
2275 messagebox saying .flo is crucial to system operation, while the .ddf
2276 call also fails, but with no error message
2281 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2283 key
= "ddxf_auto_file" ;
2284 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2286 key
= "ddxf_auto_file" ;
2287 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2290 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2292 key
= "program \"%1\"" ;
2294 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2296 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2298 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2300 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2304 #endif // TEST_REGISTRY
2306 // ----------------------------------------------------------------------------
2308 // ----------------------------------------------------------------------------
2312 #include "wx/socket.h"
2313 #include "wx/protocol/protocol.h"
2314 #include "wx/protocol/http.h"
2316 static void TestSocketServer()
2318 puts("*** Testing wxSocketServer ***\n");
2320 static const int PORT
= 3000;
2325 wxSocketServer
*server
= new wxSocketServer(addr
);
2326 if ( !server
->Ok() )
2328 puts("ERROR: failed to bind");
2335 printf("Server: waiting for connection on port %d...\n", PORT
);
2337 wxSocketBase
*socket
= server
->Accept();
2340 puts("ERROR: wxSocketServer::Accept() failed.");
2344 puts("Server: got a client.");
2346 server
->SetTimeout(60); // 1 min
2348 while ( socket
->IsConnected() )
2354 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2356 // don't log error if the client just close the connection
2357 if ( socket
->IsConnected() )
2359 puts("ERROR: in wxSocket::Read.");
2379 printf("Server: got '%s'.\n", s
.c_str());
2380 if ( s
== _T("bye") )
2387 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2388 socket
->Write("\r\n", 2);
2389 printf("Server: wrote '%s'.\n", s
.c_str());
2392 puts("Server: lost a client.");
2397 // same as "delete server" but is consistent with GUI programs
2401 static void TestSocketClient()
2403 puts("*** Testing wxSocketClient ***\n");
2405 static const char *hostname
= "www.wxwindows.org";
2408 addr
.Hostname(hostname
);
2411 printf("--- Attempting to connect to %s:80...\n", hostname
);
2413 wxSocketClient client
;
2414 if ( !client
.Connect(addr
) )
2416 printf("ERROR: failed to connect to %s\n", hostname
);
2420 printf("--- Connected to %s:%u...\n",
2421 addr
.Hostname().c_str(), addr
.Service());
2425 // could use simply "GET" here I suppose
2427 wxString::Format("GET http://%s/\r\n", hostname
);
2428 client
.Write(cmdGet
, cmdGet
.length());
2429 printf("--- Sent command '%s' to the server\n",
2430 MakePrintable(cmdGet
).c_str());
2431 client
.Read(buf
, WXSIZEOF(buf
));
2432 printf("--- Server replied:\n%s", buf
);
2436 #endif // TEST_SOCKETS
2438 // ----------------------------------------------------------------------------
2440 // ----------------------------------------------------------------------------
2444 #include "wx/protocol/ftp.h"
2448 #define FTP_ANONYMOUS
2450 #ifdef FTP_ANONYMOUS
2451 static const char *directory
= "/pub";
2452 static const char *filename
= "welcome.msg";
2454 static const char *directory
= "/etc";
2455 static const char *filename
= "issue";
2458 static bool TestFtpConnect()
2460 puts("*** Testing FTP connect ***");
2462 #ifdef FTP_ANONYMOUS
2463 static const char *hostname
= "ftp.wxwindows.org";
2465 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2466 #else // !FTP_ANONYMOUS
2467 static const char *hostname
= "localhost";
2470 fgets(user
, WXSIZEOF(user
), stdin
);
2471 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2475 printf("Password for %s: ", password
);
2476 fgets(password
, WXSIZEOF(password
), stdin
);
2477 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2478 ftp
.SetPassword(password
);
2480 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2481 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2483 if ( !ftp
.Connect(hostname
) )
2485 printf("ERROR: failed to connect to %s\n", hostname
);
2491 printf("--- Connected to %s, current directory is '%s'\n",
2492 hostname
, ftp
.Pwd().c_str());
2498 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2499 static void TestFtpWuFtpd()
2502 static const char *hostname
= "ftp.eudora.com";
2503 if ( !ftp
.Connect(hostname
) )
2505 printf("ERROR: failed to connect to %s\n", hostname
);
2509 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2510 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2513 printf("ERROR: couldn't get input stream for %s\n", filename
);
2517 size_t size
= in
->StreamSize();
2518 printf("Reading file %s (%u bytes)...", filename
, size
);
2520 char *data
= new char[size
];
2521 if ( !in
->Read(data
, size
) )
2523 puts("ERROR: read error");
2527 printf("Successfully retrieved the file.\n");
2536 static void TestFtpList()
2538 puts("*** Testing wxFTP file listing ***\n");
2541 if ( !ftp
.ChDir(directory
) )
2543 printf("ERROR: failed to cd to %s\n", directory
);
2546 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2548 // test NLIST and LIST
2549 wxArrayString files
;
2550 if ( !ftp
.GetFilesList(files
) )
2552 puts("ERROR: failed to get NLIST of files");
2556 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2557 size_t count
= files
.GetCount();
2558 for ( size_t n
= 0; n
< count
; n
++ )
2560 printf("\t%s\n", files
[n
].c_str());
2562 puts("End of the file list");
2565 if ( !ftp
.GetDirList(files
) )
2567 puts("ERROR: failed to get LIST of files");
2571 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2572 size_t count
= files
.GetCount();
2573 for ( size_t n
= 0; n
< count
; n
++ )
2575 printf("\t%s\n", files
[n
].c_str());
2577 puts("End of the file list");
2580 if ( !ftp
.ChDir(_T("..")) )
2582 puts("ERROR: failed to cd to ..");
2585 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2588 static void TestFtpDownload()
2590 puts("*** Testing wxFTP download ***\n");
2593 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2596 printf("ERROR: couldn't get input stream for %s\n", filename
);
2600 size_t size
= in
->StreamSize();
2601 printf("Reading file %s (%u bytes)...", filename
, size
);
2604 char *data
= new char[size
];
2605 if ( !in
->Read(data
, size
) )
2607 puts("ERROR: read error");
2611 printf("\nContents of %s:\n%s\n", filename
, data
);
2619 static void TestFtpFileSize()
2621 puts("*** Testing FTP SIZE command ***");
2623 if ( !ftp
.ChDir(directory
) )
2625 printf("ERROR: failed to cd to %s\n", directory
);
2628 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2630 if ( ftp
.FileExists(filename
) )
2632 int size
= ftp
.GetFileSize(filename
);
2634 printf("ERROR: couldn't get size of '%s'\n", filename
);
2636 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2640 printf("ERROR: '%s' doesn't exist\n", filename
);
2644 static void TestFtpMisc()
2646 puts("*** Testing miscellaneous wxFTP functions ***");
2648 if ( ftp
.SendCommand("STAT") != '2' )
2650 puts("ERROR: STAT failed");
2654 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2657 if ( ftp
.SendCommand("HELP SITE") != '2' )
2659 puts("ERROR: HELP SITE failed");
2663 printf("The list of site-specific commands:\n\n%s\n",
2664 ftp
.GetLastResult().c_str());
2668 static void TestFtpInteractive()
2670 puts("\n*** Interactive wxFTP test ***");
2676 printf("Enter FTP command: ");
2677 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2680 // kill the last '\n'
2681 buf
[strlen(buf
) - 1] = 0;
2683 // special handling of LIST and NLST as they require data connection
2684 wxString
start(buf
, 4);
2686 if ( start
== "LIST" || start
== "NLST" )
2689 if ( strlen(buf
) > 4 )
2692 wxArrayString files
;
2693 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2695 printf("ERROR: failed to get %s of files\n", start
.c_str());
2699 printf("--- %s of '%s' under '%s':\n",
2700 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2701 size_t count
= files
.GetCount();
2702 for ( size_t n
= 0; n
< count
; n
++ )
2704 printf("\t%s\n", files
[n
].c_str());
2706 puts("--- End of the file list");
2711 char ch
= ftp
.SendCommand(buf
);
2712 printf("Command %s", ch
? "succeeded" : "failed");
2715 printf(" (return code %c)", ch
);
2718 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2722 puts("\n*** done ***");
2725 static void TestFtpUpload()
2727 puts("*** Testing wxFTP uploading ***\n");
2730 static const char *file1
= "test1";
2731 static const char *file2
= "test2";
2732 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2735 printf("--- Uploading to %s ---\n", file1
);
2736 out
->Write("First hello", 11);
2740 // send a command to check the remote file
2741 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2743 printf("ERROR: STAT %s failed\n", file1
);
2747 printf("STAT %s returned:\n\n%s\n",
2748 file1
, ftp
.GetLastResult().c_str());
2751 out
= ftp
.GetOutputStream(file2
);
2754 printf("--- Uploading to %s ---\n", file1
);
2755 out
->Write("Second hello", 12);
2762 // ----------------------------------------------------------------------------
2764 // ----------------------------------------------------------------------------
2768 #include "wx/wfstream.h"
2769 #include "wx/mstream.h"
2771 static void TestFileStream()
2773 puts("*** Testing wxFileInputStream ***");
2775 static const wxChar
*filename
= _T("testdata.fs");
2777 wxFileOutputStream
fsOut(filename
);
2778 fsOut
.Write("foo", 3);
2781 wxFileInputStream
fsIn(filename
);
2782 printf("File stream size: %u\n", fsIn
.GetSize());
2783 while ( !fsIn
.Eof() )
2785 putchar(fsIn
.GetC());
2788 if ( !wxRemoveFile(filename
) )
2790 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2793 puts("\n*** wxFileInputStream test done ***");
2796 static void TestMemoryStream()
2798 puts("*** Testing wxMemoryInputStream ***");
2801 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2803 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2804 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2805 while ( !memInpStream
.Eof() )
2807 putchar(memInpStream
.GetC());
2810 puts("\n*** wxMemoryInputStream test done ***");
2813 #endif // TEST_STREAMS
2815 // ----------------------------------------------------------------------------
2817 // ----------------------------------------------------------------------------
2821 #include "wx/timer.h"
2822 #include "wx/utils.h"
2824 static void TestStopWatch()
2826 puts("*** Testing wxStopWatch ***\n");
2829 printf("Sleeping 3 seconds...");
2831 printf("\telapsed time: %ldms\n", sw
.Time());
2834 printf("Sleeping 2 more seconds...");
2836 printf("\telapsed time: %ldms\n", sw
.Time());
2839 printf("And 3 more seconds...");
2841 printf("\telapsed time: %ldms\n", sw
.Time());
2844 puts("\nChecking for 'backwards clock' bug...");
2845 for ( size_t n
= 0; n
< 70; n
++ )
2849 for ( size_t m
= 0; m
< 100000; m
++ )
2851 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2853 puts("\ntime is negative - ERROR!");
2863 #endif // TEST_TIMER
2865 // ----------------------------------------------------------------------------
2867 // ----------------------------------------------------------------------------
2871 #include "wx/vcard.h"
2873 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2876 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2880 wxString(_T('\t'), level
).c_str(),
2881 vcObj
->GetName().c_str());
2884 switch ( vcObj
->GetType() )
2886 case wxVCardObject::String
:
2887 case wxVCardObject::UString
:
2890 vcObj
->GetValue(&val
);
2891 value
<< _T('"') << val
<< _T('"');
2895 case wxVCardObject::Int
:
2898 vcObj
->GetValue(&i
);
2899 value
.Printf(_T("%u"), i
);
2903 case wxVCardObject::Long
:
2906 vcObj
->GetValue(&l
);
2907 value
.Printf(_T("%lu"), l
);
2911 case wxVCardObject::None
:
2914 case wxVCardObject::Object
:
2915 value
= _T("<node>");
2919 value
= _T("<unknown value type>");
2923 printf(" = %s", value
.c_str());
2926 DumpVObject(level
+ 1, *vcObj
);
2929 vcObj
= vcard
.GetNextProp(&cookie
);
2933 static void DumpVCardAddresses(const wxVCard
& vcard
)
2935 puts("\nShowing all addresses from vCard:\n");
2939 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2943 int flags
= addr
->GetFlags();
2944 if ( flags
& wxVCardAddress::Domestic
)
2946 flagsStr
<< _T("domestic ");
2948 if ( flags
& wxVCardAddress::Intl
)
2950 flagsStr
<< _T("international ");
2952 if ( flags
& wxVCardAddress::Postal
)
2954 flagsStr
<< _T("postal ");
2956 if ( flags
& wxVCardAddress::Parcel
)
2958 flagsStr
<< _T("parcel ");
2960 if ( flags
& wxVCardAddress::Home
)
2962 flagsStr
<< _T("home ");
2964 if ( flags
& wxVCardAddress::Work
)
2966 flagsStr
<< _T("work ");
2969 printf("Address %u:\n"
2971 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2974 addr
->GetPostOffice().c_str(),
2975 addr
->GetExtAddress().c_str(),
2976 addr
->GetStreet().c_str(),
2977 addr
->GetLocality().c_str(),
2978 addr
->GetRegion().c_str(),
2979 addr
->GetPostalCode().c_str(),
2980 addr
->GetCountry().c_str()
2984 addr
= vcard
.GetNextAddress(&cookie
);
2988 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2990 puts("\nShowing all phone numbers from vCard:\n");
2994 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2998 int flags
= phone
->GetFlags();
2999 if ( flags
& wxVCardPhoneNumber::Voice
)
3001 flagsStr
<< _T("voice ");
3003 if ( flags
& wxVCardPhoneNumber::Fax
)
3005 flagsStr
<< _T("fax ");
3007 if ( flags
& wxVCardPhoneNumber::Cellular
)
3009 flagsStr
<< _T("cellular ");
3011 if ( flags
& wxVCardPhoneNumber::Modem
)
3013 flagsStr
<< _T("modem ");
3015 if ( flags
& wxVCardPhoneNumber::Home
)
3017 flagsStr
<< _T("home ");
3019 if ( flags
& wxVCardPhoneNumber::Work
)
3021 flagsStr
<< _T("work ");
3024 printf("Phone number %u:\n"
3029 phone
->GetNumber().c_str()
3033 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3037 static void TestVCardRead()
3039 puts("*** Testing wxVCard reading ***\n");
3041 wxVCard
vcard(_T("vcard.vcf"));
3042 if ( !vcard
.IsOk() )
3044 puts("ERROR: couldn't load vCard.");
3048 // read individual vCard properties
3049 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3053 vcObj
->GetValue(&value
);
3058 value
= _T("<none>");
3061 printf("Full name retrieved directly: %s\n", value
.c_str());
3064 if ( !vcard
.GetFullName(&value
) )
3066 value
= _T("<none>");
3069 printf("Full name from wxVCard API: %s\n", value
.c_str());
3071 // now show how to deal with multiply occuring properties
3072 DumpVCardAddresses(vcard
);
3073 DumpVCardPhoneNumbers(vcard
);
3075 // and finally show all
3076 puts("\nNow dumping the entire vCard:\n"
3077 "-----------------------------\n");
3079 DumpVObject(0, vcard
);
3083 static void TestVCardWrite()
3085 puts("*** Testing wxVCard writing ***\n");
3088 if ( !vcard
.IsOk() )
3090 puts("ERROR: couldn't create vCard.");
3095 vcard
.SetName("Zeitlin", "Vadim");
3096 vcard
.SetFullName("Vadim Zeitlin");
3097 vcard
.SetOrganization("wxWindows", "R&D");
3099 // just dump the vCard back
3100 puts("Entire vCard follows:\n");
3101 puts(vcard
.Write());
3105 #endif // TEST_VCARD
3107 // ----------------------------------------------------------------------------
3108 // wide char (Unicode) support
3109 // ----------------------------------------------------------------------------
3113 #include "wx/strconv.h"
3114 #include "wx/fontenc.h"
3115 #include "wx/encconv.h"
3116 #include "wx/buffer.h"
3118 static void TestUtf8()
3120 puts("*** Testing UTF8 support ***\n");
3122 static const char textInUtf8
[] =
3124 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3125 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3126 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3127 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3128 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3129 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3130 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3135 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3137 puts("ERROR: UTF-8 decoding failed.");
3141 // using wxEncodingConverter
3143 wxEncodingConverter ec
;
3144 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3145 ec
.Convert(wbuf
, buf
);
3146 #else // using wxCSConv
3147 wxCSConv
conv(_T("koi8-r"));
3148 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3150 puts("ERROR: conversion to KOI8-R failed.");
3155 printf("The resulting string (in koi8-r): %s\n", buf
);
3159 #endif // TEST_WCHAR
3161 // ----------------------------------------------------------------------------
3163 // ----------------------------------------------------------------------------
3167 #include "wx/filesys.h"
3168 #include "wx/fs_zip.h"
3169 #include "wx/zipstrm.h"
3171 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3173 static void TestZipStreamRead()
3175 puts("*** Testing ZIP reading ***\n");
3177 static const wxChar
*filename
= _T("foo");
3178 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3179 printf("Archive size: %u\n", istr
.GetSize());
3181 printf("Dumping the file '%s':\n", filename
);
3182 while ( !istr
.Eof() )
3184 putchar(istr
.GetC());
3188 puts("\n----- done ------");
3191 static void DumpZipDirectory(wxFileSystem
& fs
,
3192 const wxString
& dir
,
3193 const wxString
& indent
)
3195 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3196 TESTFILE_ZIP
, dir
.c_str());
3197 wxString wildcard
= prefix
+ _T("/*");
3199 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3200 while ( !dirname
.empty() )
3202 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3204 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3209 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3211 DumpZipDirectory(fs
, dirname
,
3212 indent
+ wxString(_T(' '), 4));
3214 dirname
= fs
.FindNext();
3217 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3218 while ( !filename
.empty() )
3220 if ( !filename
.StartsWith(prefix
, &filename
) )
3222 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3227 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3229 filename
= fs
.FindNext();
3233 static void TestZipFileSystem()
3235 puts("*** Testing ZIP file system ***\n");
3237 wxFileSystem::AddHandler(new wxZipFSHandler
);
3239 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3241 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3246 // ----------------------------------------------------------------------------
3248 // ----------------------------------------------------------------------------
3252 #include "wx/zstream.h"
3253 #include "wx/wfstream.h"
3255 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3256 static const char *TEST_DATA
= "hello and hello again";
3258 static void TestZlibStreamWrite()
3260 puts("*** Testing Zlib stream reading ***\n");
3262 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3263 wxZlibOutputStream
ostr(fileOutStream
, 0);
3264 printf("Compressing the test string... ");
3265 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3268 puts("(ERROR: failed)");
3275 puts("\n----- done ------");
3278 static void TestZlibStreamRead()
3280 puts("*** Testing Zlib stream reading ***\n");
3282 wxFileInputStream
fileInStream(FILENAME_GZ
);
3283 wxZlibInputStream
istr(fileInStream
);
3284 printf("Archive size: %u\n", istr
.GetSize());
3286 puts("Dumping the file:");
3287 while ( !istr
.Eof() )
3289 putchar(istr
.GetC());
3293 puts("\n----- done ------");
3298 // ----------------------------------------------------------------------------
3300 // ----------------------------------------------------------------------------
3302 #ifdef TEST_DATETIME
3306 #include "wx/date.h"
3307 #include "wx/datetime.h"
3312 wxDateTime::wxDateTime_t day
;
3313 wxDateTime::Month month
;
3315 wxDateTime::wxDateTime_t hour
, min
, sec
;
3317 wxDateTime::WeekDay wday
;
3318 time_t gmticks
, ticks
;
3320 void Init(const wxDateTime::Tm
& tm
)
3329 gmticks
= ticks
= -1;
3332 wxDateTime
DT() const
3333 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3335 bool SameDay(const wxDateTime::Tm
& tm
) const
3337 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3340 wxString
Format() const
3343 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3345 wxDateTime::GetMonthName(month
).c_str(),
3347 abs(wxDateTime::ConvertYearToBC(year
)),
3348 year
> 0 ? "AD" : "BC");
3352 wxString
FormatDate() const
3355 s
.Printf("%02d-%s-%4d%s",
3357 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3358 abs(wxDateTime::ConvertYearToBC(year
)),
3359 year
> 0 ? "AD" : "BC");
3364 static const Date testDates
[] =
3366 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3367 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3368 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3369 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3370 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3371 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3372 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3373 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3374 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3375 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3376 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3377 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3378 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3379 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3380 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3383 // this test miscellaneous static wxDateTime functions
3384 static void TestTimeStatic()
3386 puts("\n*** wxDateTime static methods test ***");
3388 // some info about the current date
3389 int year
= wxDateTime::GetCurrentYear();
3390 printf("Current year %d is %sa leap one and has %d days.\n",
3392 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3393 wxDateTime::GetNumberOfDays(year
));
3395 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3396 printf("Current month is '%s' ('%s') and it has %d days\n",
3397 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3398 wxDateTime::GetMonthName(month
).c_str(),
3399 wxDateTime::GetNumberOfDays(month
));
3402 static const size_t nYears
= 5;
3403 static const size_t years
[2][nYears
] =
3405 // first line: the years to test
3406 { 1990, 1976, 2000, 2030, 1984, },
3408 // second line: TRUE if leap, FALSE otherwise
3409 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3412 for ( size_t n
= 0; n
< nYears
; n
++ )
3414 int year
= years
[0][n
];
3415 bool should
= years
[1][n
] != 0,
3416 is
= wxDateTime::IsLeapYear(year
);
3418 printf("Year %d is %sa leap year (%s)\n",
3421 should
== is
? "ok" : "ERROR");
3423 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3427 // test constructing wxDateTime objects
3428 static void TestTimeSet()
3430 puts("\n*** wxDateTime construction test ***");
3432 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3434 const Date
& d1
= testDates
[n
];
3435 wxDateTime dt
= d1
.DT();
3438 d2
.Init(dt
.GetTm());
3440 wxString s1
= d1
.Format(),
3443 printf("Date: %s == %s (%s)\n",
3444 s1
.c_str(), s2
.c_str(),
3445 s1
== s2
? "ok" : "ERROR");
3449 // test time zones stuff
3450 static void TestTimeZones()
3452 puts("\n*** wxDateTime timezone test ***");
3454 wxDateTime now
= wxDateTime::Now();
3456 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3457 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3458 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3459 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3460 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3461 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3463 wxDateTime::Tm tm
= now
.GetTm();
3464 if ( wxDateTime(tm
) != now
)
3466 printf("ERROR: got %s instead of %s\n",
3467 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3471 // test some minimal support for the dates outside the standard range
3472 static void TestTimeRange()
3474 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3476 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3478 printf("Unix epoch:\t%s\n",
3479 wxDateTime(2440587.5).Format(fmt
).c_str());
3480 printf("Feb 29, 0: \t%s\n",
3481 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3482 printf("JDN 0: \t%s\n",
3483 wxDateTime(0.0).Format(fmt
).c_str());
3484 printf("Jan 1, 1AD:\t%s\n",
3485 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3486 printf("May 29, 2099:\t%s\n",
3487 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3490 static void TestTimeTicks()
3492 puts("\n*** wxDateTime ticks test ***");
3494 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3496 const Date
& d
= testDates
[n
];
3497 if ( d
.ticks
== -1 )
3500 wxDateTime dt
= d
.DT();
3501 long ticks
= (dt
.GetValue() / 1000).ToLong();
3502 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3503 if ( ticks
== d
.ticks
)
3509 printf(" (ERROR: should be %ld, delta = %ld)\n",
3510 d
.ticks
, ticks
- d
.ticks
);
3513 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3514 ticks
= (dt
.GetValue() / 1000).ToLong();
3515 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3516 if ( ticks
== d
.gmticks
)
3522 printf(" (ERROR: should be %ld, delta = %ld)\n",
3523 d
.gmticks
, ticks
- d
.gmticks
);
3530 // test conversions to JDN &c
3531 static void TestTimeJDN()
3533 puts("\n*** wxDateTime to JDN test ***");
3535 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3537 const Date
& d
= testDates
[n
];
3538 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3539 double jdn
= dt
.GetJulianDayNumber();
3541 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3548 printf(" (ERROR: should be %f, delta = %f)\n",
3549 d
.jdn
, jdn
- d
.jdn
);
3554 // test week days computation
3555 static void TestTimeWDays()
3557 puts("\n*** wxDateTime weekday test ***");
3559 // test GetWeekDay()
3561 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3563 const Date
& d
= testDates
[n
];
3564 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3566 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3569 wxDateTime::GetWeekDayName(wday
).c_str());
3570 if ( wday
== d
.wday
)
3576 printf(" (ERROR: should be %s)\n",
3577 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3583 // test SetToWeekDay()
3584 struct WeekDateTestData
3586 Date date
; // the real date (precomputed)
3587 int nWeek
; // its week index in the month
3588 wxDateTime::WeekDay wday
; // the weekday
3589 wxDateTime::Month month
; // the month
3590 int year
; // and the year
3592 wxString
Format() const
3595 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3597 case 1: which
= "first"; break;
3598 case 2: which
= "second"; break;
3599 case 3: which
= "third"; break;
3600 case 4: which
= "fourth"; break;
3601 case 5: which
= "fifth"; break;
3603 case -1: which
= "last"; break;
3608 which
+= " from end";
3611 s
.Printf("The %s %s of %s in %d",
3613 wxDateTime::GetWeekDayName(wday
).c_str(),
3614 wxDateTime::GetMonthName(month
).c_str(),
3621 // the array data was generated by the following python program
3623 from DateTime import *
3624 from whrandom import *
3625 from string import *
3627 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3628 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3630 week = DateTimeDelta(7)
3633 year = randint(1900, 2100)
3634 month = randint(1, 12)
3635 day = randint(1, 28)
3636 dt = DateTime(year, month, day)
3637 wday = dt.day_of_week
3639 countFromEnd = choice([-1, 1])
3642 while dt.month is month:
3643 dt = dt - countFromEnd * week
3644 weekNum = weekNum + countFromEnd
3646 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3648 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3649 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3652 static const WeekDateTestData weekDatesTestData
[] =
3654 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3655 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3656 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3657 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3658 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3659 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3660 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3661 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3662 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3663 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3664 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3665 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3666 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3667 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3668 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3669 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3670 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3671 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3672 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3673 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3676 static const char *fmt
= "%d-%b-%Y";
3679 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3681 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3683 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3685 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3687 const Date
& d
= wd
.date
;
3688 if ( d
.SameDay(dt
.GetTm()) )
3694 dt
.Set(d
.day
, d
.month
, d
.year
);
3696 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3701 // test the computation of (ISO) week numbers
3702 static void TestTimeWNumber()
3704 puts("\n*** wxDateTime week number test ***");
3706 struct WeekNumberTestData
3708 Date date
; // the date
3709 wxDateTime::wxDateTime_t week
; // the week number in the year
3710 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3711 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3712 wxDateTime::wxDateTime_t dnum
; // day number in the year
3715 // data generated with the following python script:
3717 from DateTime import *
3718 from whrandom import *
3719 from string import *
3721 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3722 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3724 def GetMonthWeek(dt):
3725 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3726 if weekNumMonth < 0:
3727 weekNumMonth = weekNumMonth + 53
3730 def GetLastSundayBefore(dt):
3731 if dt.iso_week[2] == 7:
3734 return dt - DateTimeDelta(dt.iso_week[2])
3737 year = randint(1900, 2100)
3738 month = randint(1, 12)
3739 day = randint(1, 28)
3740 dt = DateTime(year, month, day)
3741 dayNum = dt.day_of_year
3742 weekNum = dt.iso_week[1]
3743 weekNumMonth = GetMonthWeek(dt)
3746 dtSunday = GetLastSundayBefore(dt)
3748 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3749 weekNumMonth2 = weekNumMonth2 + 1
3750 dtSunday = dtSunday - DateTimeDelta(7)
3752 data = { 'day': rjust(`day`, 2), \
3753 'month': monthNames[month - 1], \
3755 'weekNum': rjust(`weekNum`, 2), \
3756 'weekNumMonth': weekNumMonth, \
3757 'weekNumMonth2': weekNumMonth2, \
3758 'dayNum': rjust(`dayNum`, 3) }
3760 print " { { %(day)s, "\
3761 "wxDateTime::%(month)s, "\
3764 "%(weekNumMonth)s, "\
3765 "%(weekNumMonth2)s, "\
3766 "%(dayNum)s }," % data
3769 static const WeekNumberTestData weekNumberTestDates
[] =
3771 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3772 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3773 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3774 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3775 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3776 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3777 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3778 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3779 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3780 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3781 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3782 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3783 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3784 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3785 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3786 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3787 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3788 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3789 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3790 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3793 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3795 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3796 const Date
& d
= wn
.date
;
3798 wxDateTime dt
= d
.DT();
3800 wxDateTime::wxDateTime_t
3801 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3802 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3803 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3804 dnum
= dt
.GetDayOfYear();
3806 printf("%s: the day number is %d",
3807 d
.FormatDate().c_str(), dnum
);
3808 if ( dnum
== wn
.dnum
)
3814 printf(" (ERROR: should be %d)", wn
.dnum
);
3817 printf(", week in month is %d", wmon
);
3818 if ( wmon
== wn
.wmon
)
3824 printf(" (ERROR: should be %d)", wn
.wmon
);
3827 printf(" or %d", wmon2
);
3828 if ( wmon2
== wn
.wmon2
)
3834 printf(" (ERROR: should be %d)", wn
.wmon2
);
3837 printf(", week in year is %d", week
);
3838 if ( week
== wn
.week
)
3844 printf(" (ERROR: should be %d)\n", wn
.week
);
3849 // test DST calculations
3850 static void TestTimeDST()
3852 puts("\n*** wxDateTime DST test ***");
3854 printf("DST is%s in effect now.\n\n",
3855 wxDateTime::Now().IsDST() ? "" : " not");
3857 // taken from http://www.energy.ca.gov/daylightsaving.html
3858 static const Date datesDST
[2][2004 - 1900 + 1] =
3861 { 1, wxDateTime::Apr
, 1990 },
3862 { 7, wxDateTime::Apr
, 1991 },
3863 { 5, wxDateTime::Apr
, 1992 },
3864 { 4, wxDateTime::Apr
, 1993 },
3865 { 3, wxDateTime::Apr
, 1994 },
3866 { 2, wxDateTime::Apr
, 1995 },
3867 { 7, wxDateTime::Apr
, 1996 },
3868 { 6, wxDateTime::Apr
, 1997 },
3869 { 5, wxDateTime::Apr
, 1998 },
3870 { 4, wxDateTime::Apr
, 1999 },
3871 { 2, wxDateTime::Apr
, 2000 },
3872 { 1, wxDateTime::Apr
, 2001 },
3873 { 7, wxDateTime::Apr
, 2002 },
3874 { 6, wxDateTime::Apr
, 2003 },
3875 { 4, wxDateTime::Apr
, 2004 },
3878 { 28, wxDateTime::Oct
, 1990 },
3879 { 27, wxDateTime::Oct
, 1991 },
3880 { 25, wxDateTime::Oct
, 1992 },
3881 { 31, wxDateTime::Oct
, 1993 },
3882 { 30, wxDateTime::Oct
, 1994 },
3883 { 29, wxDateTime::Oct
, 1995 },
3884 { 27, wxDateTime::Oct
, 1996 },
3885 { 26, wxDateTime::Oct
, 1997 },
3886 { 25, wxDateTime::Oct
, 1998 },
3887 { 31, wxDateTime::Oct
, 1999 },
3888 { 29, wxDateTime::Oct
, 2000 },
3889 { 28, wxDateTime::Oct
, 2001 },
3890 { 27, wxDateTime::Oct
, 2002 },
3891 { 26, wxDateTime::Oct
, 2003 },
3892 { 31, wxDateTime::Oct
, 2004 },
3897 for ( year
= 1990; year
< 2005; year
++ )
3899 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3900 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3902 printf("DST period in the US for year %d: from %s to %s",
3903 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3905 size_t n
= year
- 1990;
3906 const Date
& dBegin
= datesDST
[0][n
];
3907 const Date
& dEnd
= datesDST
[1][n
];
3909 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3915 printf(" (ERROR: should be %s %d to %s %d)\n",
3916 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3917 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3923 for ( year
= 1990; year
< 2005; year
++ )
3925 printf("DST period in Europe for year %d: from %s to %s\n",
3927 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3928 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3932 // test wxDateTime -> text conversion
3933 static void TestTimeFormat()
3935 puts("\n*** wxDateTime formatting test ***");
3937 // some information may be lost during conversion, so store what kind
3938 // of info should we recover after a round trip
3941 CompareNone
, // don't try comparing
3942 CompareBoth
, // dates and times should be identical
3943 CompareDate
, // dates only
3944 CompareTime
// time only
3949 CompareKind compareKind
;
3951 } formatTestFormats
[] =
3953 { CompareBoth
, "---> %c" },
3954 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3955 { CompareBoth
, "Date is %x, time is %X" },
3956 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3957 { CompareNone
, "The day of year: %j, the week of year: %W" },
3958 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3961 static const Date formatTestDates
[] =
3963 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3964 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3966 // this test can't work for other centuries because it uses two digit
3967 // years in formats, so don't even try it
3968 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3969 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3970 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3974 // an extra test (as it doesn't depend on date, don't do it in the loop)
3975 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3977 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3981 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3982 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3984 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3985 printf("%s", s
.c_str());
3987 // what can we recover?
3988 int kind
= formatTestFormats
[n
].compareKind
;
3992 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3995 // converion failed - should it have?
3996 if ( kind
== CompareNone
)
3999 puts(" (ERROR: conversion back failed)");
4003 // should have parsed the entire string
4004 puts(" (ERROR: conversion back stopped too soon)");
4008 bool equal
= FALSE
; // suppress compilaer warning
4016 equal
= dt
.IsSameDate(dt2
);
4020 equal
= dt
.IsSameTime(dt2
);
4026 printf(" (ERROR: got back '%s' instead of '%s')\n",
4027 dt2
.Format().c_str(), dt
.Format().c_str());
4038 // test text -> wxDateTime conversion
4039 static void TestTimeParse()
4041 puts("\n*** wxDateTime parse test ***");
4043 struct ParseTestData
4050 static const ParseTestData parseTestDates
[] =
4052 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4053 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4056 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4058 const char *format
= parseTestDates
[n
].format
;
4060 printf("%s => ", format
);
4063 if ( dt
.ParseRfc822Date(format
) )
4065 printf("%s ", dt
.Format().c_str());
4067 if ( parseTestDates
[n
].good
)
4069 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4076 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4081 puts("(ERROR: bad format)");
4086 printf("bad format (%s)\n",
4087 parseTestDates
[n
].good
? "ERROR" : "ok");
4092 static void TestDateTimeInteractive()
4094 puts("\n*** interactive wxDateTime tests ***");
4100 printf("Enter a date: ");
4101 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4104 // kill the last '\n'
4105 buf
[strlen(buf
) - 1] = 0;
4108 const char *p
= dt
.ParseDate(buf
);
4111 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4117 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4120 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4121 dt
.Format("%b %d, %Y").c_str(),
4123 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4124 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4125 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4128 puts("\n*** done ***");
4131 static void TestTimeMS()
4133 puts("*** testing millisecond-resolution support in wxDateTime ***");
4135 wxDateTime dt1
= wxDateTime::Now(),
4136 dt2
= wxDateTime::UNow();
4138 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4139 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4140 printf("Dummy loop: ");
4141 for ( int i
= 0; i
< 6000; i
++ )
4143 //for ( int j = 0; j < 10; j++ )
4146 s
.Printf("%g", sqrt(i
));
4155 dt2
= wxDateTime::UNow();
4156 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4158 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4160 puts("\n*** done ***");
4163 static void TestTimeArithmetics()
4165 puts("\n*** testing arithmetic operations on wxDateTime ***");
4167 static const struct ArithmData
4169 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4170 : span(sp
), name(nam
) { }
4174 } testArithmData
[] =
4176 ArithmData(wxDateSpan::Day(), "day"),
4177 ArithmData(wxDateSpan::Week(), "week"),
4178 ArithmData(wxDateSpan::Month(), "month"),
4179 ArithmData(wxDateSpan::Year(), "year"),
4180 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4183 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4185 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4187 wxDateSpan span
= testArithmData
[n
].span
;
4191 const char *name
= testArithmData
[n
].name
;
4192 printf("%s + %s = %s, %s - %s = %s\n",
4193 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4194 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4196 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4197 if ( dt1
- span
== dt
)
4203 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4206 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4207 if ( dt2
+ span
== dt
)
4213 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4216 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4217 if ( dt2
+ 2*span
== dt1
)
4223 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4230 static void TestTimeHolidays()
4232 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4234 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4235 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4236 dtEnd
= dtStart
.GetLastMonthDay();
4238 wxDateTimeArray hol
;
4239 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4241 const wxChar
*format
= "%d-%b-%Y (%a)";
4243 printf("All holidays between %s and %s:\n",
4244 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4246 size_t count
= hol
.GetCount();
4247 for ( size_t n
= 0; n
< count
; n
++ )
4249 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4255 static void TestTimeZoneBug()
4257 puts("\n*** testing for DST/timezone bug ***\n");
4259 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4260 for ( int i
= 0; i
< 31; i
++ )
4262 printf("Date %s: week day %s.\n",
4263 date
.Format(_T("%d-%m-%Y")).c_str(),
4264 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4266 date
+= wxDateSpan::Day();
4272 static void TestTimeSpanFormat()
4274 puts("\n*** wxTimeSpan tests ***");
4276 static const char *formats
[] =
4278 _T("(default) %H:%M:%S"),
4279 _T("%E weeks and %D days"),
4280 _T("%l milliseconds"),
4281 _T("(with ms) %H:%M:%S:%l"),
4282 _T("100%% of minutes is %M"), // test "%%"
4283 _T("%D days and %H hours"),
4284 _T("or also %S seconds"),
4287 wxTimeSpan
ts1(1, 2, 3, 4),
4289 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4291 printf("ts1 = %s\tts2 = %s\n",
4292 ts1
.Format(formats
[n
]).c_str(),
4293 ts2
.Format(formats
[n
]).c_str());
4301 // test compatibility with the old wxDate/wxTime classes
4302 static void TestTimeCompatibility()
4304 puts("\n*** wxDateTime compatibility test ***");
4306 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4307 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4309 double jdnNow
= wxDateTime::Now().GetJDN();
4310 long jdnMidnight
= (long)(jdnNow
- 0.5);
4311 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4313 jdnMidnight
= wxDate().Set().GetJulianDate();
4314 printf("wxDateTime for today: %s\n",
4315 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4317 int flags
= wxEUROPEAN
;//wxFULL;
4320 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4321 for ( int n
= 0; n
< 7; n
++ )
4323 printf("Previous %s is %s\n",
4324 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4325 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4331 #endif // TEST_DATETIME
4333 // ----------------------------------------------------------------------------
4335 // ----------------------------------------------------------------------------
4339 #include "wx/thread.h"
4341 static size_t gs_counter
= (size_t)-1;
4342 static wxCriticalSection gs_critsect
;
4343 static wxCondition gs_cond
;
4345 class MyJoinableThread
: public wxThread
4348 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4349 { m_n
= n
; Create(); }
4351 // thread execution starts here
4352 virtual ExitCode
Entry();
4358 wxThread::ExitCode
MyJoinableThread::Entry()
4360 unsigned long res
= 1;
4361 for ( size_t n
= 1; n
< m_n
; n
++ )
4365 // it's a loooong calculation :-)
4369 return (ExitCode
)res
;
4372 class MyDetachedThread
: public wxThread
4375 MyDetachedThread(size_t n
, char ch
)
4379 m_cancelled
= FALSE
;
4384 // thread execution starts here
4385 virtual ExitCode
Entry();
4388 virtual void OnExit();
4391 size_t m_n
; // number of characters to write
4392 char m_ch
; // character to write
4394 bool m_cancelled
; // FALSE if we exit normally
4397 wxThread::ExitCode
MyDetachedThread::Entry()
4400 wxCriticalSectionLocker
lock(gs_critsect
);
4401 if ( gs_counter
== (size_t)-1 )
4407 for ( size_t n
= 0; n
< m_n
; n
++ )
4409 if ( TestDestroy() )
4419 wxThread::Sleep(100);
4425 void MyDetachedThread::OnExit()
4427 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4429 wxCriticalSectionLocker
lock(gs_critsect
);
4430 if ( !--gs_counter
&& !m_cancelled
)
4434 void TestDetachedThreads()
4436 puts("\n*** Testing detached threads ***");
4438 static const size_t nThreads
= 3;
4439 MyDetachedThread
*threads
[nThreads
];
4441 for ( n
= 0; n
< nThreads
; n
++ )
4443 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4446 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4447 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4449 for ( n
= 0; n
< nThreads
; n
++ )
4454 // wait until all threads terminate
4460 void TestJoinableThreads()
4462 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4464 // calc 10! in the background
4465 MyJoinableThread
thread(10);
4468 printf("\nThread terminated with exit code %lu.\n",
4469 (unsigned long)thread
.Wait());
4472 void TestThreadSuspend()
4474 puts("\n*** Testing thread suspend/resume functions ***");
4476 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4480 // this is for this demo only, in a real life program we'd use another
4481 // condition variable which would be signaled from wxThread::Entry() to
4482 // tell us that the thread really started running - but here just wait a
4483 // bit and hope that it will be enough (the problem is, of course, that
4484 // the thread might still not run when we call Pause() which will result
4486 wxThread::Sleep(300);
4488 for ( size_t n
= 0; n
< 3; n
++ )
4492 puts("\nThread suspended");
4495 // don't sleep but resume immediately the first time
4496 wxThread::Sleep(300);
4498 puts("Going to resume the thread");
4503 puts("Waiting until it terminates now");
4505 // wait until the thread terminates
4511 void TestThreadDelete()
4513 // As above, using Sleep() is only for testing here - we must use some
4514 // synchronisation object instead to ensure that the thread is still
4515 // running when we delete it - deleting a detached thread which already
4516 // terminated will lead to a crash!
4518 puts("\n*** Testing thread delete function ***");
4520 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4524 puts("\nDeleted a thread which didn't start to run yet.");
4526 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4530 wxThread::Sleep(300);
4534 puts("\nDeleted a running thread.");
4536 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4540 wxThread::Sleep(300);
4546 puts("\nDeleted a sleeping thread.");
4548 MyJoinableThread
thread3(20);
4553 puts("\nDeleted a joinable thread.");
4555 MyJoinableThread
thread4(2);
4558 wxThread::Sleep(300);
4562 puts("\nDeleted a joinable thread which already terminated.");
4567 #endif // TEST_THREADS
4569 // ----------------------------------------------------------------------------
4571 // ----------------------------------------------------------------------------
4575 static void PrintArray(const char* name
, const wxArrayString
& array
)
4577 printf("Dump of the array '%s'\n", name
);
4579 size_t nCount
= array
.GetCount();
4580 for ( size_t n
= 0; n
< nCount
; n
++ )
4582 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4586 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4588 printf("Dump of the array '%s'\n", name
);
4590 size_t nCount
= array
.GetCount();
4591 for ( size_t n
= 0; n
< nCount
; n
++ )
4593 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4597 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4598 const wxString
& second
)
4600 return first
.length() - second
.length();
4603 int wxCMPFUNC_CONV
IntCompare(int *first
,
4606 return *first
- *second
;
4609 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4612 return *second
- *first
;
4615 static void TestArrayOfInts()
4617 puts("*** Testing wxArrayInt ***\n");
4628 puts("After sort:");
4632 puts("After reverse sort:");
4633 a
.Sort(IntRevCompare
);
4637 #include "wx/dynarray.h"
4639 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4640 #include "wx/arrimpl.cpp"
4641 WX_DEFINE_OBJARRAY(ArrayBars
);
4643 static void TestArrayOfObjects()
4645 puts("*** Testing wxObjArray ***\n");
4649 Bar
bar("second bar");
4651 printf("Initially: %u objects in the array, %u objects total.\n",
4652 bars
.GetCount(), Bar::GetNumber());
4654 bars
.Add(new Bar("first bar"));
4657 printf("Now: %u objects in the array, %u objects total.\n",
4658 bars
.GetCount(), Bar::GetNumber());
4662 printf("After Empty(): %u objects in the array, %u objects total.\n",
4663 bars
.GetCount(), Bar::GetNumber());
4666 printf("Finally: no more objects in the array, %u objects total.\n",
4670 #endif // TEST_ARRAYS
4672 // ----------------------------------------------------------------------------
4674 // ----------------------------------------------------------------------------
4678 #include "wx/timer.h"
4679 #include "wx/tokenzr.h"
4681 static void TestStringConstruction()
4683 puts("*** Testing wxString constructores ***");
4685 #define TEST_CTOR(args, res) \
4688 printf("wxString%s = %s ", #args, s.c_str()); \
4695 printf("(ERROR: should be %s)\n", res); \
4699 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4700 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4701 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4702 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4704 static const wxChar
*s
= _T("?really!");
4705 const wxChar
*start
= wxStrchr(s
, _T('r'));
4706 const wxChar
*end
= wxStrchr(s
, _T('!'));
4707 TEST_CTOR((start
, end
), _T("really"));
4712 static void TestString()
4722 for (int i
= 0; i
< 1000000; ++i
)
4726 c
= "! How'ya doin'?";
4729 c
= "Hello world! What's up?";
4734 printf ("TestString elapsed time: %ld\n", sw
.Time());
4737 static void TestPChar()
4745 for (int i
= 0; i
< 1000000; ++i
)
4747 strcpy (a
, "Hello");
4748 strcpy (b
, " world");
4749 strcpy (c
, "! How'ya doin'?");
4752 strcpy (c
, "Hello world! What's up?");
4753 if (strcmp (c
, a
) == 0)
4757 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4760 static void TestStringSub()
4762 wxString
s("Hello, world!");
4764 puts("*** Testing wxString substring extraction ***");
4766 printf("String = '%s'\n", s
.c_str());
4767 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4768 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4769 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4770 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4771 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4772 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4774 static const wxChar
*prefixes
[] =
4778 _T("Hello, world!"),
4779 _T("Hello, world!!!"),
4785 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4787 wxString prefix
= prefixes
[n
], rest
;
4788 bool rc
= s
.StartsWith(prefix
, &rest
);
4789 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4792 printf(" (the rest is '%s')\n", rest
.c_str());
4803 static void TestStringFormat()
4805 puts("*** Testing wxString formatting ***");
4808 s
.Printf("%03d", 18);
4810 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4811 printf("Number 18: %s\n", s
.c_str());
4816 // returns "not found" for npos, value for all others
4817 static wxString
PosToString(size_t res
)
4819 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4820 : wxString::Format(_T("%u"), res
);
4824 static void TestStringFind()
4826 puts("*** Testing wxString find() functions ***");
4828 static const wxChar
*strToFind
= _T("ell");
4829 static const struct StringFindTest
4833 result
; // of searching "ell" in str
4836 { _T("Well, hello world"), 0, 1 },
4837 { _T("Well, hello world"), 6, 7 },
4838 { _T("Well, hello world"), 9, wxString::npos
},
4841 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4843 const StringFindTest
& ft
= findTestData
[n
];
4844 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4846 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4847 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4849 size_t resTrue
= ft
.result
;
4850 if ( res
== resTrue
)
4856 printf(_T("(ERROR: should be %s)\n"),
4857 PosToString(resTrue
).c_str());
4864 static void TestStringTokenizer()
4866 puts("*** Testing wxStringTokenizer ***");
4868 static const wxChar
*modeNames
[] =
4872 _T("return all empty"),
4877 static const struct StringTokenizerTest
4879 const wxChar
*str
; // string to tokenize
4880 const wxChar
*delims
; // delimiters to use
4881 size_t count
; // count of token
4882 wxStringTokenizerMode mode
; // how should we tokenize it
4883 } tokenizerTestData
[] =
4885 { _T(""), _T(" "), 0 },
4886 { _T("Hello, world"), _T(" "), 2 },
4887 { _T("Hello, world "), _T(" "), 2 },
4888 { _T("Hello, world"), _T(","), 2 },
4889 { _T("Hello, world!"), _T(",!"), 2 },
4890 { _T("Hello,, world!"), _T(",!"), 3 },
4891 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4892 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4893 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4894 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4895 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4896 { _T("01/02/99"), _T("/-"), 3 },
4897 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4900 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4902 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4903 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4905 size_t count
= tkz
.CountTokens();
4906 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4907 MakePrintable(tt
.str
).c_str(),
4909 MakePrintable(tt
.delims
).c_str(),
4910 modeNames
[tkz
.GetMode()]);
4911 if ( count
== tt
.count
)
4917 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4922 // if we emulate strtok(), check that we do it correctly
4923 wxChar
*buf
, *s
= NULL
, *last
;
4925 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4927 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4928 wxStrcpy(buf
, tt
.str
);
4930 s
= wxStrtok(buf
, tt
.delims
, &last
);
4937 // now show the tokens themselves
4939 while ( tkz
.HasMoreTokens() )
4941 wxString token
= tkz
.GetNextToken();
4943 printf(_T("\ttoken %u: '%s'"),
4945 MakePrintable(token
).c_str());
4955 printf(" (ERROR: should be %s)\n", s
);
4958 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4962 // nothing to compare with
4967 if ( count2
!= count
)
4969 puts(_T("\tERROR: token count mismatch"));
4978 static void TestStringReplace()
4980 puts("*** Testing wxString::replace ***");
4982 static const struct StringReplaceTestData
4984 const wxChar
*original
; // original test string
4985 size_t start
, len
; // the part to replace
4986 const wxChar
*replacement
; // the replacement string
4987 const wxChar
*result
; // and the expected result
4988 } stringReplaceTestData
[] =
4990 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4991 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4992 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4993 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4994 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4997 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4999 const StringReplaceTestData data
= stringReplaceTestData
[n
];
5001 wxString original
= data
.original
;
5002 original
.replace(data
.start
, data
.len
, data
.replacement
);
5004 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
5005 data
.original
, data
.start
, data
.len
, data
.replacement
,
5008 if ( original
== data
.result
)
5014 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
5021 static void TestStringMatch()
5023 wxPuts(_T("*** Testing wxString::Matches() ***"));
5025 static const struct StringMatchTestData
5028 const wxChar
*wildcard
;
5030 } stringMatchTestData
[] =
5032 { _T("foobar"), _T("foo*"), 1 },
5033 { _T("foobar"), _T("*oo*"), 1 },
5034 { _T("foobar"), _T("*bar"), 1 },
5035 { _T("foobar"), _T("??????"), 1 },
5036 { _T("foobar"), _T("f??b*"), 1 },
5037 { _T("foobar"), _T("f?b*"), 0 },
5038 { _T("foobar"), _T("*goo*"), 0 },
5039 { _T("foobar"), _T("*foo"), 0 },
5040 { _T("foobarfoo"), _T("*foo"), 1 },
5041 { _T(""), _T("*"), 1 },
5042 { _T(""), _T("?"), 0 },
5045 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
5047 const StringMatchTestData
& data
= stringMatchTestData
[n
];
5048 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
5049 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
5051 matches
? _T("matches") : _T("doesn't match"),
5053 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5059 #endif // TEST_STRINGS
5061 // ----------------------------------------------------------------------------
5063 // ----------------------------------------------------------------------------
5065 int main(int argc
, char **argv
)
5067 wxInitializer initializer
;
5070 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5075 #ifdef TEST_SNGLINST
5076 wxSingleInstanceChecker checker
;
5077 if ( checker
.Create(_T(".wxconsole.lock")) )
5079 if ( checker
.IsAnotherRunning() )
5081 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5086 // wait some time to give time to launch another instance
5087 wxPrintf(_T("Press \"Enter\" to continue..."));
5090 else // failed to create
5092 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5094 #endif // TEST_SNGLINST
5098 #endif // TEST_CHARSET
5101 TestCmdLineConvert();
5103 #if wxUSE_CMDLINE_PARSER
5104 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5106 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5107 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5108 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5109 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5111 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5112 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5113 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5114 wxCMD_LINE_VAL_NUMBER
},
5115 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5116 wxCMD_LINE_VAL_DATE
},
5118 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5119 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5124 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5126 parser
.AddOption("project_name", "", "full path to project file",
5127 wxCMD_LINE_VAL_STRING
,
5128 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5130 switch ( parser
.Parse() )
5133 wxLogMessage("Help was given, terminating.");
5137 ShowCmdLine(parser
);
5141 wxLogMessage("Syntax error detected, aborting.");
5144 #endif // wxUSE_CMDLINE_PARSER
5146 #endif // TEST_CMDLINE
5154 TestStringConstruction();
5157 TestStringTokenizer();
5158 TestStringReplace();
5161 #endif // TEST_STRINGS
5174 puts("*** Initially:");
5176 PrintArray("a1", a1
);
5178 wxArrayString
a2(a1
);
5179 PrintArray("a2", a2
);
5181 wxSortedArrayString
a3(a1
);
5182 PrintArray("a3", a3
);
5184 puts("*** After deleting a string from a1");
5187 PrintArray("a1", a1
);
5188 PrintArray("a2", a2
);
5189 PrintArray("a3", a3
);
5191 puts("*** After reassigning a1 to a2 and a3");
5193 PrintArray("a2", a2
);
5194 PrintArray("a3", a3
);
5196 puts("*** After sorting a1");
5198 PrintArray("a1", a1
);
5200 puts("*** After sorting a1 in reverse order");
5202 PrintArray("a1", a1
);
5204 puts("*** After sorting a1 by the string length");
5205 a1
.Sort(StringLenCompare
);
5206 PrintArray("a1", a1
);
5208 TestArrayOfObjects();
5211 #endif // TEST_ARRAYS
5219 #ifdef TEST_DLLLOADER
5221 #endif // TEST_DLLLOADER
5225 #endif // TEST_ENVIRON
5229 #endif // TEST_EXECUTE
5231 #ifdef TEST_FILECONF
5233 #endif // TEST_FILECONF
5241 #endif // TEST_LOCALE
5245 for ( size_t n
= 0; n
< 8000; n
++ )
5247 s
<< (char)('A' + (n
% 26));
5251 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5253 // this one shouldn't be truncated
5256 // but this one will because log functions use fixed size buffer
5257 // (note that it doesn't need '\n' at the end neither - will be added
5259 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5271 #ifdef TEST_FILENAME
5275 fn
.Assign("c:\\foo", "bar.baz");
5280 TestFileNameMakeRelative();
5283 TestFileNameConstruction();
5284 TestFileNameSplit();
5287 TestFileNameComparison();
5288 TestFileNameOperations();
5290 #endif // TEST_FILENAME
5292 #ifdef TEST_FILETIME
5295 #endif // TEST_FILETIME
5298 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5299 if ( TestFtpConnect() )
5310 TestFtpInteractive();
5312 //else: connecting to the FTP server failed
5319 int nCPUs
= wxThread::GetCPUCount();
5320 printf("This system has %d CPUs\n", nCPUs
);
5322 wxThread::SetConcurrency(nCPUs
);
5324 if ( argc
> 1 && argv
[1][0] == 't' )
5325 wxLog::AddTraceMask("thread");
5328 TestDetachedThreads();
5330 TestJoinableThreads();
5332 TestThreadSuspend();
5336 #endif // TEST_THREADS
5338 #ifdef TEST_LONGLONG
5339 // seed pseudo random generator
5340 srand((unsigned)time(NULL
));
5348 TestMultiplication();
5351 TestLongLongConversion();
5352 TestBitOperations();
5353 TestLongLongComparison();
5355 TestLongLongPrint();
5356 #endif // TEST_LONGLONG
5363 wxLog::AddTraceMask(_T("mime"));
5371 TestMimeAssociate();
5374 #ifdef TEST_INFO_FUNCTIONS
5381 #endif // TEST_INFO_FUNCTIONS
5383 #ifdef TEST_PATHLIST
5385 #endif // TEST_PATHLIST
5389 #endif // TEST_REGCONF
5392 // TODO: write a real test using src/regex/tests file
5397 TestRegExSubmatch();
5398 TestRegExInteractive();
5400 TestRegExReplacement();
5401 #endif // TEST_REGEX
5403 #ifdef TEST_REGISTRY
5406 TestRegistryAssociation();
5407 #endif // TEST_REGISTRY
5415 #endif // TEST_SOCKETS
5421 #endif // TEST_STREAMS
5425 #endif // TEST_TIMER
5427 #ifdef TEST_DATETIME
5440 TestTimeArithmetics();
5447 TestTimeSpanFormat();
5449 TestDateTimeInteractive();
5450 #endif // TEST_DATETIME
5453 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5455 #endif // TEST_USLEEP
5461 #endif // TEST_VCARD
5465 #endif // TEST_WCHAR
5469 TestZipStreamRead();
5470 TestZipFileSystem();
5475 TestZlibStreamWrite();
5476 TestZlibStreamRead();