1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWidgets
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
24 #include "wx/string.h"
29 // without this pragma, the stupid compiler precompiles #defines below so that
30 // changing them doesn't "take place" later!
35 // ----------------------------------------------------------------------------
36 // conditional compilation
37 // ----------------------------------------------------------------------------
40 A note about all these conditional compilation macros: this file is used
41 both as a test suite for various non-GUI wxWidgets classes and as a
42 scratchpad for quick tests. So there are two compilation modes: if you
43 define TEST_ALL all tests are run, otherwise you may enable the individual
44 tests individually in the "#else" branch below.
47 // what to test (in alphabetic order)? Define TEST_ALL to 0 to do a single
48 // test, define it to 1 to do all tests.
56 #define TEST_DLLLOADER
63 // #define TEST_FTP --FIXME! (RN)
64 #define TEST_INFO_FUNCTIONS
74 #define TEST_SCOPEGUARD
76 // #define TEST_SOCKETS --FIXME! (RN)
79 #define TEST_TEXTSTREAM
82 // #define TEST_VCARD -- don't enable this (VZ)
83 // #define TEST_VOLUME --FIXME! (RN)
90 // some tests are interactive, define this to run them
91 #ifdef TEST_INTERACTIVE
92 #undef TEST_INTERACTIVE
94 #define TEST_INTERACTIVE 1
96 #define TEST_INTERACTIVE 0
99 // ============================================================================
101 // ============================================================================
103 // ----------------------------------------------------------------------------
105 // ----------------------------------------------------------------------------
107 #if defined(TEST_SOCKETS)
109 // replace TABs with \t and CRs with \n
110 static wxString
MakePrintable(const wxChar
*s
)
113 (void)str
.Replace(_T("\t"), _T("\\t"));
114 (void)str
.Replace(_T("\n"), _T("\\n"));
115 (void)str
.Replace(_T("\r"), _T("\\r"));
120 #endif // MakePrintable() is used
122 // ----------------------------------------------------------------------------
124 // ----------------------------------------------------------------------------
128 #include "wx/cmdline.h"
129 #include "wx/datetime.h"
131 #if wxUSE_CMDLINE_PARSER
133 static void ShowCmdLine(const wxCmdLineParser
& parser
)
135 wxString s
= _T("Input files: ");
137 size_t count
= parser
.GetParamCount();
138 for ( size_t param
= 0; param
< count
; param
++ )
140 s
<< parser
.GetParam(param
) << ' ';
144 << _T("Verbose:\t") << (parser
.Found(_T("v")) ? _T("yes") : _T("no")) << '\n'
145 << _T("Quiet:\t") << (parser
.Found(_T("q")) ? _T("yes") : _T("no")) << '\n';
150 if ( parser
.Found(_T("o"), &strVal
) )
151 s
<< _T("Output file:\t") << strVal
<< '\n';
152 if ( parser
.Found(_T("i"), &strVal
) )
153 s
<< _T("Input dir:\t") << strVal
<< '\n';
154 if ( parser
.Found(_T("s"), &lVal
) )
155 s
<< _T("Size:\t") << lVal
<< '\n';
156 if ( parser
.Found(_T("d"), &dt
) )
157 s
<< _T("Date:\t") << dt
.FormatISODate() << '\n';
158 if ( parser
.Found(_T("project_name"), &strVal
) )
159 s
<< _T("Project:\t") << strVal
<< '\n';
164 #endif // wxUSE_CMDLINE_PARSER
166 static void TestCmdLineConvert()
168 static const wxChar
*cmdlines
[] =
171 _T("-a \"-bstring 1\" -c\"string 2\" \"string 3\""),
172 _T("literal \\\" and \"\""),
175 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
177 const wxChar
*cmdline
= cmdlines
[n
];
178 wxPrintf(_T("Parsing: %s\n"), cmdline
);
179 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
181 size_t count
= args
.GetCount();
182 wxPrintf(_T("\targc = %u\n"), count
);
183 for ( size_t arg
= 0; arg
< count
; arg
++ )
185 wxPrintf(_T("\targv[%u] = %s\n"), arg
, args
[arg
].c_str());
190 #endif // TEST_CMDLINE
192 // ----------------------------------------------------------------------------
194 // ----------------------------------------------------------------------------
201 static const wxChar
*ROOTDIR
= _T("/");
202 static const wxChar
*TESTDIR
= _T("/usr/local/share");
203 #elif defined(__WXMSW__)
204 static const wxChar
*ROOTDIR
= _T("c:\\");
205 static const wxChar
*TESTDIR
= _T("d:\\");
207 #error "don't know where the root directory is"
210 static void TestDirEnumHelper(wxDir
& dir
,
211 int flags
= wxDIR_DEFAULT
,
212 const wxString
& filespec
= wxEmptyString
)
216 if ( !dir
.IsOpened() )
219 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
222 wxPrintf(_T("\t%s\n"), filename
.c_str());
224 cont
= dir
.GetNext(&filename
);
227 wxPuts(wxEmptyString
);
230 static void TestDirEnum()
232 wxPuts(_T("*** Testing wxDir::GetFirst/GetNext ***"));
234 wxString cwd
= wxGetCwd();
235 if ( !wxDir::Exists(cwd
) )
237 wxPrintf(_T("ERROR: current directory '%s' doesn't exist?\n"), cwd
.c_str());
242 if ( !dir
.IsOpened() )
244 wxPrintf(_T("ERROR: failed to open current directory '%s'.\n"), cwd
.c_str());
248 wxPuts(_T("Enumerating everything in current directory:"));
249 TestDirEnumHelper(dir
);
251 wxPuts(_T("Enumerating really everything in current directory:"));
252 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
254 wxPuts(_T("Enumerating object files in current directory:"));
255 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, _T("*.o*"));
257 wxPuts(_T("Enumerating directories in current directory:"));
258 TestDirEnumHelper(dir
, wxDIR_DIRS
);
260 wxPuts(_T("Enumerating files in current directory:"));
261 TestDirEnumHelper(dir
, wxDIR_FILES
);
263 wxPuts(_T("Enumerating files including hidden in current directory:"));
264 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
268 wxPuts(_T("Enumerating everything in root directory:"));
269 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
271 wxPuts(_T("Enumerating directories in root directory:"));
272 TestDirEnumHelper(dir
, wxDIR_DIRS
);
274 wxPuts(_T("Enumerating files in root directory:"));
275 TestDirEnumHelper(dir
, wxDIR_FILES
);
277 wxPuts(_T("Enumerating files including hidden in root directory:"));
278 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
280 wxPuts(_T("Enumerating files in non existing directory:"));
281 wxDir
dirNo(_T("nosuchdir"));
282 TestDirEnumHelper(dirNo
);
285 class DirPrintTraverser
: public wxDirTraverser
288 virtual wxDirTraverseResult
OnFile(const wxString
& WXUNUSED(filename
))
290 return wxDIR_CONTINUE
;
293 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
295 wxString path
, name
, ext
;
296 wxSplitPath(dirname
, &path
, &name
, &ext
);
299 name
<< _T('.') << ext
;
302 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
304 if ( wxIsPathSeparator(*p
) )
308 wxPrintf(_T("%s%s\n"), indent
.c_str(), name
.c_str());
310 return wxDIR_CONTINUE
;
314 static void TestDirTraverse()
316 wxPuts(_T("*** Testing wxDir::Traverse() ***"));
320 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
321 wxPrintf(_T("There are %u files under '%s'\n"), n
, TESTDIR
);
324 wxPrintf(_T("First one is '%s'\n"), files
[0u].c_str());
325 wxPrintf(_T(" last one is '%s'\n"), files
[n
- 1].c_str());
328 // enum again with custom traverser
329 wxPuts(_T("Now enumerating directories:"));
331 DirPrintTraverser traverser
;
332 dir
.Traverse(traverser
, wxEmptyString
, wxDIR_DIRS
| wxDIR_HIDDEN
);
335 static void TestDirExists()
337 wxPuts(_T("*** Testing wxDir::Exists() ***"));
339 static const wxChar
*dirnames
[] =
342 #if defined(__WXMSW__)
345 _T("\\\\share\\file"),
349 _T("c:\\autoexec.bat"),
350 #elif defined(__UNIX__)
359 for ( size_t n
= 0; n
< WXSIZEOF(dirnames
); n
++ )
361 wxPrintf(_T("%-40s: %s\n"),
363 wxDir::Exists(dirnames
[n
]) ? _T("exists")
364 : _T("doesn't exist"));
370 // ----------------------------------------------------------------------------
372 // ----------------------------------------------------------------------------
374 #ifdef TEST_DLLLOADER
376 #include "wx/dynlib.h"
378 static void TestDllLoad()
380 #if defined(__WXMSW__)
381 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
382 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
383 #elif defined(__UNIX__)
384 // weird: using just libc.so does *not* work!
385 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
386 static const wxChar
*FUNC_NAME
= _T("strlen");
388 #error "don't know how to test wxDllLoader on this platform"
391 wxPuts(_T("*** testing wxDllLoader ***\n"));
393 wxDynamicLibrary
lib(LIB_NAME
);
394 if ( !lib
.IsLoaded() )
396 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
400 typedef int (*wxStrlenType
)(const char *);
401 wxStrlenType pfnStrlen
= (wxStrlenType
)lib
.GetSymbol(FUNC_NAME
);
404 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
405 FUNC_NAME
, LIB_NAME
);
409 if ( pfnStrlen("foo") != 3 )
411 wxPrintf(_T("ERROR: loaded function is not wxStrlen()!\n"));
415 wxPuts(_T("... ok"));
421 #endif // TEST_DLLLOADER
423 // ----------------------------------------------------------------------------
425 // ----------------------------------------------------------------------------
429 #include "wx/utils.h"
431 static wxString
MyGetEnv(const wxString
& var
)
434 if ( !wxGetEnv(var
, &val
) )
437 val
= wxString(_T('\'')) + val
+ _T('\'');
442 static void TestEnvironment()
444 const wxChar
*var
= _T("wxTestVar");
446 wxPuts(_T("*** testing environment access functions ***"));
448 wxPrintf(_T("Initially getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
449 wxSetEnv(var
, _T("value for wxTestVar"));
450 wxPrintf(_T("After wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
451 wxSetEnv(var
, _T("another value"));
452 wxPrintf(_T("After 2nd wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
454 wxPrintf(_T("After wxUnsetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
455 wxPrintf(_T("PATH = %s\n"), MyGetEnv(_T("PATH")).c_str());
458 #endif // TEST_ENVIRON
460 // ----------------------------------------------------------------------------
462 // ----------------------------------------------------------------------------
466 #include "wx/utils.h"
468 static void TestExecute()
470 wxPuts(_T("*** testing wxExecute ***"));
473 #define COMMAND "cat -n ../../Makefile" // "echo hi"
474 #define SHELL_COMMAND "echo hi from shell"
475 #define REDIRECT_COMMAND COMMAND // "date"
476 #elif defined(__WXMSW__)
477 #define COMMAND "command.com /c echo hi"
478 #define SHELL_COMMAND "echo hi"
479 #define REDIRECT_COMMAND COMMAND
481 #error "no command to exec"
484 wxPrintf(_T("Testing wxShell: "));
486 if ( wxShell(_T(SHELL_COMMAND
)) )
489 wxPuts(_T("ERROR."));
491 wxPrintf(_T("Testing wxExecute: "));
493 if ( wxExecute(_T(COMMAND
), true /* sync */) == 0 )
496 wxPuts(_T("ERROR."));
498 #if 0 // no, it doesn't work (yet?)
499 wxPrintf(_T("Testing async wxExecute: "));
501 if ( wxExecute(COMMAND
) != 0 )
502 wxPuts(_T("Ok (command launched)."));
504 wxPuts(_T("ERROR."));
507 wxPrintf(_T("Testing wxExecute with redirection:\n"));
508 wxArrayString output
;
509 if ( wxExecute(_T(REDIRECT_COMMAND
), output
) != 0 )
511 wxPuts(_T("ERROR."));
515 size_t count
= output
.GetCount();
516 for ( size_t n
= 0; n
< count
; n
++ )
518 wxPrintf(_T("\t%s\n"), output
[n
].c_str());
525 #endif // TEST_EXECUTE
527 // ----------------------------------------------------------------------------
529 // ----------------------------------------------------------------------------
534 #include "wx/ffile.h"
535 #include "wx/textfile.h"
537 static void TestFileRead()
539 wxPuts(_T("*** wxFile read test ***"));
541 wxFile
file(_T("testdata.fc"));
542 if ( file
.IsOpened() )
544 wxPrintf(_T("File length: %lu\n"), file
.Length());
546 wxPuts(_T("File dump:\n----------"));
548 static const size_t len
= 1024;
552 size_t nRead
= file
.Read(buf
, len
);
553 if ( nRead
== (size_t)wxInvalidOffset
)
555 wxPrintf(_T("Failed to read the file."));
559 fwrite(buf
, nRead
, 1, stdout
);
565 wxPuts(_T("----------"));
569 wxPrintf(_T("ERROR: can't open test file.\n"));
572 wxPuts(wxEmptyString
);
575 static void TestTextFileRead()
577 wxPuts(_T("*** wxTextFile read test ***"));
579 wxTextFile
file(_T("testdata.fc"));
582 wxPrintf(_T("Number of lines: %u\n"), file
.GetLineCount());
583 wxPrintf(_T("Last line: '%s'\n"), file
.GetLastLine().c_str());
587 wxPuts(_T("\nDumping the entire file:"));
588 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
590 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
592 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
594 wxPuts(_T("\nAnd now backwards:"));
595 for ( s
= file
.GetLastLine();
596 file
.GetCurrentLine() != 0;
597 s
= file
.GetPrevLine() )
599 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
601 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
605 wxPrintf(_T("ERROR: can't open '%s'\n"), file
.GetName());
608 wxPuts(wxEmptyString
);
611 static void TestFileCopy()
613 wxPuts(_T("*** Testing wxCopyFile ***"));
615 static const wxChar
*filename1
= _T("testdata.fc");
616 static const wxChar
*filename2
= _T("test2");
617 if ( !wxCopyFile(filename1
, filename2
) )
619 wxPuts(_T("ERROR: failed to copy file"));
623 wxFFile
f1(filename1
, _T("rb")),
624 f2(filename2
, _T("rb"));
626 if ( !f1
.IsOpened() || !f2
.IsOpened() )
628 wxPuts(_T("ERROR: failed to open file(s)"));
633 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
635 wxPuts(_T("ERROR: failed to read file(s)"));
639 if ( (s1
.length() != s2
.length()) ||
640 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
642 wxPuts(_T("ERROR: copy error!"));
646 wxPuts(_T("File was copied ok."));
652 if ( !wxRemoveFile(filename2
) )
654 wxPuts(_T("ERROR: failed to remove the file"));
657 wxPuts(wxEmptyString
);
662 // ----------------------------------------------------------------------------
664 // ----------------------------------------------------------------------------
668 #include "wx/confbase.h"
669 #include "wx/fileconf.h"
671 static const struct FileConfTestData
673 const wxChar
*name
; // value name
674 const wxChar
*value
; // the value from the file
677 { _T("value1"), _T("one") },
678 { _T("value2"), _T("two") },
679 { _T("novalue"), _T("default") },
682 static void TestFileConfRead()
684 wxPuts(_T("*** testing wxFileConfig loading/reading ***"));
686 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
687 _T("testdata.fc"), wxEmptyString
,
688 wxCONFIG_USE_RELATIVE_PATH
);
690 // test simple reading
691 wxPuts(_T("\nReading config file:"));
692 wxString
defValue(_T("default")), value
;
693 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
695 const FileConfTestData
& data
= fcTestData
[n
];
696 value
= fileconf
.Read(data
.name
, defValue
);
697 wxPrintf(_T("\t%s = %s "), data
.name
, value
.c_str());
698 if ( value
== data
.value
)
704 wxPrintf(_T("(ERROR: should be %s)\n"), data
.value
);
708 // test enumerating the entries
709 wxPuts(_T("\nEnumerating all root entries:"));
712 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
715 wxPrintf(_T("\t%s = %s\n"),
717 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
719 cont
= fileconf
.GetNextEntry(name
, dummy
);
722 static const wxChar
*testEntry
= _T("TestEntry");
723 wxPrintf(_T("\nTesting deletion of newly created \"Test\" entry: "));
724 fileconf
.Write(testEntry
, _T("A value"));
725 fileconf
.DeleteEntry(testEntry
);
726 wxPrintf(fileconf
.HasEntry(testEntry
) ? _T("ERROR\n") : _T("ok\n"));
729 #endif // TEST_FILECONF
731 // ----------------------------------------------------------------------------
733 // ----------------------------------------------------------------------------
737 #include "wx/filename.h"
740 static void DumpFileName(const wxChar
*desc
, const wxFileName
& fn
)
744 wxString full
= fn
.GetFullPath();
746 wxString vol
, path
, name
, ext
;
747 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
749 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
750 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
752 wxFileName::SplitPath(full
, &path
, &name
, &ext
);
753 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
754 path
.c_str(), name
.c_str(), ext
.c_str());
756 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
757 wxPrintf(_T("with volume: \t'%s'\n"),
758 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
759 wxPrintf(_T("with separator:\t'%s'\n"),
760 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
761 wxPrintf(_T("with both: \t'%s'\n"),
762 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
764 wxPuts(_T("The directories in the path are:"));
765 wxArrayString dirs
= fn
.GetDirs();
766 size_t count
= dirs
.GetCount();
767 for ( size_t n
= 0; n
< count
; n
++ )
769 wxPrintf(_T("\t%u: %s\n"), n
, dirs
[n
].c_str());
774 static void TestFileNameTemp()
776 wxPuts(_T("*** testing wxFileName temp file creation ***"));
778 static const wxChar
*tmpprefixes
[] =
786 _T("/tmp/foo/bar"), // this one must be an error
790 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
792 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
795 // "error" is not in upper case because it may be ok
796 wxPrintf(_T("Prefix '%s'\t-> error\n"), tmpprefixes
[n
]);
800 wxPrintf(_T("Prefix '%s'\t-> temp file '%s'\n"),
801 tmpprefixes
[n
], path
.c_str());
803 if ( !wxRemoveFile(path
) )
805 wxLogWarning(_T("Failed to remove temp file '%s'"),
812 static void TestFileNameMakeRelative()
814 wxPuts(_T("*** testing wxFileName::MakeRelativeTo() ***"));
816 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
818 const FileNameInfo
& fni
= filenames
[n
];
820 wxFileName
fn(fni
.fullname
, fni
.format
);
822 // choose the base dir of the same format
824 switch ( fni
.format
)
827 base
= _T("/usr/bin/");
836 // TODO: I don't know how this is supposed to work there
839 case wxPATH_NATIVE
: // make gcc happy
841 wxFAIL_MSG( _T("unexpected path format") );
844 wxPrintf(_T("'%s' relative to '%s': "),
845 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
847 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
849 wxPuts(_T("unchanged"));
853 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
858 static void TestFileNameMakeAbsolute()
860 wxPuts(_T("*** testing wxFileName::MakeAbsolute() ***"));
862 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
864 const FileNameInfo
& fni
= filenames
[n
];
865 wxFileName
fn(fni
.fullname
, fni
.format
);
867 wxPrintf(_T("'%s' absolutized: "),
868 fn
.GetFullPath(fni
.format
).c_str());
870 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
873 wxPuts(wxEmptyString
);
876 static void TestFileNameDirManip()
878 // TODO: test AppendDir(), RemoveDir(), ...
881 static void TestFileNameComparison()
886 static void TestFileNameOperations()
891 static void TestFileNameCwd()
896 #endif // TEST_FILENAME
898 // ----------------------------------------------------------------------------
899 // wxFileName time functions
900 // ----------------------------------------------------------------------------
904 #include <wx/filename.h>
905 #include <wx/datetime.h>
907 static void TestFileGetTimes()
909 wxFileName
fn(_T("testdata.fc"));
911 wxDateTime dtAccess
, dtMod
, dtCreate
;
912 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
914 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
918 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
920 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
921 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
922 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
923 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
928 static void TestFileSetTimes()
930 wxFileName
fn(_T("testdata.fc"));
934 wxPrintf(_T("ERROR: Touch() failed.\n"));
939 #endif // TEST_FILETIME
941 // ----------------------------------------------------------------------------
943 // ----------------------------------------------------------------------------
948 #include "wx/utils.h" // for wxSetEnv
950 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
952 // find the name of the language from its value
953 static const wxChar
*GetLangName(int lang
)
955 static const wxChar
*languageNames
[] =
965 _T("ARABIC_ALGERIA"),
966 _T("ARABIC_BAHRAIN"),
971 _T("ARABIC_LEBANON"),
973 _T("ARABIC_MOROCCO"),
976 _T("ARABIC_SAUDI_ARABIA"),
979 _T("ARABIC_TUNISIA"),
986 _T("AZERI_CYRILLIC"),
1001 _T("CHINESE_SIMPLIFIED"),
1002 _T("CHINESE_TRADITIONAL"),
1003 _T("CHINESE_HONGKONG"),
1004 _T("CHINESE_MACAU"),
1005 _T("CHINESE_SINGAPORE"),
1006 _T("CHINESE_TAIWAN"),
1012 _T("DUTCH_BELGIAN"),
1016 _T("ENGLISH_AUSTRALIA"),
1017 _T("ENGLISH_BELIZE"),
1018 _T("ENGLISH_BOTSWANA"),
1019 _T("ENGLISH_CANADA"),
1020 _T("ENGLISH_CARIBBEAN"),
1021 _T("ENGLISH_DENMARK"),
1023 _T("ENGLISH_JAMAICA"),
1024 _T("ENGLISH_NEW_ZEALAND"),
1025 _T("ENGLISH_PHILIPPINES"),
1026 _T("ENGLISH_SOUTH_AFRICA"),
1027 _T("ENGLISH_TRINIDAD"),
1028 _T("ENGLISH_ZIMBABWE"),
1036 _T("FRENCH_BELGIAN"),
1037 _T("FRENCH_CANADIAN"),
1038 _T("FRENCH_LUXEMBOURG"),
1039 _T("FRENCH_MONACO"),
1045 _T("GERMAN_AUSTRIAN"),
1046 _T("GERMAN_BELGIUM"),
1047 _T("GERMAN_LIECHTENSTEIN"),
1048 _T("GERMAN_LUXEMBOURG"),
1066 _T("ITALIAN_SWISS"),
1071 _T("KASHMIRI_INDIA"),
1089 _T("MALAY_BRUNEI_DARUSSALAM"),
1090 _T("MALAY_MALAYSIA"),
1100 _T("NORWEGIAN_BOKMAL"),
1101 _T("NORWEGIAN_NYNORSK"),
1108 _T("PORTUGUESE_BRAZILIAN"),
1111 _T("RHAETO_ROMANCE"),
1114 _T("RUSSIAN_UKRAINE"),
1120 _T("SERBIAN_CYRILLIC"),
1121 _T("SERBIAN_LATIN"),
1122 _T("SERBO_CROATIAN"),
1133 _T("SPANISH_ARGENTINA"),
1134 _T("SPANISH_BOLIVIA"),
1135 _T("SPANISH_CHILE"),
1136 _T("SPANISH_COLOMBIA"),
1137 _T("SPANISH_COSTA_RICA"),
1138 _T("SPANISH_DOMINICAN_REPUBLIC"),
1139 _T("SPANISH_ECUADOR"),
1140 _T("SPANISH_EL_SALVADOR"),
1141 _T("SPANISH_GUATEMALA"),
1142 _T("SPANISH_HONDURAS"),
1143 _T("SPANISH_MEXICAN"),
1144 _T("SPANISH_MODERN"),
1145 _T("SPANISH_NICARAGUA"),
1146 _T("SPANISH_PANAMA"),
1147 _T("SPANISH_PARAGUAY"),
1149 _T("SPANISH_PUERTO_RICO"),
1150 _T("SPANISH_URUGUAY"),
1152 _T("SPANISH_VENEZUELA"),
1156 _T("SWEDISH_FINLAND"),
1174 _T("URDU_PAKISTAN"),
1176 _T("UZBEK_CYRILLIC"),
1189 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1190 return languageNames
[lang
];
1192 return _T("INVALID");
1195 static void TestDefaultLang()
1197 wxPuts(_T("*** Testing wxLocale::GetSystemLanguage ***"));
1199 static const wxChar
*langStrings
[] =
1201 NULL
, // system default
1208 _T("de_DE.iso88591"),
1210 _T("?"), // invalid lang spec
1211 _T("klingonese"), // I bet on some systems it does exist...
1214 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1215 wxLocale::GetSystemEncodingName().c_str(),
1216 wxLocale::GetSystemEncoding());
1218 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1220 const wxChar
*langStr
= langStrings
[n
];
1223 // FIXME: this doesn't do anything at all under Windows, we need
1224 // to create a new wxLocale!
1225 wxSetEnv(_T("LC_ALL"), langStr
);
1228 int lang
= gs_localeDefault
.GetSystemLanguage();
1229 wxPrintf(_T("Locale for '%s' is %s.\n"),
1230 langStr
? langStr
: _T("system default"), GetLangName(lang
));
1234 #endif // TEST_LOCALE
1236 // ----------------------------------------------------------------------------
1238 // ----------------------------------------------------------------------------
1242 #include "wx/mimetype.h"
1244 static void TestMimeEnum()
1246 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1248 wxArrayString mimetypes
;
1250 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1252 wxPrintf(_T("*** All %u known filetypes: ***\n"), count
);
1257 for ( size_t n
= 0; n
< count
; n
++ )
1259 wxFileType
*filetype
=
1260 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1263 wxPrintf(_T("nothing known about the filetype '%s'!\n"),
1264 mimetypes
[n
].c_str());
1268 filetype
->GetDescription(&desc
);
1269 filetype
->GetExtensions(exts
);
1271 filetype
->GetIcon(NULL
);
1274 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1277 extsAll
<< _T(", ");
1281 wxPrintf(_T("\t%s: %s (%s)\n"),
1282 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1285 wxPuts(wxEmptyString
);
1288 static void TestMimeOverride()
1290 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1292 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1293 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1295 if ( wxFile::Exists(mailcap
) )
1296 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1298 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1300 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1303 if ( wxFile::Exists(mimetypes
) )
1304 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1306 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1308 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1311 wxPuts(wxEmptyString
);
1314 static void TestMimeFilename()
1316 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1318 static const wxChar
*filenames
[] =
1326 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1328 const wxString fname
= filenames
[n
];
1329 wxString ext
= fname
.AfterLast(_T('.'));
1330 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1333 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1338 if ( !ft
->GetDescription(&desc
) )
1339 desc
= _T("<no description>");
1342 if ( !ft
->GetOpenCommand(&cmd
,
1343 wxFileType::MessageParameters(fname
, wxEmptyString
)) )
1344 cmd
= _T("<no command available>");
1346 cmd
= wxString(_T('"')) + cmd
+ _T('"');
1348 wxPrintf(_T("To open %s (%s) do %s.\n"),
1349 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1355 wxPuts(wxEmptyString
);
1358 static void TestMimeAssociate()
1360 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1362 wxFileTypeInfo
ftInfo(
1363 _T("application/x-xyz"),
1364 _T("xyzview '%s'"), // open cmd
1365 _T(""), // print cmd
1366 _T("XYZ File"), // description
1367 _T(".xyz"), // extensions
1368 NULL
// end of extensions
1370 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1372 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1375 wxPuts(_T("ERROR: failed to create association!"));
1379 // TODO: read it back
1383 wxPuts(wxEmptyString
);
1388 // ----------------------------------------------------------------------------
1389 // misc information functions
1390 // ----------------------------------------------------------------------------
1392 #ifdef TEST_INFO_FUNCTIONS
1394 #include "wx/utils.h"
1396 static void TestDiskInfo()
1398 wxPuts(_T("*** Testing wxGetDiskSpace() ***"));
1402 wxChar pathname
[128];
1403 wxPrintf(_T("\nEnter a directory name: "));
1404 if ( !wxFgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1407 // kill the last '\n'
1408 pathname
[wxStrlen(pathname
) - 1] = 0;
1410 wxLongLong total
, free
;
1411 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1413 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1417 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1418 (total
/ 1024).ToString().c_str(),
1419 (free
/ 1024).ToString().c_str(),
1425 static void TestOsInfo()
1427 wxPuts(_T("*** Testing OS info functions ***\n"));
1430 wxGetOsVersion(&major
, &minor
);
1431 wxPrintf(_T("Running under: %s, version %d.%d\n"),
1432 wxGetOsDescription().c_str(), major
, minor
);
1434 wxPrintf(_T("%ld free bytes of memory left.\n"), wxGetFreeMemory());
1436 wxPrintf(_T("Host name is %s (%s).\n"),
1437 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1439 wxPuts(wxEmptyString
);
1442 static void TestUserInfo()
1444 wxPuts(_T("*** Testing user info functions ***\n"));
1446 wxPrintf(_T("User id is:\t%s\n"), wxGetUserId().c_str());
1447 wxPrintf(_T("User name is:\t%s\n"), wxGetUserName().c_str());
1448 wxPrintf(_T("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
1449 wxPrintf(_T("Email address:\t%s\n"), wxGetEmailAddress().c_str());
1451 wxPuts(wxEmptyString
);
1454 #endif // TEST_INFO_FUNCTIONS
1456 // ----------------------------------------------------------------------------
1458 // ----------------------------------------------------------------------------
1460 #ifdef TEST_PATHLIST
1463 #define CMD_IN_PATH _T("ls")
1465 #define CMD_IN_PATH _T("command.com")
1468 static void TestPathList()
1470 wxPuts(_T("*** Testing wxPathList ***\n"));
1472 wxPathList pathlist
;
1473 pathlist
.AddEnvList(_T("PATH"));
1474 wxString path
= pathlist
.FindValidPath(CMD_IN_PATH
);
1477 wxPrintf(_T("ERROR: command not found in the path.\n"));
1481 wxPrintf(_T("Command found in the path as '%s'.\n"), path
.c_str());
1485 #endif // TEST_PATHLIST
1487 // ----------------------------------------------------------------------------
1488 // regular expressions
1489 // ----------------------------------------------------------------------------
1493 #include "wx/regex.h"
1495 static void TestRegExInteractive()
1497 wxPuts(_T("*** Testing RE interactively ***"));
1501 wxChar pattern
[128];
1502 wxPrintf(_T("\nEnter a pattern: "));
1503 if ( !wxFgets(pattern
, WXSIZEOF(pattern
), stdin
) )
1506 // kill the last '\n'
1507 pattern
[wxStrlen(pattern
) - 1] = 0;
1510 if ( !re
.Compile(pattern
) )
1518 wxPrintf(_T("Enter text to match: "));
1519 if ( !wxFgets(text
, WXSIZEOF(text
), stdin
) )
1522 // kill the last '\n'
1523 text
[wxStrlen(text
) - 1] = 0;
1525 if ( !re
.Matches(text
) )
1527 wxPrintf(_T("No match.\n"));
1531 wxPrintf(_T("Pattern matches at '%s'\n"), re
.GetMatch(text
).c_str());
1534 for ( size_t n
= 1; ; n
++ )
1536 if ( !re
.GetMatch(&start
, &len
, n
) )
1541 wxPrintf(_T("Subexpr %u matched '%s'\n"),
1542 n
, wxString(text
+ start
, len
).c_str());
1549 #endif // TEST_REGEX
1551 // ----------------------------------------------------------------------------
1553 // ----------------------------------------------------------------------------
1563 static void TestDbOpen()
1571 // ----------------------------------------------------------------------------
1573 // ----------------------------------------------------------------------------
1576 NB: this stuff was taken from the glibc test suite and modified to build
1577 in wxWidgets: if I read the copyright below properly, this shouldn't
1583 #ifdef wxTEST_PRINTF
1584 // use our functions from wxchar.cpp
1588 // NB: do _not_ use ATTRIBUTE_PRINTF here, we have some invalid formats
1589 // in the tests below
1590 int wxPrintf( const wxChar
*format
, ... );
1591 int wxSprintf( wxChar
*str
, const wxChar
*format
, ... );
1594 #include "wx/longlong.h"
1598 static void rfg1 (void);
1599 static void rfg2 (void);
1603 fmtchk (const wxChar
*fmt
)
1605 (void) wxPrintf(_T("%s:\t`"), fmt
);
1606 (void) wxPrintf(fmt
, 0x12);
1607 (void) wxPrintf(_T("'\n"));
1611 fmtst1chk (const wxChar
*fmt
)
1613 (void) wxPrintf(_T("%s:\t`"), fmt
);
1614 (void) wxPrintf(fmt
, 4, 0x12);
1615 (void) wxPrintf(_T("'\n"));
1619 fmtst2chk (const wxChar
*fmt
)
1621 (void) wxPrintf(_T("%s:\t`"), fmt
);
1622 (void) wxPrintf(fmt
, 4, 4, 0x12);
1623 (void) wxPrintf(_T("'\n"));
1626 /* This page is covered by the following copyright: */
1628 /* (C) Copyright C E Chew
1630 * Feel free to copy, use and distribute this software provided:
1632 * 1. you do not pretend that you wrote it
1633 * 2. you leave this copyright notice intact.
1637 * Extracted from exercise.c for glibc-1.05 bug report by Bruce Evans.
1644 /* Formatted Output Test
1646 * This exercises the output formatting code.
1649 wxChar
*PointerNull
= NULL
;
1656 wxChar
*prefix
= buf
;
1659 wxPuts(_T("\nFormatted output test"));
1660 wxPrintf(_T("prefix 6d 6o 6x 6X 6u\n"));
1661 wxStrcpy(prefix
, _T("%"));
1662 for (i
= 0; i
< 2; i
++) {
1663 for (j
= 0; j
< 2; j
++) {
1664 for (k
= 0; k
< 2; k
++) {
1665 for (l
= 0; l
< 2; l
++) {
1666 wxStrcpy(prefix
, _T("%"));
1667 if (i
== 0) wxStrcat(prefix
, _T("-"));
1668 if (j
== 0) wxStrcat(prefix
, _T("+"));
1669 if (k
== 0) wxStrcat(prefix
, _T("#"));
1670 if (l
== 0) wxStrcat(prefix
, _T("0"));
1671 wxPrintf(_T("%5s |"), prefix
);
1672 wxStrcpy(tp
, prefix
);
1673 wxStrcat(tp
, _T("6d |"));
1675 wxStrcpy(tp
, prefix
);
1676 wxStrcat(tp
, _T("6o |"));
1678 wxStrcpy(tp
, prefix
);
1679 wxStrcat(tp
, _T("6x |"));
1681 wxStrcpy(tp
, prefix
);
1682 wxStrcat(tp
, _T("6X |"));
1684 wxStrcpy(tp
, prefix
);
1685 wxStrcat(tp
, _T("6u |"));
1692 wxPrintf(_T("%10s\n"), PointerNull
);
1693 wxPrintf(_T("%-10s\n"), PointerNull
);
1696 static void TestPrintf()
1698 static wxChar shortstr
[] = _T("Hi, Z.");
1699 static wxChar longstr
[] = _T("Good morning, Doctor Chandra. This is Hal. \
1700 I am ready for my first lesson today.");
1702 wxString test_format
;
1706 fmtchk(_T("%4.4x"));
1707 fmtchk(_T("%04.4x"));
1708 fmtchk(_T("%4.3x"));
1709 fmtchk(_T("%04.3x"));
1711 fmtst1chk(_T("%.*x"));
1712 fmtst1chk(_T("%0*x"));
1713 fmtst2chk(_T("%*.*x"));
1714 fmtst2chk(_T("%0*.*x"));
1716 wxString bad_format
= _T("bad format:\t\"%b\"\n");
1717 wxPrintf(bad_format
.c_str());
1718 wxPrintf(_T("nil pointer (padded):\t\"%10p\"\n"), (void *) NULL
);
1720 wxPrintf(_T("decimal negative:\t\"%d\"\n"), -2345);
1721 wxPrintf(_T("octal negative:\t\"%o\"\n"), -2345);
1722 wxPrintf(_T("hex negative:\t\"%x\"\n"), -2345);
1723 wxPrintf(_T("long decimal number:\t\"%ld\"\n"), -123456L);
1724 wxPrintf(_T("long octal negative:\t\"%lo\"\n"), -2345L);
1725 wxPrintf(_T("long unsigned decimal number:\t\"%lu\"\n"), -123456L);
1726 wxPrintf(_T("zero-padded LDN:\t\"%010ld\"\n"), -123456L);
1727 test_format
= _T("left-adjusted ZLDN:\t\"%-010ld\"\n");
1728 wxPrintf(test_format
.c_str(), -123456);
1729 wxPrintf(_T("space-padded LDN:\t\"%10ld\"\n"), -123456L);
1730 wxPrintf(_T("left-adjusted SLDN:\t\"%-10ld\"\n"), -123456L);
1732 test_format
= _T("zero-padded string:\t\"%010s\"\n");
1733 wxPrintf(test_format
.c_str(), shortstr
);
1734 test_format
= _T("left-adjusted Z string:\t\"%-010s\"\n");
1735 wxPrintf(test_format
.c_str(), shortstr
);
1736 wxPrintf(_T("space-padded string:\t\"%10s\"\n"), shortstr
);
1737 wxPrintf(_T("left-adjusted S string:\t\"%-10s\"\n"), shortstr
);
1738 wxPrintf(_T("null string:\t\"%s\"\n"), PointerNull
);
1739 wxPrintf(_T("limited string:\t\"%.22s\"\n"), longstr
);
1741 wxPrintf(_T("e-style >= 1:\t\"%e\"\n"), 12.34);
1742 wxPrintf(_T("e-style >= .1:\t\"%e\"\n"), 0.1234);
1743 wxPrintf(_T("e-style < .1:\t\"%e\"\n"), 0.001234);
1744 wxPrintf(_T("e-style big:\t\"%.60e\"\n"), 1e20
);
1745 wxPrintf(_T("e-style == .1:\t\"%e\"\n"), 0.1);
1746 wxPrintf(_T("f-style >= 1:\t\"%f\"\n"), 12.34);
1747 wxPrintf(_T("f-style >= .1:\t\"%f\"\n"), 0.1234);
1748 wxPrintf(_T("f-style < .1:\t\"%f\"\n"), 0.001234);
1749 wxPrintf(_T("g-style >= 1:\t\"%g\"\n"), 12.34);
1750 wxPrintf(_T("g-style >= .1:\t\"%g\"\n"), 0.1234);
1751 wxPrintf(_T("g-style < .1:\t\"%g\"\n"), 0.001234);
1752 wxPrintf(_T("g-style big:\t\"%.60g\"\n"), 1e20
);
1754 wxPrintf (_T(" %6.5f\n"), .099999999860301614);
1755 wxPrintf (_T(" %6.5f\n"), .1);
1756 wxPrintf (_T("x%5.4fx\n"), .5);
1758 wxPrintf (_T("%#03x\n"), 1);
1760 //wxPrintf (_T("something really insane: %.10000f\n"), 1.0);
1766 while (niter
-- != 0)
1767 wxPrintf (_T("%.17e\n"), d
/ 2);
1772 // Open Watcom cause compiler error here
1773 // Error! E173: col(24) floating-point constant too small to represent
1774 wxPrintf (_T("%15.5e\n"), 4.9406564584124654e-324);
1777 #define FORMAT _T("|%12.4f|%12.4e|%12.4g|\n")
1778 wxPrintf (FORMAT
, 0.0, 0.0, 0.0);
1779 wxPrintf (FORMAT
, 1.0, 1.0, 1.0);
1780 wxPrintf (FORMAT
, -1.0, -1.0, -1.0);
1781 wxPrintf (FORMAT
, 100.0, 100.0, 100.0);
1782 wxPrintf (FORMAT
, 1000.0, 1000.0, 1000.0);
1783 wxPrintf (FORMAT
, 10000.0, 10000.0, 10000.0);
1784 wxPrintf (FORMAT
, 12345.0, 12345.0, 12345.0);
1785 wxPrintf (FORMAT
, 100000.0, 100000.0, 100000.0);
1786 wxPrintf (FORMAT
, 123456.0, 123456.0, 123456.0);
1791 int rc
= wxSnprintf (buf
, WXSIZEOF(buf
), _T("%30s"), _T("foo"));
1793 wxPrintf(_T("snprintf (\"%%30s\", \"foo\") == %d, \"%.*s\"\n"),
1794 rc
, WXSIZEOF(buf
), buf
);
1797 wxPrintf ("snprintf (\"%%.999999u\", 10)\n",
1798 wxSnprintf(buf2
, WXSIZEOFbuf2
), "%.999999u", 10));
1804 wxPrintf (_T("%e should be 1.234568e+06\n"), 1234567.8);
1805 wxPrintf (_T("%f should be 1234567.800000\n"), 1234567.8);
1806 wxPrintf (_T("%g should be 1.23457e+06\n"), 1234567.8);
1807 wxPrintf (_T("%g should be 123.456\n"), 123.456);
1808 wxPrintf (_T("%g should be 1e+06\n"), 1000000.0);
1809 wxPrintf (_T("%g should be 10\n"), 10.0);
1810 wxPrintf (_T("%g should be 0.02\n"), 0.02);
1814 wxPrintf(_T("%.17f\n"),(1.0/x
/10.0+1.0)*x
-x
);
1820 wxSprintf(buf
,_T("%*s%*s%*s"),-1,_T("one"),-20,_T("two"),-30,_T("three"));
1822 result
|= wxStrcmp (buf
,
1823 _T("onetwo three "));
1825 wxPuts (result
!= 0 ? _T("Test failed!") : _T("Test ok."));
1832 wxSprintf(buf
, _T("%07") wxLongLongFmtSpec
_T("o"), wxLL(040000000000));
1834 // for some reason below line fails under Borland
1835 wxPrintf (_T("sprintf (buf, \"%%07Lo\", 040000000000ll) = %s"), buf
);
1838 if (wxStrcmp (buf
, _T("40000000000")) != 0)
1841 wxPuts (_T("\tFAILED"));
1843 wxUnusedVar(result
);
1844 wxPuts (wxEmptyString
);
1846 #endif // wxLongLong_t
1848 wxPrintf (_T("printf (\"%%hhu\", %u) = %hhu\n"), UCHAR_MAX
+ 2, UCHAR_MAX
+ 2);
1849 wxPrintf (_T("printf (\"%%hu\", %u) = %hu\n"), USHRT_MAX
+ 2, USHRT_MAX
+ 2);
1851 wxPuts (_T("--- Should be no further output. ---"));
1860 memset (bytes
, '\xff', sizeof bytes
);
1861 wxSprintf (buf
, _T("foo%hhn\n"), &bytes
[3]);
1862 if (bytes
[0] != '\xff' || bytes
[1] != '\xff' || bytes
[2] != '\xff'
1863 || bytes
[4] != '\xff' || bytes
[5] != '\xff' || bytes
[6] != '\xff')
1865 wxPuts (_T("%hhn overwrite more bytes"));
1870 wxPuts (_T("%hhn wrote incorrect value"));
1882 wxSprintf (buf
, _T("%5.s"), _T("xyz"));
1883 if (wxStrcmp (buf
, _T(" ")) != 0)
1884 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" "));
1885 wxSprintf (buf
, _T("%5.f"), 33.3);
1886 if (wxStrcmp (buf
, _T(" 33")) != 0)
1887 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 33"));
1888 wxSprintf (buf
, _T("%8.e"), 33.3e7
);
1889 if (wxStrcmp (buf
, _T(" 3e+08")) != 0)
1890 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3e+08"));
1891 wxSprintf (buf
, _T("%8.E"), 33.3e7
);
1892 if (wxStrcmp (buf
, _T(" 3E+08")) != 0)
1893 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3E+08"));
1894 wxSprintf (buf
, _T("%.g"), 33.3);
1895 if (wxStrcmp (buf
, _T("3e+01")) != 0)
1896 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3e+01"));
1897 wxSprintf (buf
, _T("%.G"), 33.3);
1898 if (wxStrcmp (buf
, _T("3E+01")) != 0)
1899 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3E+01"));
1907 wxString test_format
;
1910 wxSprintf (buf
, _T("%.*g"), prec
, 3.3);
1911 if (wxStrcmp (buf
, _T("3")) != 0)
1912 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
1914 wxSprintf (buf
, _T("%.*G"), prec
, 3.3);
1915 if (wxStrcmp (buf
, _T("3")) != 0)
1916 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
1918 wxSprintf (buf
, _T("%7.*G"), prec
, 3.33);
1919 if (wxStrcmp (buf
, _T(" 3")) != 0)
1920 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3"));
1922 test_format
= _T("%04.*o");
1923 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1924 if (wxStrcmp (buf
, _T(" 041")) != 0)
1925 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 041"));
1927 test_format
= _T("%09.*u");
1928 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1929 if (wxStrcmp (buf
, _T(" 0000033")) != 0)
1930 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 0000033"));
1932 test_format
= _T("%04.*x");
1933 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1934 if (wxStrcmp (buf
, _T(" 021")) != 0)
1935 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
1937 test_format
= _T("%04.*X");
1938 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1939 if (wxStrcmp (buf
, _T(" 021")) != 0)
1940 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
1943 #endif // TEST_PRINTF
1945 // ----------------------------------------------------------------------------
1946 // registry and related stuff
1947 // ----------------------------------------------------------------------------
1949 // this is for MSW only
1952 #undef TEST_REGISTRY
1957 #include "wx/confbase.h"
1958 #include "wx/msw/regconf.h"
1961 static void TestRegConfWrite()
1963 wxConfig
*config
= new wxConfig(_T("myapp"));
1964 config
->SetPath(_T("/group1"));
1965 config
->Write(_T("entry1"), _T("foo"));
1966 config
->SetPath(_T("/group2"));
1967 config
->Write(_T("entry1"), _T("bar"));
1971 static void TestRegConfRead()
1973 wxConfig
*config
= new wxConfig(_T("myapp"));
1977 config
->SetPath(_T("/"));
1978 wxPuts(_T("Enumerating / subgroups:"));
1979 bool bCont
= config
->GetFirstGroup(str
, dummy
);
1983 bCont
= config
->GetNextGroup(str
, dummy
);
1987 #endif // TEST_REGCONF
1989 #ifdef TEST_REGISTRY
1991 #include "wx/msw/registry.h"
1993 // I chose this one because I liked its name, but it probably only exists under
1995 static const wxChar
*TESTKEY
=
1996 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1998 static void TestRegistryRead()
2000 wxPuts(_T("*** testing registry reading ***"));
2002 wxRegKey
key(TESTKEY
);
2003 wxPrintf(_T("The test key name is '%s'.\n"), key
.GetName().c_str());
2006 wxPuts(_T("ERROR: test key can't be opened, aborting test."));
2011 size_t nSubKeys
, nValues
;
2012 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2014 wxPrintf(_T("It has %u subkeys and %u values.\n"), nSubKeys
, nValues
);
2017 wxPrintf(_T("Enumerating values:\n"));
2021 bool cont
= key
.GetFirstValue(value
, dummy
);
2024 wxPrintf(_T("Value '%s': type "), value
.c_str());
2025 switch ( key
.GetValueType(value
) )
2027 case wxRegKey::Type_None
: wxPrintf(_T("ERROR (none)")); break;
2028 case wxRegKey::Type_String
: wxPrintf(_T("SZ")); break;
2029 case wxRegKey::Type_Expand_String
: wxPrintf(_T("EXPAND_SZ")); break;
2030 case wxRegKey::Type_Binary
: wxPrintf(_T("BINARY")); break;
2031 case wxRegKey::Type_Dword
: wxPrintf(_T("DWORD")); break;
2032 case wxRegKey::Type_Multi_String
: wxPrintf(_T("MULTI_SZ")); break;
2033 default: wxPrintf(_T("other (unknown)")); break;
2036 wxPrintf(_T(", value = "));
2037 if ( key
.IsNumericValue(value
) )
2040 key
.QueryValue(value
, &val
);
2041 wxPrintf(_T("%ld"), val
);
2046 key
.QueryValue(value
, val
);
2047 wxPrintf(_T("'%s'"), val
.c_str());
2049 key
.QueryRawValue(value
, val
);
2050 wxPrintf(_T(" (raw value '%s')"), val
.c_str());
2055 cont
= key
.GetNextValue(value
, dummy
);
2059 static void TestRegistryAssociation()
2062 The second call to deleteself genertaes an error message, with a
2063 messagebox saying .flo is crucial to system operation, while the .ddf
2064 call also fails, but with no error message
2069 key
.SetName(_T("HKEY_CLASSES_ROOT\\.ddf") );
2071 key
= _T("ddxf_auto_file") ;
2072 key
.SetName(_T("HKEY_CLASSES_ROOT\\.flo") );
2074 key
= _T("ddxf_auto_file") ;
2075 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2077 key
= _T("program,0") ;
2078 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2080 key
= _T("program \"%1\"") ;
2082 key
.SetName(_T("HKEY_CLASSES_ROOT\\.ddf") );
2084 key
.SetName(_T("HKEY_CLASSES_ROOT\\.flo") );
2086 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2088 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2092 #endif // TEST_REGISTRY
2094 // ----------------------------------------------------------------------------
2096 // ----------------------------------------------------------------------------
2098 #ifdef TEST_SCOPEGUARD
2100 #include "wx/scopeguard.h"
2102 static void function0() { puts("function0()"); }
2103 static void function1(int n
) { printf("function1(%d)\n", n
); }
2104 static void function2(double x
, char c
) { printf("function2(%g, %c)\n", x
, c
); }
2108 void method0() { printf("method0()\n"); }
2109 void method1(int n
) { printf("method1(%d)\n", n
); }
2110 void method2(double x
, char c
) { printf("method2(%g, %c)\n", x
, c
); }
2113 static void TestScopeGuard()
2115 wxON_BLOCK_EXIT0(function0
);
2116 wxON_BLOCK_EXIT1(function1
, 17);
2117 wxON_BLOCK_EXIT2(function2
, 3.14, 'p');
2120 wxON_BLOCK_EXIT_OBJ0(obj
, &Object::method0
);
2121 wxON_BLOCK_EXIT_OBJ1(obj
, &Object::method1
, 7);
2122 wxON_BLOCK_EXIT_OBJ2(obj
, &Object::method2
, 2.71, 'e');
2124 wxScopeGuard dismissed
= wxMakeGuard(function0
);
2125 dismissed
.Dismiss();
2130 // ----------------------------------------------------------------------------
2132 // ----------------------------------------------------------------------------
2136 #include "wx/socket.h"
2137 #include "wx/protocol/protocol.h"
2138 #include "wx/protocol/http.h"
2140 static void TestSocketServer()
2142 wxPuts(_T("*** Testing wxSocketServer ***\n"));
2144 static const int PORT
= 3000;
2149 wxSocketServer
*server
= new wxSocketServer(addr
);
2150 if ( !server
->Ok() )
2152 wxPuts(_T("ERROR: failed to bind"));
2160 wxPrintf(_T("Server: waiting for connection on port %d...\n"), PORT
);
2162 wxSocketBase
*socket
= server
->Accept();
2165 wxPuts(_T("ERROR: wxSocketServer::Accept() failed."));
2169 wxPuts(_T("Server: got a client."));
2171 server
->SetTimeout(60); // 1 min
2174 while ( !close
&& socket
->IsConnected() )
2177 wxChar ch
= _T('\0');
2180 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2182 // don't log error if the client just close the connection
2183 if ( socket
->IsConnected() )
2185 wxPuts(_T("ERROR: in wxSocket::Read."));
2205 wxPrintf(_T("Server: got '%s'.\n"), s
.c_str());
2206 if ( s
== _T("close") )
2208 wxPuts(_T("Closing connection"));
2212 else if ( s
== _T("quit") )
2217 wxPuts(_T("Shutting down the server"));
2219 else // not a special command
2221 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2222 socket
->Write("\r\n", 2);
2223 wxPrintf(_T("Server: wrote '%s'.\n"), s
.c_str());
2229 wxPuts(_T("Server: lost a client unexpectedly."));
2235 // same as "delete server" but is consistent with GUI programs
2239 static void TestSocketClient()
2241 wxPuts(_T("*** Testing wxSocketClient ***\n"));
2243 static const wxChar
*hostname
= _T("www.wxwidgets.org");
2246 addr
.Hostname(hostname
);
2249 wxPrintf(_T("--- Attempting to connect to %s:80...\n"), hostname
);
2251 wxSocketClient client
;
2252 if ( !client
.Connect(addr
) )
2254 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2258 wxPrintf(_T("--- Connected to %s:%u...\n"),
2259 addr
.Hostname().c_str(), addr
.Service());
2263 // could use simply "GET" here I suppose
2265 wxString::Format(_T("GET http://%s/\r\n"), hostname
);
2266 client
.Write(cmdGet
, cmdGet
.length());
2267 wxPrintf(_T("--- Sent command '%s' to the server\n"),
2268 MakePrintable(cmdGet
).c_str());
2269 client
.Read(buf
, WXSIZEOF(buf
));
2270 wxPrintf(_T("--- Server replied:\n%s"), buf
);
2274 #endif // TEST_SOCKETS
2276 // ----------------------------------------------------------------------------
2278 // ----------------------------------------------------------------------------
2282 #include "wx/protocol/ftp.h"
2286 #define FTP_ANONYMOUS
2288 #ifdef FTP_ANONYMOUS
2289 static const wxChar
*directory
= _T("/pub");
2290 static const wxChar
*filename
= _T("welcome.msg");
2292 static const wxChar
*directory
= _T("/etc");
2293 static const wxChar
*filename
= _T("issue");
2296 static bool TestFtpConnect()
2298 wxPuts(_T("*** Testing FTP connect ***"));
2300 #ifdef FTP_ANONYMOUS
2301 static const wxChar
*hostname
= _T("ftp.wxwidgets.org");
2303 wxPrintf(_T("--- Attempting to connect to %s:21 anonymously...\n"), hostname
);
2304 #else // !FTP_ANONYMOUS
2305 static const wxChar
*hostname
= "localhost";
2308 wxFgets(user
, WXSIZEOF(user
), stdin
);
2309 user
[wxStrlen(user
) - 1] = '\0'; // chop off '\n'
2312 wxChar password
[256];
2313 wxPrintf(_T("Password for %s: "), password
);
2314 wxFgets(password
, WXSIZEOF(password
), stdin
);
2315 password
[wxStrlen(password
) - 1] = '\0'; // chop off '\n'
2316 ftp
.SetPassword(password
);
2318 wxPrintf(_T("--- Attempting to connect to %s:21 as %s...\n"), hostname
, user
);
2319 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2321 if ( !ftp
.Connect(hostname
) )
2323 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2329 wxPrintf(_T("--- Connected to %s, current directory is '%s'\n"),
2330 hostname
, ftp
.Pwd().c_str());
2337 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2338 static void TestFtpWuFtpd()
2341 static const wxChar
*hostname
= _T("ftp.eudora.com");
2342 if ( !ftp
.Connect(hostname
) )
2344 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2348 static const wxChar
*filename
= _T("eudora/pubs/draft-gellens-submit-09.txt");
2349 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2352 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
2356 size_t size
= in
->GetSize();
2357 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
2359 wxChar
*data
= new wxChar
[size
];
2360 if ( !in
->Read(data
, size
) )
2362 wxPuts(_T("ERROR: read error"));
2366 wxPrintf(_T("Successfully retrieved the file.\n"));
2375 static void TestFtpList()
2377 wxPuts(_T("*** Testing wxFTP file listing ***\n"));
2380 if ( !ftp
.ChDir(directory
) )
2382 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
2385 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2387 // test NLIST and LIST
2388 wxArrayString files
;
2389 if ( !ftp
.GetFilesList(files
) )
2391 wxPuts(_T("ERROR: failed to get NLIST of files"));
2395 wxPrintf(_T("Brief list of files under '%s':\n"), ftp
.Pwd().c_str());
2396 size_t count
= files
.GetCount();
2397 for ( size_t n
= 0; n
< count
; n
++ )
2399 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2401 wxPuts(_T("End of the file list"));
2404 if ( !ftp
.GetDirList(files
) )
2406 wxPuts(_T("ERROR: failed to get LIST of files"));
2410 wxPrintf(_T("Detailed list of files under '%s':\n"), ftp
.Pwd().c_str());
2411 size_t count
= files
.GetCount();
2412 for ( size_t n
= 0; n
< count
; n
++ )
2414 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2416 wxPuts(_T("End of the file list"));
2419 if ( !ftp
.ChDir(_T("..")) )
2421 wxPuts(_T("ERROR: failed to cd to .."));
2424 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2427 static void TestFtpDownload()
2429 wxPuts(_T("*** Testing wxFTP download ***\n"));
2432 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2435 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
2439 size_t size
= in
->GetSize();
2440 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
2443 wxChar
*data
= new wxChar
[size
];
2444 if ( !in
->Read(data
, size
) )
2446 wxPuts(_T("ERROR: read error"));
2450 wxPrintf(_T("\nContents of %s:\n%s\n"), filename
, data
);
2458 static void TestFtpFileSize()
2460 wxPuts(_T("*** Testing FTP SIZE command ***"));
2462 if ( !ftp
.ChDir(directory
) )
2464 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
2467 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2469 if ( ftp
.FileExists(filename
) )
2471 int size
= ftp
.GetFileSize(filename
);
2473 wxPrintf(_T("ERROR: couldn't get size of '%s'\n"), filename
);
2475 wxPrintf(_T("Size of '%s' is %d bytes.\n"), filename
, size
);
2479 wxPrintf(_T("ERROR: '%s' doesn't exist\n"), filename
);
2483 static void TestFtpMisc()
2485 wxPuts(_T("*** Testing miscellaneous wxFTP functions ***"));
2487 if ( ftp
.SendCommand(_T("STAT")) != '2' )
2489 wxPuts(_T("ERROR: STAT failed"));
2493 wxPrintf(_T("STAT returned:\n\n%s\n"), ftp
.GetLastResult().c_str());
2496 if ( ftp
.SendCommand(_T("HELP SITE")) != '2' )
2498 wxPuts(_T("ERROR: HELP SITE failed"));
2502 wxPrintf(_T("The list of site-specific commands:\n\n%s\n"),
2503 ftp
.GetLastResult().c_str());
2507 static void TestFtpInteractive()
2509 wxPuts(_T("\n*** Interactive wxFTP test ***"));
2515 wxPrintf(_T("Enter FTP command: "));
2516 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
2519 // kill the last '\n'
2520 buf
[wxStrlen(buf
) - 1] = 0;
2522 // special handling of LIST and NLST as they require data connection
2523 wxString
start(buf
, 4);
2525 if ( start
== _T("LIST") || start
== _T("NLST") )
2528 if ( wxStrlen(buf
) > 4 )
2531 wxArrayString files
;
2532 if ( !ftp
.GetList(files
, wildcard
, start
== _T("LIST")) )
2534 wxPrintf(_T("ERROR: failed to get %s of files\n"), start
.c_str());
2538 wxPrintf(_T("--- %s of '%s' under '%s':\n"),
2539 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2540 size_t count
= files
.GetCount();
2541 for ( size_t n
= 0; n
< count
; n
++ )
2543 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2545 wxPuts(_T("--- End of the file list"));
2550 wxChar ch
= ftp
.SendCommand(buf
);
2551 wxPrintf(_T("Command %s"), ch
? _T("succeeded") : _T("failed"));
2554 wxPrintf(_T(" (return code %c)"), ch
);
2557 wxPrintf(_T(", server reply:\n%s\n\n"), ftp
.GetLastResult().c_str());
2561 wxPuts(_T("\n*** done ***"));
2564 static void TestFtpUpload()
2566 wxPuts(_T("*** Testing wxFTP uploading ***\n"));
2569 static const wxChar
*file1
= _T("test1");
2570 static const wxChar
*file2
= _T("test2");
2571 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2574 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
2575 out
->Write("First hello", 11);
2579 // send a command to check the remote file
2580 if ( ftp
.SendCommand(wxString(_T("STAT ")) + file1
) != '2' )
2582 wxPrintf(_T("ERROR: STAT %s failed\n"), file1
);
2586 wxPrintf(_T("STAT %s returned:\n\n%s\n"),
2587 file1
, ftp
.GetLastResult().c_str());
2590 out
= ftp
.GetOutputStream(file2
);
2593 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
2594 out
->Write("Second hello", 12);
2601 // ----------------------------------------------------------------------------
2603 // ----------------------------------------------------------------------------
2605 #ifdef TEST_STDPATHS
2607 #include "wx/stdpaths.h"
2609 static void TestStandardPaths()
2611 wxPuts(_T("*** Testing wxStandardPaths ***\n"));
2613 wxTheApp
->SetAppName(_T("console"));
2615 wxStandardPaths
& stdp
= wxStandardPaths::Get();
2616 wxPrintf(_T("Config dir (sys):\t%s\n"), stdp
.GetConfigDir().c_str());
2617 wxPrintf(_T("Config dir (user):\t%s\n"), stdp
.GetUserConfigDir().c_str());
2618 wxPrintf(_T("Data dir (sys):\t\t%s\n"), stdp
.GetDataDir().c_str());
2619 wxPrintf(_T("Data dir (sys local):\t%s\n"), stdp
.GetLocalDataDir().c_str());
2620 wxPrintf(_T("Data dir (user):\t%s\n"), stdp
.GetUserDataDir().c_str());
2621 wxPrintf(_T("Data dir (user local):\t%s\n"), stdp
.GetUserLocalDataDir().c_str());
2622 wxPrintf(_T("Plugins dir:\t\t%s\n"), stdp
.GetPluginsDir().c_str());
2625 #endif // TEST_STDPATHS
2627 // ----------------------------------------------------------------------------
2629 // ----------------------------------------------------------------------------
2633 #include "wx/wfstream.h"
2634 #include "wx/mstream.h"
2636 static void TestFileStream()
2638 wxPuts(_T("*** Testing wxFileInputStream ***"));
2640 static const wxString filename
= _T("testdata.fs");
2642 wxFileOutputStream
fsOut(filename
);
2643 fsOut
.Write("foo", 3);
2646 wxFileInputStream
fsIn(filename
);
2647 wxPrintf(_T("File stream size: %u\n"), fsIn
.GetSize());
2648 while ( !fsIn
.Eof() )
2650 wxPutchar(fsIn
.GetC());
2653 if ( !wxRemoveFile(filename
) )
2655 wxPrintf(_T("ERROR: failed to remove the file '%s'.\n"), filename
.c_str());
2658 wxPuts(_T("\n*** wxFileInputStream test done ***"));
2661 static void TestMemoryStream()
2663 wxPuts(_T("*** Testing wxMemoryOutputStream ***"));
2665 wxMemoryOutputStream memOutStream
;
2666 wxPrintf(_T("Initially out stream offset: %lu\n"),
2667 (unsigned long)memOutStream
.TellO());
2669 for ( const wxChar
*p
= _T("Hello, stream!"); *p
; p
++ )
2671 memOutStream
.PutC(*p
);
2674 wxPrintf(_T("Final out stream offset: %lu\n"),
2675 (unsigned long)memOutStream
.TellO());
2677 wxPuts(_T("*** Testing wxMemoryInputStream ***"));
2680 size_t len
= memOutStream
.CopyTo(buf
, WXSIZEOF(buf
));
2682 wxMemoryInputStream
memInpStream(buf
, len
);
2683 wxPrintf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2684 while ( !memInpStream
.Eof() )
2686 wxPutchar(memInpStream
.GetC());
2689 wxPuts(_T("\n*** wxMemoryInputStream test done ***"));
2692 #endif // TEST_STREAMS
2694 // ----------------------------------------------------------------------------
2696 // ----------------------------------------------------------------------------
2700 #include "wx/timer.h"
2701 #include "wx/utils.h"
2703 static void TestStopWatch()
2705 wxPuts(_T("*** Testing wxStopWatch ***\n"));
2709 wxPrintf(_T("Initially paused, after 2 seconds time is..."));
2712 wxPrintf(_T("\t%ldms\n"), sw
.Time());
2714 wxPrintf(_T("Resuming stopwatch and sleeping 3 seconds..."));
2718 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2721 wxPrintf(_T("Pausing agan and sleeping 2 more seconds..."));
2724 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2727 wxPrintf(_T("Finally resuming and sleeping 2 more seconds..."));
2730 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2733 wxPuts(_T("\nChecking for 'backwards clock' bug..."));
2734 for ( size_t n
= 0; n
< 70; n
++ )
2738 for ( size_t m
= 0; m
< 100000; m
++ )
2740 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2742 wxPuts(_T("\ntime is negative - ERROR!"));
2750 wxPuts(_T(", ok."));
2753 #endif // TEST_TIMER
2755 // ----------------------------------------------------------------------------
2757 // ----------------------------------------------------------------------------
2761 #include "wx/vcard.h"
2763 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2766 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2769 wxPrintf(_T("%s%s"),
2770 wxString(_T('\t'), level
).c_str(),
2771 vcObj
->GetName().c_str());
2774 switch ( vcObj
->GetType() )
2776 case wxVCardObject::String
:
2777 case wxVCardObject::UString
:
2780 vcObj
->GetValue(&val
);
2781 value
<< _T('"') << val
<< _T('"');
2785 case wxVCardObject::Int
:
2788 vcObj
->GetValue(&i
);
2789 value
.Printf(_T("%u"), i
);
2793 case wxVCardObject::Long
:
2796 vcObj
->GetValue(&l
);
2797 value
.Printf(_T("%lu"), l
);
2801 case wxVCardObject::None
:
2804 case wxVCardObject::Object
:
2805 value
= _T("<node>");
2809 value
= _T("<unknown value type>");
2813 wxPrintf(_T(" = %s"), value
.c_str());
2816 DumpVObject(level
+ 1, *vcObj
);
2819 vcObj
= vcard
.GetNextProp(&cookie
);
2823 static void DumpVCardAddresses(const wxVCard
& vcard
)
2825 wxPuts(_T("\nShowing all addresses from vCard:\n"));
2829 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2833 int flags
= addr
->GetFlags();
2834 if ( flags
& wxVCardAddress::Domestic
)
2836 flagsStr
<< _T("domestic ");
2838 if ( flags
& wxVCardAddress::Intl
)
2840 flagsStr
<< _T("international ");
2842 if ( flags
& wxVCardAddress::Postal
)
2844 flagsStr
<< _T("postal ");
2846 if ( flags
& wxVCardAddress::Parcel
)
2848 flagsStr
<< _T("parcel ");
2850 if ( flags
& wxVCardAddress::Home
)
2852 flagsStr
<< _T("home ");
2854 if ( flags
& wxVCardAddress::Work
)
2856 flagsStr
<< _T("work ");
2859 wxPrintf(_T("Address %u:\n")
2861 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2864 addr
->GetPostOffice().c_str(),
2865 addr
->GetExtAddress().c_str(),
2866 addr
->GetStreet().c_str(),
2867 addr
->GetLocality().c_str(),
2868 addr
->GetRegion().c_str(),
2869 addr
->GetPostalCode().c_str(),
2870 addr
->GetCountry().c_str()
2874 addr
= vcard
.GetNextAddress(&cookie
);
2878 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2880 wxPuts(_T("\nShowing all phone numbers from vCard:\n"));
2884 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2888 int flags
= phone
->GetFlags();
2889 if ( flags
& wxVCardPhoneNumber::Voice
)
2891 flagsStr
<< _T("voice ");
2893 if ( flags
& wxVCardPhoneNumber::Fax
)
2895 flagsStr
<< _T("fax ");
2897 if ( flags
& wxVCardPhoneNumber::Cellular
)
2899 flagsStr
<< _T("cellular ");
2901 if ( flags
& wxVCardPhoneNumber::Modem
)
2903 flagsStr
<< _T("modem ");
2905 if ( flags
& wxVCardPhoneNumber::Home
)
2907 flagsStr
<< _T("home ");
2909 if ( flags
& wxVCardPhoneNumber::Work
)
2911 flagsStr
<< _T("work ");
2914 wxPrintf(_T("Phone number %u:\n")
2919 phone
->GetNumber().c_str()
2923 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2927 static void TestVCardRead()
2929 wxPuts(_T("*** Testing wxVCard reading ***\n"));
2931 wxVCard
vcard(_T("vcard.vcf"));
2932 if ( !vcard
.IsOk() )
2934 wxPuts(_T("ERROR: couldn't load vCard."));
2938 // read individual vCard properties
2939 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2943 vcObj
->GetValue(&value
);
2948 value
= _T("<none>");
2951 wxPrintf(_T("Full name retrieved directly: %s\n"), value
.c_str());
2954 if ( !vcard
.GetFullName(&value
) )
2956 value
= _T("<none>");
2959 wxPrintf(_T("Full name from wxVCard API: %s\n"), value
.c_str());
2961 // now show how to deal with multiply occuring properties
2962 DumpVCardAddresses(vcard
);
2963 DumpVCardPhoneNumbers(vcard
);
2965 // and finally show all
2966 wxPuts(_T("\nNow dumping the entire vCard:\n")
2967 "-----------------------------\n");
2969 DumpVObject(0, vcard
);
2973 static void TestVCardWrite()
2975 wxPuts(_T("*** Testing wxVCard writing ***\n"));
2978 if ( !vcard
.IsOk() )
2980 wxPuts(_T("ERROR: couldn't create vCard."));
2985 vcard
.SetName("Zeitlin", "Vadim");
2986 vcard
.SetFullName("Vadim Zeitlin");
2987 vcard
.SetOrganization("wxWidgets", "R&D");
2989 // just dump the vCard back
2990 wxPuts(_T("Entire vCard follows:\n"));
2991 wxPuts(vcard
.Write());
2995 #endif // TEST_VCARD
2997 // ----------------------------------------------------------------------------
2999 // ----------------------------------------------------------------------------
3001 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
3007 #include "wx/volume.h"
3009 static const wxChar
*volumeKinds
[] =
3015 _T("network volume"),
3019 static void TestFSVolume()
3021 wxPuts(_T("*** Testing wxFSVolume class ***"));
3023 wxArrayString volumes
= wxFSVolume::GetVolumes();
3024 size_t count
= volumes
.GetCount();
3028 wxPuts(_T("ERROR: no mounted volumes?"));
3032 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3034 for ( size_t n
= 0; n
< count
; n
++ )
3036 wxFSVolume
vol(volumes
[n
]);
3039 wxPuts(_T("ERROR: couldn't create volume"));
3043 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3045 vol
.GetDisplayName().c_str(),
3046 vol
.GetName().c_str(),
3047 volumeKinds
[vol
.GetKind()],
3048 vol
.IsWritable() ? _T("rw") : _T("ro"),
3049 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3054 #endif // TEST_VOLUME
3056 // ----------------------------------------------------------------------------
3057 // wide char and Unicode support
3058 // ----------------------------------------------------------------------------
3062 #include "wx/strconv.h"
3063 #include "wx/fontenc.h"
3064 #include "wx/encconv.h"
3065 #include "wx/buffer.h"
3067 static const unsigned char utf8koi8r
[] =
3069 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3070 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3071 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3072 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3073 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3074 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3075 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3078 static const unsigned char utf8iso8859_1
[] =
3080 0x53, 0x79, 0x73, 0x74, 0xc3, 0xa8, 0x6d, 0x65, 0x73, 0x20, 0x49, 0x6e,
3081 0x74, 0xc3, 0xa9, 0x67, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x20, 0x65,
3082 0x6e, 0x20, 0x4d, 0xc3, 0xa9, 0x63, 0x61, 0x6e, 0x69, 0x71, 0x75, 0x65,
3083 0x20, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x69, 0x71, 0x75, 0x65, 0x20, 0x65,
3084 0x74, 0x20, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x71, 0x75, 0x65, 0
3087 static const unsigned char utf8Invalid
[] =
3089 0x3c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x3e, 0x32, 0x30, 0x30,
3090 0x32, 0xe5, 0xb9, 0xb4, 0x30, 0x39, 0xe6, 0x9c, 0x88, 0x32, 0x35, 0xe6,
3091 0x97, 0xa5, 0x20, 0x30, 0x37, 0xe6, 0x99, 0x82, 0x33, 0x39, 0xe5, 0x88,
3092 0x86, 0x35, 0x37, 0xe7, 0xa7, 0x92, 0x3c, 0x2f, 0x64, 0x69, 0x73, 0x70,
3096 static const struct Utf8Data
3098 const unsigned char *text
;
3100 const wxChar
*charset
;
3101 wxFontEncoding encoding
;
3104 { utf8Invalid
, WXSIZEOF(utf8Invalid
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3105 { utf8koi8r
, WXSIZEOF(utf8koi8r
), _T("koi8-r"), wxFONTENCODING_KOI8
},
3106 { utf8iso8859_1
, WXSIZEOF(utf8iso8859_1
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3109 static void TestUtf8()
3111 wxPuts(_T("*** Testing UTF8 support ***\n"));
3116 for ( size_t n
= 0; n
< WXSIZEOF(utf8data
); n
++ )
3118 const Utf8Data
& u8d
= utf8data
[n
];
3119 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)u8d
.text
,
3120 WXSIZEOF(wbuf
)) == (size_t)-1 )
3122 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3126 wxCSConv
conv(u8d
.charset
);
3127 if ( conv
.WC2MB(buf
, wbuf
, WXSIZEOF(buf
)) == (size_t)-1 )
3129 wxPrintf(_T("ERROR: conversion to %s failed.\n"), u8d
.charset
);
3133 wxPrintf(_T("String in %s: %s\n"), u8d
.charset
, buf
);
3137 wxString
s(wxConvUTF8
.cMB2WC((const char *)u8d
.text
));
3139 s
= _T("<< conversion failed >>");
3140 wxPrintf(_T("String in current cset: %s\n"), s
.c_str());
3144 wxPuts(wxEmptyString
);
3147 static void TestEncodingConverter()
3149 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3151 // using wxEncodingConverter should give the same result as above
3154 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)utf8koi8r
,
3155 WXSIZEOF(utf8koi8r
)) == (size_t)-1 )
3157 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3161 wxEncodingConverter ec
;
3162 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3163 ec
.Convert(wbuf
, buf
);
3164 wxPrintf(_T("The same KOI8-R string using wxEC: %s\n"), buf
);
3167 wxPuts(wxEmptyString
);
3170 #endif // TEST_WCHAR
3172 // ----------------------------------------------------------------------------
3174 // ----------------------------------------------------------------------------
3178 #include "wx/filesys.h"
3179 #include "wx/fs_zip.h"
3180 #include "wx/zipstrm.h"
3182 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3184 static void TestZipStreamRead()
3186 wxPuts(_T("*** Testing ZIP reading ***\n"));
3188 static const wxString filename
= _T("foo");
3189 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3190 wxPrintf(_T("Archive size: %u\n"), istr
.GetSize());
3192 wxPrintf(_T("Dumping the file '%s':\n"), filename
.c_str());
3193 while ( !istr
.Eof() )
3195 wxPutchar(istr
.GetC());
3199 wxPuts(_T("\n----- done ------"));
3202 static void DumpZipDirectory(wxFileSystem
& fs
,
3203 const wxString
& dir
,
3204 const wxString
& indent
)
3206 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3207 TESTFILE_ZIP
, dir
.c_str());
3208 wxString wildcard
= prefix
+ _T("/*");
3210 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3211 while ( !dirname
.empty() )
3213 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3215 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3220 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3222 DumpZipDirectory(fs
, dirname
,
3223 indent
+ wxString(_T(' '), 4));
3225 dirname
= fs
.FindNext();
3228 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3229 while ( !filename
.empty() )
3231 if ( !filename
.StartsWith(prefix
, &filename
) )
3233 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3238 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3240 filename
= fs
.FindNext();
3244 static void TestZipFileSystem()
3246 wxPuts(_T("*** Testing ZIP file system ***\n"));
3248 wxFileSystem::AddHandler(new wxZipFSHandler
);
3250 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3252 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3257 // ----------------------------------------------------------------------------
3259 // ----------------------------------------------------------------------------
3261 #ifdef TEST_DATETIME
3265 #include "wx/datetime.h"
3267 // this test miscellaneous static wxDateTime functions
3271 static void TestTimeStatic()
3273 wxPuts(_T("\n*** wxDateTime static methods test ***"));
3275 // some info about the current date
3276 int year
= wxDateTime::GetCurrentYear();
3277 wxPrintf(_T("Current year %d is %sa leap one and has %d days.\n"),
3279 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3280 wxDateTime::GetNumberOfDays(year
));
3282 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3283 wxPrintf(_T("Current month is '%s' ('%s') and it has %d days\n"),
3284 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3285 wxDateTime::GetMonthName(month
).c_str(),
3286 wxDateTime::GetNumberOfDays(month
));
3289 // test time zones stuff
3290 static void TestTimeZones()
3292 wxPuts(_T("\n*** wxDateTime timezone test ***"));
3294 wxDateTime now
= wxDateTime::Now();
3296 wxPrintf(_T("Current GMT time:\t%s\n"), now
.Format(_T("%c"), wxDateTime::GMT0
).c_str());
3297 wxPrintf(_T("Unix epoch (GMT):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::GMT0
).c_str());
3298 wxPrintf(_T("Unix epoch (EST):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::EST
).c_str());
3299 wxPrintf(_T("Current time in Paris:\t%s\n"), now
.Format(_T("%c"), wxDateTime::CET
).c_str());
3300 wxPrintf(_T(" Moscow:\t%s\n"), now
.Format(_T("%c"), wxDateTime::MSK
).c_str());
3301 wxPrintf(_T(" New York:\t%s\n"), now
.Format(_T("%c"), wxDateTime::EST
).c_str());
3303 wxPrintf(_T("%s\n"), wxDateTime::Now().Format(_T("Our timezone is %Z")).c_str());
3305 wxDateTime::Tm tm
= now
.GetTm();
3306 if ( wxDateTime(tm
) != now
)
3308 wxPrintf(_T("ERROR: got %s instead of %s\n"),
3309 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3313 // test some minimal support for the dates outside the standard range
3314 static void TestTimeRange()
3316 wxPuts(_T("\n*** wxDateTime out-of-standard-range dates test ***"));
3318 static const wxChar
*fmt
= _T("%d-%b-%Y %H:%M:%S");
3320 wxPrintf(_T("Unix epoch:\t%s\n"),
3321 wxDateTime(2440587.5).Format(fmt
).c_str());
3322 wxPrintf(_T("Feb 29, 0: \t%s\n"),
3323 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3324 wxPrintf(_T("JDN 0: \t%s\n"),
3325 wxDateTime(0.0).Format(fmt
).c_str());
3326 wxPrintf(_T("Jan 1, 1AD:\t%s\n"),
3327 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3328 wxPrintf(_T("May 29, 2099:\t%s\n"),
3329 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3332 // test DST calculations
3333 static void TestTimeDST()
3335 wxPuts(_T("\n*** wxDateTime DST test ***"));
3337 wxPrintf(_T("DST is%s in effect now.\n\n"),
3338 wxDateTime::Now().IsDST() ? wxEmptyString
: _T(" not"));
3340 for ( int year
= 1990; year
< 2005; year
++ )
3342 wxPrintf(_T("DST period in Europe for year %d: from %s to %s\n"),
3344 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3345 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3351 #if TEST_INTERACTIVE
3353 static void TestDateTimeInteractive()
3355 wxPuts(_T("\n*** interactive wxDateTime tests ***"));
3361 wxPrintf(_T("Enter a date: "));
3362 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
3365 // kill the last '\n'
3366 buf
[wxStrlen(buf
) - 1] = 0;
3369 const wxChar
*p
= dt
.ParseDate(buf
);
3372 wxPrintf(_T("ERROR: failed to parse the date '%s'.\n"), buf
);
3378 wxPrintf(_T("WARNING: parsed only first %u characters.\n"), p
- buf
);
3381 wxPrintf(_T("%s: day %u, week of month %u/%u, week of year %u\n"),
3382 dt
.Format(_T("%b %d, %Y")).c_str(),
3384 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3385 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3386 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3389 wxPuts(_T("\n*** done ***"));
3392 #endif // TEST_INTERACTIVE
3396 static void TestTimeMS()
3398 wxPuts(_T("*** testing millisecond-resolution support in wxDateTime ***"));
3400 wxDateTime dt1
= wxDateTime::Now(),
3401 dt2
= wxDateTime::UNow();
3403 wxPrintf(_T("Now = %s\n"), dt1
.Format(_T("%H:%M:%S:%l")).c_str());
3404 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
3405 wxPrintf(_T("Dummy loop: "));
3406 for ( int i
= 0; i
< 6000; i
++ )
3408 //for ( int j = 0; j < 10; j++ )
3411 s
.Printf(_T("%g"), sqrt((float)i
));
3417 wxPuts(_T(", done"));
3420 dt2
= wxDateTime::UNow();
3421 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
3423 wxPrintf(_T("Loop executed in %s ms\n"), (dt2
- dt1
).Format(_T("%l")).c_str());
3425 wxPuts(_T("\n*** done ***"));
3428 static void TestTimeHolidays()
3430 wxPuts(_T("\n*** testing wxDateTimeHolidayAuthority ***\n"));
3432 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3433 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3434 dtEnd
= dtStart
.GetLastMonthDay();
3436 wxDateTimeArray hol
;
3437 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3439 const wxChar
*format
= _T("%d-%b-%Y (%a)");
3441 wxPrintf(_T("All holidays between %s and %s:\n"),
3442 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3444 size_t count
= hol
.GetCount();
3445 for ( size_t n
= 0; n
< count
; n
++ )
3447 wxPrintf(_T("\t%s\n"), hol
[n
].Format(format
).c_str());
3450 wxPuts(wxEmptyString
);
3453 static void TestTimeZoneBug()
3455 wxPuts(_T("\n*** testing for DST/timezone bug ***\n"));
3457 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3458 for ( int i
= 0; i
< 31; i
++ )
3460 wxPrintf(_T("Date %s: week day %s.\n"),
3461 date
.Format(_T("%d-%m-%Y")).c_str(),
3462 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3464 date
+= wxDateSpan::Day();
3467 wxPuts(wxEmptyString
);
3470 static void TestTimeSpanFormat()
3472 wxPuts(_T("\n*** wxTimeSpan tests ***"));
3474 static const wxChar
*formats
[] =
3476 _T("(default) %H:%M:%S"),
3477 _T("%E weeks and %D days"),
3478 _T("%l milliseconds"),
3479 _T("(with ms) %H:%M:%S:%l"),
3480 _T("100%% of minutes is %M"), // test "%%"
3481 _T("%D days and %H hours"),
3482 _T("or also %S seconds"),
3485 wxTimeSpan
ts1(1, 2, 3, 4),
3487 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3489 wxPrintf(_T("ts1 = %s\tts2 = %s\n"),
3490 ts1
.Format(formats
[n
]).c_str(),
3491 ts2
.Format(formats
[n
]).c_str());
3494 wxPuts(wxEmptyString
);
3499 #endif // TEST_DATETIME
3501 // ----------------------------------------------------------------------------
3502 // wxTextInput/OutputStream
3503 // ----------------------------------------------------------------------------
3505 #ifdef TEST_TEXTSTREAM
3507 #include "wx/txtstrm.h"
3508 #include "wx/wfstream.h"
3510 static void TestTextInputStream()
3512 wxPuts(_T("\n*** wxTextInputStream test ***"));
3514 wxString filename
= _T("testdata.fc");
3515 wxFileInputStream
fsIn(filename
);
3518 wxPuts(_T("ERROR: couldn't open file."));
3522 wxTextInputStream
tis(fsIn
);
3527 const wxString s
= tis
.ReadLine();
3529 // line could be non empty if the last line of the file isn't
3530 // terminated with EOL
3531 if ( fsIn
.Eof() && s
.empty() )
3534 wxPrintf(_T("Line %d: %s\n"), line
++, s
.c_str());
3539 #endif // TEST_TEXTSTREAM
3541 // ----------------------------------------------------------------------------
3543 // ----------------------------------------------------------------------------
3547 #include "wx/thread.h"
3549 static size_t gs_counter
= (size_t)-1;
3550 static wxCriticalSection gs_critsect
;
3551 static wxSemaphore gs_cond
;
3553 class MyJoinableThread
: public wxThread
3556 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3557 { m_n
= n
; Create(); }
3559 // thread execution starts here
3560 virtual ExitCode
Entry();
3566 wxThread::ExitCode
MyJoinableThread::Entry()
3568 unsigned long res
= 1;
3569 for ( size_t n
= 1; n
< m_n
; n
++ )
3573 // it's a loooong calculation :-)
3577 return (ExitCode
)res
;
3580 class MyDetachedThread
: public wxThread
3583 MyDetachedThread(size_t n
, wxChar ch
)
3587 m_cancelled
= false;
3592 // thread execution starts here
3593 virtual ExitCode
Entry();
3596 virtual void OnExit();
3599 size_t m_n
; // number of characters to write
3600 wxChar m_ch
; // character to write
3602 bool m_cancelled
; // false if we exit normally
3605 wxThread::ExitCode
MyDetachedThread::Entry()
3608 wxCriticalSectionLocker
lock(gs_critsect
);
3609 if ( gs_counter
== (size_t)-1 )
3615 for ( size_t n
= 0; n
< m_n
; n
++ )
3617 if ( TestDestroy() )
3627 wxThread::Sleep(100);
3633 void MyDetachedThread::OnExit()
3635 wxLogTrace(_T("thread"), _T("Thread %ld is in OnExit"), GetId());
3637 wxCriticalSectionLocker
lock(gs_critsect
);
3638 if ( !--gs_counter
&& !m_cancelled
)
3642 static void TestDetachedThreads()
3644 wxPuts(_T("\n*** Testing detached threads ***"));
3646 static const size_t nThreads
= 3;
3647 MyDetachedThread
*threads
[nThreads
];
3649 for ( n
= 0; n
< nThreads
; n
++ )
3651 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3654 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3655 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3657 for ( n
= 0; n
< nThreads
; n
++ )
3662 // wait until all threads terminate
3665 wxPuts(wxEmptyString
);
3668 static void TestJoinableThreads()
3670 wxPuts(_T("\n*** Testing a joinable thread (a loooong calculation...) ***"));
3672 // calc 10! in the background
3673 MyJoinableThread
thread(10);
3676 wxPrintf(_T("\nThread terminated with exit code %lu.\n"),
3677 (unsigned long)thread
.Wait());
3680 static void TestThreadSuspend()
3682 wxPuts(_T("\n*** Testing thread suspend/resume functions ***"));
3684 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3688 // this is for this demo only, in a real life program we'd use another
3689 // condition variable which would be signaled from wxThread::Entry() to
3690 // tell us that the thread really started running - but here just wait a
3691 // bit and hope that it will be enough (the problem is, of course, that
3692 // the thread might still not run when we call Pause() which will result
3694 wxThread::Sleep(300);
3696 for ( size_t n
= 0; n
< 3; n
++ )
3700 wxPuts(_T("\nThread suspended"));
3703 // don't sleep but resume immediately the first time
3704 wxThread::Sleep(300);
3706 wxPuts(_T("Going to resume the thread"));
3711 wxPuts(_T("Waiting until it terminates now"));
3713 // wait until the thread terminates
3716 wxPuts(wxEmptyString
);
3719 static void TestThreadDelete()
3721 // As above, using Sleep() is only for testing here - we must use some
3722 // synchronisation object instead to ensure that the thread is still
3723 // running when we delete it - deleting a detached thread which already
3724 // terminated will lead to a crash!
3726 wxPuts(_T("\n*** Testing thread delete function ***"));
3728 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3732 wxPuts(_T("\nDeleted a thread which didn't start to run yet."));
3734 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3738 wxThread::Sleep(300);
3742 wxPuts(_T("\nDeleted a running thread."));
3744 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3748 wxThread::Sleep(300);
3754 wxPuts(_T("\nDeleted a sleeping thread."));
3756 MyJoinableThread
thread3(20);
3761 wxPuts(_T("\nDeleted a joinable thread."));
3763 MyJoinableThread
thread4(2);
3766 wxThread::Sleep(300);
3770 wxPuts(_T("\nDeleted a joinable thread which already terminated."));
3772 wxPuts(wxEmptyString
);
3775 class MyWaitingThread
: public wxThread
3778 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
3781 m_condition
= condition
;
3786 virtual ExitCode
Entry()
3788 wxPrintf(_T("Thread %lu has started running.\n"), GetId());
3793 wxPrintf(_T("Thread %lu starts to wait...\n"), GetId());
3797 m_condition
->Wait();
3800 wxPrintf(_T("Thread %lu finished to wait, exiting.\n"), GetId());
3808 wxCondition
*m_condition
;
3811 static void TestThreadConditions()
3814 wxCondition
condition(mutex
);
3816 // otherwise its difficult to understand which log messages pertain to
3818 //wxLogTrace(_T("thread"), _T("Local condition var is %08x, gs_cond = %08x"),
3819 // condition.GetId(), gs_cond.GetId());
3821 // create and launch threads
3822 MyWaitingThread
*threads
[10];
3825 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
3827 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
3830 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
3835 // wait until all threads run
3836 wxPuts(_T("Main thread is waiting for the other threads to start"));
3839 size_t nRunning
= 0;
3840 while ( nRunning
< WXSIZEOF(threads
) )
3846 wxPrintf(_T("Main thread: %u already running\n"), nRunning
);
3850 wxPuts(_T("Main thread: all threads started up."));
3853 wxThread::Sleep(500);
3856 // now wake one of them up
3857 wxPrintf(_T("Main thread: about to signal the condition.\n"));
3862 wxThread::Sleep(200);
3864 // wake all the (remaining) threads up, so that they can exit
3865 wxPrintf(_T("Main thread: about to broadcast the condition.\n"));
3867 condition
.Broadcast();
3869 // give them time to terminate (dirty!)
3870 wxThread::Sleep(500);
3873 #include "wx/utils.h"
3875 class MyExecThread
: public wxThread
3878 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
3884 virtual ExitCode
Entry()
3886 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
3893 static void TestThreadExec()
3895 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
3897 MyExecThread
thread(_T("true"));
3900 wxPrintf(_T("Main program exit code: %ld.\n"),
3901 wxExecute(_T("false"), wxEXEC_SYNC
));
3903 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
3907 #include "wx/datetime.h"
3909 class MySemaphoreThread
: public wxThread
3912 MySemaphoreThread(int i
, wxSemaphore
*sem
)
3913 : wxThread(wxTHREAD_JOINABLE
),
3920 virtual ExitCode
Entry()
3922 wxPrintf(_T("%s: Thread #%d (%ld) starting to wait for semaphore...\n"),
3923 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
3927 wxPrintf(_T("%s: Thread #%d (%ld) acquired the semaphore.\n"),
3928 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
3932 wxPrintf(_T("%s: Thread #%d (%ld) releasing the semaphore.\n"),
3933 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
3945 WX_DEFINE_ARRAY_PTR(wxThread
*, ArrayThreads
);
3947 static void TestSemaphore()
3949 wxPuts(_T("*** Testing wxSemaphore class. ***"));
3951 static const int SEM_LIMIT
= 3;
3953 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
3954 ArrayThreads threads
;
3956 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
3958 threads
.Add(new MySemaphoreThread(i
, &sem
));
3959 threads
.Last()->Run();
3962 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
3969 #endif // TEST_THREADS
3971 // ----------------------------------------------------------------------------
3973 // ----------------------------------------------------------------------------
3975 #ifdef TEST_SNGLINST
3976 #include "wx/snglinst.h"
3977 #endif // TEST_SNGLINST
3979 int main(int argc
, char **argv
)
3981 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "program");
3983 wxInitializer initializer
;
3986 fprintf(stderr
, "Failed to initialize the wxWidgets library, aborting.");
3991 #ifdef TEST_SNGLINST
3992 wxSingleInstanceChecker checker
;
3993 if ( checker
.Create(_T(".wxconsole.lock")) )
3995 if ( checker
.IsAnotherRunning() )
3997 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4002 // wait some time to give time to launch another instance
4003 wxPrintf(_T("Press \"Enter\" to continue..."));
4006 else // failed to create
4008 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4010 #endif // TEST_SNGLINST
4013 TestCmdLineConvert();
4015 #if wxUSE_CMDLINE_PARSER
4016 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4018 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), _T("show this help message"),
4019 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
4020 { wxCMD_LINE_SWITCH
, _T("v"), _T("verbose"), _T("be verbose") },
4021 { wxCMD_LINE_SWITCH
, _T("q"), _T("quiet"), _T("be quiet") },
4023 { wxCMD_LINE_OPTION
, _T("o"), _T("output"), _T("output file") },
4024 { wxCMD_LINE_OPTION
, _T("i"), _T("input"), _T("input dir") },
4025 { wxCMD_LINE_OPTION
, _T("s"), _T("size"), _T("output block size"),
4026 wxCMD_LINE_VAL_NUMBER
},
4027 { wxCMD_LINE_OPTION
, _T("d"), _T("date"), _T("output file date"),
4028 wxCMD_LINE_VAL_DATE
},
4030 { wxCMD_LINE_PARAM
, NULL
, NULL
, _T("input file"),
4031 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4037 wxChar
**wargv
= new wxChar
*[argc
+ 1];
4042 for (n
= 0; n
< argc
; n
++ )
4044 wxMB2WXbuf warg
= wxConvertMB2WX(argv
[n
]);
4045 wargv
[n
] = wxStrdup(warg
);
4052 #endif // wxUSE_UNICODE
4054 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4058 for ( int n
= 0; n
< argc
; n
++ )
4063 #endif // wxUSE_UNICODE
4065 parser
.AddOption(_T("project_name"), _T(""), _T("full path to project file"),
4066 wxCMD_LINE_VAL_STRING
,
4067 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4069 switch ( parser
.Parse() )
4072 wxLogMessage(_T("Help was given, terminating."));
4076 ShowCmdLine(parser
);
4080 wxLogMessage(_T("Syntax error detected, aborting."));
4083 #endif // wxUSE_CMDLINE_PARSER
4085 #endif // TEST_CMDLINE
4095 #ifdef TEST_DLLLOADER
4097 #endif // TEST_DLLLOADER
4101 #endif // TEST_ENVIRON
4105 #endif // TEST_EXECUTE
4107 #ifdef TEST_FILECONF
4109 #endif // TEST_FILECONF
4113 #endif // TEST_LOCALE
4116 wxPuts(_T("*** Testing wxLog ***"));
4119 for ( size_t n
= 0; n
< 8000; n
++ )
4121 s
<< (wxChar
)(_T('A') + (n
% 26));
4124 wxLogWarning(_T("The length of the string is %lu"),
4125 (unsigned long)s
.length());
4128 msg
.Printf(_T("A very very long message: '%s', the end!\n"), s
.c_str());
4130 // this one shouldn't be truncated
4133 // but this one will because log functions use fixed size buffer
4134 // (note that it doesn't need '\n' at the end neither - will be added
4136 wxLogMessage(_T("A very very long message 2: '%s', the end!"), s
.c_str());
4145 #ifdef TEST_FILENAME
4146 TestFileNameConstruction();
4147 TestFileNameMakeRelative();
4148 TestFileNameMakeAbsolute();
4149 TestFileNameSplit();
4152 TestFileNameDirManip();
4153 TestFileNameComparison();
4154 TestFileNameOperations();
4155 #endif // TEST_FILENAME
4157 #ifdef TEST_FILETIME
4162 #endif // TEST_FILETIME
4165 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4166 if ( TestFtpConnect() )
4176 #if TEST_INTERACTIVE
4177 TestFtpInteractive();
4180 //else: connecting to the FTP server failed
4188 wxLog::AddTraceMask(_T("mime"));
4192 TestMimeAssociate();
4197 #ifdef TEST_INFO_FUNCTIONS
4202 #if TEST_INTERACTIVE
4206 #endif // TEST_INFO_FUNCTIONS
4208 #ifdef TEST_PATHLIST
4210 #endif // TEST_PATHLIST
4218 #endif // TEST_PRINTF
4225 #endif // TEST_REGCONF
4227 #if defined TEST_REGEX && TEST_INTERACTIVE
4228 TestRegExInteractive();
4229 #endif // defined TEST_REGEX && TEST_INTERACTIVE
4231 #ifdef TEST_REGISTRY
4233 TestRegistryAssociation();
4234 #endif // TEST_REGISTRY
4239 #endif // TEST_SOCKETS
4246 #endif // TEST_STREAMS
4248 #ifdef TEST_TEXTSTREAM
4249 TestTextInputStream();
4250 #endif // TEST_TEXTSTREAM
4253 int nCPUs
= wxThread::GetCPUCount();
4254 wxPrintf(_T("This system has %d CPUs\n"), nCPUs
);
4256 wxThread::SetConcurrency(nCPUs
);
4258 TestJoinableThreads();
4261 TestJoinableThreads();
4262 TestDetachedThreads();
4263 TestThreadSuspend();
4265 TestThreadConditions();
4269 #endif // TEST_THREADS
4273 #endif // TEST_TIMER
4275 #ifdef TEST_DATETIME
4287 TestTimeArithmetics();
4289 TestTimeSpanFormat();
4295 #if TEST_INTERACTIVE
4296 TestDateTimeInteractive();
4298 #endif // TEST_DATETIME
4300 #ifdef TEST_SCOPEGUARD
4304 #ifdef TEST_STDPATHS
4305 TestStandardPaths();
4309 wxPuts(_T("Sleeping for 3 seconds... z-z-z-z-z..."));
4311 #endif // TEST_USLEEP
4316 #endif // TEST_VCARD
4320 #endif // TEST_VOLUME
4324 TestEncodingConverter();
4325 #endif // TEST_WCHAR
4328 TestZipStreamRead();
4329 TestZipFileSystem();