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)
87 #define TEST_DLLLOADER
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.so.6");
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 wxPrintf(_T("Calling %s dynamically loaded from %s "),
410 FUNC_NAME
, LIB_NAME
);
412 if ( pfnStrlen("foo") != 3 )
414 wxPrintf(_T("ERROR: loaded function is not wxStrlen()!\n"));
418 wxPuts(_T("... ok"));
424 #endif // TEST_DLLLOADER
426 // ----------------------------------------------------------------------------
428 // ----------------------------------------------------------------------------
432 #include "wx/utils.h"
434 static wxString
MyGetEnv(const wxString
& var
)
437 if ( !wxGetEnv(var
, &val
) )
440 val
= wxString(_T('\'')) + val
+ _T('\'');
445 static void TestEnvironment()
447 const wxChar
*var
= _T("wxTestVar");
449 wxPuts(_T("*** testing environment access functions ***"));
451 wxPrintf(_T("Initially getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
452 wxSetEnv(var
, _T("value for wxTestVar"));
453 wxPrintf(_T("After wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
454 wxSetEnv(var
, _T("another value"));
455 wxPrintf(_T("After 2nd wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
457 wxPrintf(_T("After wxUnsetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
458 wxPrintf(_T("PATH = %s\n"), MyGetEnv(_T("PATH")).c_str());
461 #endif // TEST_ENVIRON
463 // ----------------------------------------------------------------------------
465 // ----------------------------------------------------------------------------
469 #include "wx/utils.h"
471 static void TestExecute()
473 wxPuts(_T("*** testing wxExecute ***"));
476 #define COMMAND "cat -n ../../Makefile" // "echo hi"
477 #define SHELL_COMMAND "echo hi from shell"
478 #define REDIRECT_COMMAND COMMAND // "date"
479 #elif defined(__WXMSW__)
480 #define COMMAND "command.com /c echo hi"
481 #define SHELL_COMMAND "echo hi"
482 #define REDIRECT_COMMAND COMMAND
484 #error "no command to exec"
487 wxPrintf(_T("Testing wxShell: "));
489 if ( wxShell(_T(SHELL_COMMAND
)) )
492 wxPuts(_T("ERROR."));
494 wxPrintf(_T("Testing wxExecute: "));
496 if ( wxExecute(_T(COMMAND
), true /* sync */) == 0 )
499 wxPuts(_T("ERROR."));
501 #if 0 // no, it doesn't work (yet?)
502 wxPrintf(_T("Testing async wxExecute: "));
504 if ( wxExecute(COMMAND
) != 0 )
505 wxPuts(_T("Ok (command launched)."));
507 wxPuts(_T("ERROR."));
510 wxPrintf(_T("Testing wxExecute with redirection:\n"));
511 wxArrayString output
;
512 if ( wxExecute(_T(REDIRECT_COMMAND
), output
) != 0 )
514 wxPuts(_T("ERROR."));
518 size_t count
= output
.GetCount();
519 for ( size_t n
= 0; n
< count
; n
++ )
521 wxPrintf(_T("\t%s\n"), output
[n
].c_str());
528 #endif // TEST_EXECUTE
530 // ----------------------------------------------------------------------------
532 // ----------------------------------------------------------------------------
537 #include "wx/ffile.h"
538 #include "wx/textfile.h"
540 static void TestFileRead()
542 wxPuts(_T("*** wxFile read test ***"));
544 wxFile
file(_T("testdata.fc"));
545 if ( file
.IsOpened() )
547 wxPrintf(_T("File length: %lu\n"), file
.Length());
549 wxPuts(_T("File dump:\n----------"));
551 static const size_t len
= 1024;
555 size_t nRead
= file
.Read(buf
, len
);
556 if ( nRead
== (size_t)wxInvalidOffset
)
558 wxPrintf(_T("Failed to read the file."));
562 fwrite(buf
, nRead
, 1, stdout
);
568 wxPuts(_T("----------"));
572 wxPrintf(_T("ERROR: can't open test file.\n"));
575 wxPuts(wxEmptyString
);
578 static void TestTextFileRead()
580 wxPuts(_T("*** wxTextFile read test ***"));
582 wxTextFile
file(_T("testdata.fc"));
585 wxPrintf(_T("Number of lines: %u\n"), file
.GetLineCount());
586 wxPrintf(_T("Last line: '%s'\n"), file
.GetLastLine().c_str());
590 wxPuts(_T("\nDumping the entire file:"));
591 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
593 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
595 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
597 wxPuts(_T("\nAnd now backwards:"));
598 for ( s
= file
.GetLastLine();
599 file
.GetCurrentLine() != 0;
600 s
= file
.GetPrevLine() )
602 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
604 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
608 wxPrintf(_T("ERROR: can't open '%s'\n"), file
.GetName());
611 wxPuts(wxEmptyString
);
614 static void TestFileCopy()
616 wxPuts(_T("*** Testing wxCopyFile ***"));
618 static const wxChar
*filename1
= _T("testdata.fc");
619 static const wxChar
*filename2
= _T("test2");
620 if ( !wxCopyFile(filename1
, filename2
) )
622 wxPuts(_T("ERROR: failed to copy file"));
626 wxFFile
f1(filename1
, _T("rb")),
627 f2(filename2
, _T("rb"));
629 if ( !f1
.IsOpened() || !f2
.IsOpened() )
631 wxPuts(_T("ERROR: failed to open file(s)"));
636 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
638 wxPuts(_T("ERROR: failed to read file(s)"));
642 if ( (s1
.length() != s2
.length()) ||
643 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
645 wxPuts(_T("ERROR: copy error!"));
649 wxPuts(_T("File was copied ok."));
655 if ( !wxRemoveFile(filename2
) )
657 wxPuts(_T("ERROR: failed to remove the file"));
660 wxPuts(wxEmptyString
);
665 // ----------------------------------------------------------------------------
667 // ----------------------------------------------------------------------------
671 #include "wx/confbase.h"
672 #include "wx/fileconf.h"
674 static const struct FileConfTestData
676 const wxChar
*name
; // value name
677 const wxChar
*value
; // the value from the file
680 { _T("value1"), _T("one") },
681 { _T("value2"), _T("two") },
682 { _T("novalue"), _T("default") },
685 static void TestFileConfRead()
687 wxPuts(_T("*** testing wxFileConfig loading/reading ***"));
689 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
690 _T("testdata.fc"), wxEmptyString
,
691 wxCONFIG_USE_RELATIVE_PATH
);
693 // test simple reading
694 wxPuts(_T("\nReading config file:"));
695 wxString
defValue(_T("default")), value
;
696 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
698 const FileConfTestData
& data
= fcTestData
[n
];
699 value
= fileconf
.Read(data
.name
, defValue
);
700 wxPrintf(_T("\t%s = %s "), data
.name
, value
.c_str());
701 if ( value
== data
.value
)
707 wxPrintf(_T("(ERROR: should be %s)\n"), data
.value
);
711 // test enumerating the entries
712 wxPuts(_T("\nEnumerating all root entries:"));
715 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
718 wxPrintf(_T("\t%s = %s\n"),
720 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
722 cont
= fileconf
.GetNextEntry(name
, dummy
);
725 static const wxChar
*testEntry
= _T("TestEntry");
726 wxPrintf(_T("\nTesting deletion of newly created \"Test\" entry: "));
727 fileconf
.Write(testEntry
, _T("A value"));
728 fileconf
.DeleteEntry(testEntry
);
729 wxPrintf(fileconf
.HasEntry(testEntry
) ? _T("ERROR\n") : _T("ok\n"));
732 #endif // TEST_FILECONF
734 // ----------------------------------------------------------------------------
736 // ----------------------------------------------------------------------------
740 #include "wx/filename.h"
743 static void DumpFileName(const wxChar
*desc
, const wxFileName
& fn
)
747 wxString full
= fn
.GetFullPath();
749 wxString vol
, path
, name
, ext
;
750 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
752 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
753 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
755 wxFileName::SplitPath(full
, &path
, &name
, &ext
);
756 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
757 path
.c_str(), name
.c_str(), ext
.c_str());
759 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
760 wxPrintf(_T("with volume: \t'%s'\n"),
761 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
762 wxPrintf(_T("with separator:\t'%s'\n"),
763 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
764 wxPrintf(_T("with both: \t'%s'\n"),
765 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
767 wxPuts(_T("The directories in the path are:"));
768 wxArrayString dirs
= fn
.GetDirs();
769 size_t count
= dirs
.GetCount();
770 for ( size_t n
= 0; n
< count
; n
++ )
772 wxPrintf(_T("\t%u: %s\n"), n
, dirs
[n
].c_str());
777 static void TestFileNameTemp()
779 wxPuts(_T("*** testing wxFileName temp file creation ***"));
781 static const wxChar
*tmpprefixes
[] =
789 _T("/tmp/foo/bar"), // this one must be an error
793 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
795 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
798 // "error" is not in upper case because it may be ok
799 wxPrintf(_T("Prefix '%s'\t-> error\n"), tmpprefixes
[n
]);
803 wxPrintf(_T("Prefix '%s'\t-> temp file '%s'\n"),
804 tmpprefixes
[n
], path
.c_str());
806 if ( !wxRemoveFile(path
) )
808 wxLogWarning(_T("Failed to remove temp file '%s'"),
815 static void TestFileNameMakeRelative()
817 wxPuts(_T("*** testing wxFileName::MakeRelativeTo() ***"));
819 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
821 const FileNameInfo
& fni
= filenames
[n
];
823 wxFileName
fn(fni
.fullname
, fni
.format
);
825 // choose the base dir of the same format
827 switch ( fni
.format
)
830 base
= _T("/usr/bin/");
839 // TODO: I don't know how this is supposed to work there
842 case wxPATH_NATIVE
: // make gcc happy
844 wxFAIL_MSG( _T("unexpected path format") );
847 wxPrintf(_T("'%s' relative to '%s': "),
848 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
850 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
852 wxPuts(_T("unchanged"));
856 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
861 static void TestFileNameMakeAbsolute()
863 wxPuts(_T("*** testing wxFileName::MakeAbsolute() ***"));
865 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
867 const FileNameInfo
& fni
= filenames
[n
];
868 wxFileName
fn(fni
.fullname
, fni
.format
);
870 wxPrintf(_T("'%s' absolutized: "),
871 fn
.GetFullPath(fni
.format
).c_str());
873 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
876 wxPuts(wxEmptyString
);
879 static void TestFileNameDirManip()
881 // TODO: test AppendDir(), RemoveDir(), ...
884 static void TestFileNameComparison()
889 static void TestFileNameOperations()
894 static void TestFileNameCwd()
899 #endif // TEST_FILENAME
901 // ----------------------------------------------------------------------------
902 // wxFileName time functions
903 // ----------------------------------------------------------------------------
907 #include <wx/filename.h>
908 #include <wx/datetime.h>
910 static void TestFileGetTimes()
912 wxFileName
fn(_T("testdata.fc"));
914 wxDateTime dtAccess
, dtMod
, dtCreate
;
915 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
917 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
921 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
923 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
924 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
925 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
926 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
931 static void TestFileSetTimes()
933 wxFileName
fn(_T("testdata.fc"));
937 wxPrintf(_T("ERROR: Touch() failed.\n"));
942 #endif // TEST_FILETIME
944 // ----------------------------------------------------------------------------
946 // ----------------------------------------------------------------------------
951 #include "wx/utils.h" // for wxSetEnv
953 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
955 // find the name of the language from its value
956 static const wxChar
*GetLangName(int lang
)
958 static const wxChar
*languageNames
[] =
968 _T("ARABIC_ALGERIA"),
969 _T("ARABIC_BAHRAIN"),
974 _T("ARABIC_LEBANON"),
976 _T("ARABIC_MOROCCO"),
979 _T("ARABIC_SAUDI_ARABIA"),
982 _T("ARABIC_TUNISIA"),
989 _T("AZERI_CYRILLIC"),
1004 _T("CHINESE_SIMPLIFIED"),
1005 _T("CHINESE_TRADITIONAL"),
1006 _T("CHINESE_HONGKONG"),
1007 _T("CHINESE_MACAU"),
1008 _T("CHINESE_SINGAPORE"),
1009 _T("CHINESE_TAIWAN"),
1015 _T("DUTCH_BELGIAN"),
1019 _T("ENGLISH_AUSTRALIA"),
1020 _T("ENGLISH_BELIZE"),
1021 _T("ENGLISH_BOTSWANA"),
1022 _T("ENGLISH_CANADA"),
1023 _T("ENGLISH_CARIBBEAN"),
1024 _T("ENGLISH_DENMARK"),
1026 _T("ENGLISH_JAMAICA"),
1027 _T("ENGLISH_NEW_ZEALAND"),
1028 _T("ENGLISH_PHILIPPINES"),
1029 _T("ENGLISH_SOUTH_AFRICA"),
1030 _T("ENGLISH_TRINIDAD"),
1031 _T("ENGLISH_ZIMBABWE"),
1039 _T("FRENCH_BELGIAN"),
1040 _T("FRENCH_CANADIAN"),
1041 _T("FRENCH_LUXEMBOURG"),
1042 _T("FRENCH_MONACO"),
1048 _T("GERMAN_AUSTRIAN"),
1049 _T("GERMAN_BELGIUM"),
1050 _T("GERMAN_LIECHTENSTEIN"),
1051 _T("GERMAN_LUXEMBOURG"),
1069 _T("ITALIAN_SWISS"),
1074 _T("KASHMIRI_INDIA"),
1092 _T("MALAY_BRUNEI_DARUSSALAM"),
1093 _T("MALAY_MALAYSIA"),
1103 _T("NORWEGIAN_BOKMAL"),
1104 _T("NORWEGIAN_NYNORSK"),
1111 _T("PORTUGUESE_BRAZILIAN"),
1114 _T("RHAETO_ROMANCE"),
1117 _T("RUSSIAN_UKRAINE"),
1123 _T("SERBIAN_CYRILLIC"),
1124 _T("SERBIAN_LATIN"),
1125 _T("SERBO_CROATIAN"),
1136 _T("SPANISH_ARGENTINA"),
1137 _T("SPANISH_BOLIVIA"),
1138 _T("SPANISH_CHILE"),
1139 _T("SPANISH_COLOMBIA"),
1140 _T("SPANISH_COSTA_RICA"),
1141 _T("SPANISH_DOMINICAN_REPUBLIC"),
1142 _T("SPANISH_ECUADOR"),
1143 _T("SPANISH_EL_SALVADOR"),
1144 _T("SPANISH_GUATEMALA"),
1145 _T("SPANISH_HONDURAS"),
1146 _T("SPANISH_MEXICAN"),
1147 _T("SPANISH_MODERN"),
1148 _T("SPANISH_NICARAGUA"),
1149 _T("SPANISH_PANAMA"),
1150 _T("SPANISH_PARAGUAY"),
1152 _T("SPANISH_PUERTO_RICO"),
1153 _T("SPANISH_URUGUAY"),
1155 _T("SPANISH_VENEZUELA"),
1159 _T("SWEDISH_FINLAND"),
1177 _T("URDU_PAKISTAN"),
1179 _T("UZBEK_CYRILLIC"),
1192 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1193 return languageNames
[lang
];
1195 return _T("INVALID");
1198 static void TestDefaultLang()
1200 wxPuts(_T("*** Testing wxLocale::GetSystemLanguage ***"));
1202 static const wxChar
*langStrings
[] =
1204 NULL
, // system default
1211 _T("de_DE.iso88591"),
1213 _T("?"), // invalid lang spec
1214 _T("klingonese"), // I bet on some systems it does exist...
1217 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1218 wxLocale::GetSystemEncodingName().c_str(),
1219 wxLocale::GetSystemEncoding());
1221 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1223 const wxChar
*langStr
= langStrings
[n
];
1226 // FIXME: this doesn't do anything at all under Windows, we need
1227 // to create a new wxLocale!
1228 wxSetEnv(_T("LC_ALL"), langStr
);
1231 int lang
= gs_localeDefault
.GetSystemLanguage();
1232 wxPrintf(_T("Locale for '%s' is %s.\n"),
1233 langStr
? langStr
: _T("system default"), GetLangName(lang
));
1237 #endif // TEST_LOCALE
1239 // ----------------------------------------------------------------------------
1241 // ----------------------------------------------------------------------------
1245 #include "wx/mimetype.h"
1247 static void TestMimeEnum()
1249 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1251 wxArrayString mimetypes
;
1253 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1255 wxPrintf(_T("*** All %u known filetypes: ***\n"), count
);
1260 for ( size_t n
= 0; n
< count
; n
++ )
1262 wxFileType
*filetype
=
1263 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1266 wxPrintf(_T("nothing known about the filetype '%s'!\n"),
1267 mimetypes
[n
].c_str());
1271 filetype
->GetDescription(&desc
);
1272 filetype
->GetExtensions(exts
);
1274 filetype
->GetIcon(NULL
);
1277 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1280 extsAll
<< _T(", ");
1284 wxPrintf(_T("\t%s: %s (%s)\n"),
1285 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1288 wxPuts(wxEmptyString
);
1291 static void TestMimeOverride()
1293 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1295 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1296 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1298 if ( wxFile::Exists(mailcap
) )
1299 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1301 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1303 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1306 if ( wxFile::Exists(mimetypes
) )
1307 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1309 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1311 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1314 wxPuts(wxEmptyString
);
1317 static void TestMimeFilename()
1319 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1321 static const wxChar
*filenames
[] =
1329 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1331 const wxString fname
= filenames
[n
];
1332 wxString ext
= fname
.AfterLast(_T('.'));
1333 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1336 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1341 if ( !ft
->GetDescription(&desc
) )
1342 desc
= _T("<no description>");
1345 if ( !ft
->GetOpenCommand(&cmd
,
1346 wxFileType::MessageParameters(fname
, wxEmptyString
)) )
1347 cmd
= _T("<no command available>");
1349 cmd
= wxString(_T('"')) + cmd
+ _T('"');
1351 wxPrintf(_T("To open %s (%s) do %s.\n"),
1352 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1358 wxPuts(wxEmptyString
);
1361 static void TestMimeAssociate()
1363 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1365 wxFileTypeInfo
ftInfo(
1366 _T("application/x-xyz"),
1367 _T("xyzview '%s'"), // open cmd
1368 _T(""), // print cmd
1369 _T("XYZ File"), // description
1370 _T(".xyz"), // extensions
1371 NULL
// end of extensions
1373 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1375 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1378 wxPuts(_T("ERROR: failed to create association!"));
1382 // TODO: read it back
1386 wxPuts(wxEmptyString
);
1391 // ----------------------------------------------------------------------------
1392 // misc information functions
1393 // ----------------------------------------------------------------------------
1395 #ifdef TEST_INFO_FUNCTIONS
1397 #include "wx/utils.h"
1399 static void TestDiskInfo()
1401 wxPuts(_T("*** Testing wxGetDiskSpace() ***"));
1405 wxChar pathname
[128];
1406 wxPrintf(_T("\nEnter a directory name: "));
1407 if ( !wxFgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1410 // kill the last '\n'
1411 pathname
[wxStrlen(pathname
) - 1] = 0;
1413 wxLongLong total
, free
;
1414 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1416 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1420 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1421 (total
/ 1024).ToString().c_str(),
1422 (free
/ 1024).ToString().c_str(),
1428 static void TestOsInfo()
1430 wxPuts(_T("*** Testing OS info functions ***\n"));
1433 wxGetOsVersion(&major
, &minor
);
1434 wxPrintf(_T("Running under: %s, version %d.%d\n"),
1435 wxGetOsDescription().c_str(), major
, minor
);
1437 wxPrintf(_T("%ld free bytes of memory left.\n"), wxGetFreeMemory());
1439 wxPrintf(_T("Host name is %s (%s).\n"),
1440 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1442 wxPuts(wxEmptyString
);
1445 static void TestUserInfo()
1447 wxPuts(_T("*** Testing user info functions ***\n"));
1449 wxPrintf(_T("User id is:\t%s\n"), wxGetUserId().c_str());
1450 wxPrintf(_T("User name is:\t%s\n"), wxGetUserName().c_str());
1451 wxPrintf(_T("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
1452 wxPrintf(_T("Email address:\t%s\n"), wxGetEmailAddress().c_str());
1454 wxPuts(wxEmptyString
);
1457 #endif // TEST_INFO_FUNCTIONS
1459 // ----------------------------------------------------------------------------
1461 // ----------------------------------------------------------------------------
1463 #ifdef TEST_PATHLIST
1466 #define CMD_IN_PATH _T("ls")
1468 #define CMD_IN_PATH _T("command.com")
1471 static void TestPathList()
1473 wxPuts(_T("*** Testing wxPathList ***\n"));
1475 wxPathList pathlist
;
1476 pathlist
.AddEnvList(_T("PATH"));
1477 wxString path
= pathlist
.FindValidPath(CMD_IN_PATH
);
1480 wxPrintf(_T("ERROR: command not found in the path.\n"));
1484 wxPrintf(_T("Command found in the path as '%s'.\n"), path
.c_str());
1488 #endif // TEST_PATHLIST
1490 // ----------------------------------------------------------------------------
1491 // regular expressions
1492 // ----------------------------------------------------------------------------
1496 #include "wx/regex.h"
1498 static void TestRegExInteractive()
1500 wxPuts(_T("*** Testing RE interactively ***"));
1504 wxChar pattern
[128];
1505 wxPrintf(_T("\nEnter a pattern: "));
1506 if ( !wxFgets(pattern
, WXSIZEOF(pattern
), stdin
) )
1509 // kill the last '\n'
1510 pattern
[wxStrlen(pattern
) - 1] = 0;
1513 if ( !re
.Compile(pattern
) )
1521 wxPrintf(_T("Enter text to match: "));
1522 if ( !wxFgets(text
, WXSIZEOF(text
), stdin
) )
1525 // kill the last '\n'
1526 text
[wxStrlen(text
) - 1] = 0;
1528 if ( !re
.Matches(text
) )
1530 wxPrintf(_T("No match.\n"));
1534 wxPrintf(_T("Pattern matches at '%s'\n"), re
.GetMatch(text
).c_str());
1537 for ( size_t n
= 1; ; n
++ )
1539 if ( !re
.GetMatch(&start
, &len
, n
) )
1544 wxPrintf(_T("Subexpr %u matched '%s'\n"),
1545 n
, wxString(text
+ start
, len
).c_str());
1552 #endif // TEST_REGEX
1554 // ----------------------------------------------------------------------------
1556 // ----------------------------------------------------------------------------
1566 static void TestDbOpen()
1574 // ----------------------------------------------------------------------------
1576 // ----------------------------------------------------------------------------
1579 NB: this stuff was taken from the glibc test suite and modified to build
1580 in wxWidgets: if I read the copyright below properly, this shouldn't
1586 #ifdef wxTEST_PRINTF
1587 // use our functions from wxchar.cpp
1591 // NB: do _not_ use ATTRIBUTE_PRINTF here, we have some invalid formats
1592 // in the tests below
1593 int wxPrintf( const wxChar
*format
, ... );
1594 int wxSprintf( wxChar
*str
, const wxChar
*format
, ... );
1597 #include "wx/longlong.h"
1601 static void rfg1 (void);
1602 static void rfg2 (void);
1606 fmtchk (const wxChar
*fmt
)
1608 (void) wxPrintf(_T("%s:\t`"), fmt
);
1609 (void) wxPrintf(fmt
, 0x12);
1610 (void) wxPrintf(_T("'\n"));
1614 fmtst1chk (const wxChar
*fmt
)
1616 (void) wxPrintf(_T("%s:\t`"), fmt
);
1617 (void) wxPrintf(fmt
, 4, 0x12);
1618 (void) wxPrintf(_T("'\n"));
1622 fmtst2chk (const wxChar
*fmt
)
1624 (void) wxPrintf(_T("%s:\t`"), fmt
);
1625 (void) wxPrintf(fmt
, 4, 4, 0x12);
1626 (void) wxPrintf(_T("'\n"));
1629 /* This page is covered by the following copyright: */
1631 /* (C) Copyright C E Chew
1633 * Feel free to copy, use and distribute this software provided:
1635 * 1. you do not pretend that you wrote it
1636 * 2. you leave this copyright notice intact.
1640 * Extracted from exercise.c for glibc-1.05 bug report by Bruce Evans.
1647 /* Formatted Output Test
1649 * This exercises the output formatting code.
1652 wxChar
*PointerNull
= NULL
;
1659 wxChar
*prefix
= buf
;
1662 wxPuts(_T("\nFormatted output test"));
1663 wxPrintf(_T("prefix 6d 6o 6x 6X 6u\n"));
1664 wxStrcpy(prefix
, _T("%"));
1665 for (i
= 0; i
< 2; i
++) {
1666 for (j
= 0; j
< 2; j
++) {
1667 for (k
= 0; k
< 2; k
++) {
1668 for (l
= 0; l
< 2; l
++) {
1669 wxStrcpy(prefix
, _T("%"));
1670 if (i
== 0) wxStrcat(prefix
, _T("-"));
1671 if (j
== 0) wxStrcat(prefix
, _T("+"));
1672 if (k
== 0) wxStrcat(prefix
, _T("#"));
1673 if (l
== 0) wxStrcat(prefix
, _T("0"));
1674 wxPrintf(_T("%5s |"), prefix
);
1675 wxStrcpy(tp
, prefix
);
1676 wxStrcat(tp
, _T("6d |"));
1678 wxStrcpy(tp
, prefix
);
1679 wxStrcat(tp
, _T("6o |"));
1681 wxStrcpy(tp
, prefix
);
1682 wxStrcat(tp
, _T("6x |"));
1684 wxStrcpy(tp
, prefix
);
1685 wxStrcat(tp
, _T("6X |"));
1687 wxStrcpy(tp
, prefix
);
1688 wxStrcat(tp
, _T("6u |"));
1695 wxPrintf(_T("%10s\n"), PointerNull
);
1696 wxPrintf(_T("%-10s\n"), PointerNull
);
1699 static void TestPrintf()
1701 static wxChar shortstr
[] = _T("Hi, Z.");
1702 static wxChar longstr
[] = _T("Good morning, Doctor Chandra. This is Hal. \
1703 I am ready for my first lesson today.");
1705 wxString test_format
;
1709 fmtchk(_T("%4.4x"));
1710 fmtchk(_T("%04.4x"));
1711 fmtchk(_T("%4.3x"));
1712 fmtchk(_T("%04.3x"));
1714 fmtst1chk(_T("%.*x"));
1715 fmtst1chk(_T("%0*x"));
1716 fmtst2chk(_T("%*.*x"));
1717 fmtst2chk(_T("%0*.*x"));
1719 wxString bad_format
= _T("bad format:\t\"%b\"\n");
1720 wxPrintf(bad_format
.c_str());
1721 wxPrintf(_T("nil pointer (padded):\t\"%10p\"\n"), (void *) NULL
);
1723 wxPrintf(_T("decimal negative:\t\"%d\"\n"), -2345);
1724 wxPrintf(_T("octal negative:\t\"%o\"\n"), -2345);
1725 wxPrintf(_T("hex negative:\t\"%x\"\n"), -2345);
1726 wxPrintf(_T("long decimal number:\t\"%ld\"\n"), -123456L);
1727 wxPrintf(_T("long octal negative:\t\"%lo\"\n"), -2345L);
1728 wxPrintf(_T("long unsigned decimal number:\t\"%lu\"\n"), -123456L);
1729 wxPrintf(_T("zero-padded LDN:\t\"%010ld\"\n"), -123456L);
1730 test_format
= _T("left-adjusted ZLDN:\t\"%-010ld\"\n");
1731 wxPrintf(test_format
.c_str(), -123456);
1732 wxPrintf(_T("space-padded LDN:\t\"%10ld\"\n"), -123456L);
1733 wxPrintf(_T("left-adjusted SLDN:\t\"%-10ld\"\n"), -123456L);
1735 test_format
= _T("zero-padded string:\t\"%010s\"\n");
1736 wxPrintf(test_format
.c_str(), shortstr
);
1737 test_format
= _T("left-adjusted Z string:\t\"%-010s\"\n");
1738 wxPrintf(test_format
.c_str(), shortstr
);
1739 wxPrintf(_T("space-padded string:\t\"%10s\"\n"), shortstr
);
1740 wxPrintf(_T("left-adjusted S string:\t\"%-10s\"\n"), shortstr
);
1741 wxPrintf(_T("null string:\t\"%s\"\n"), PointerNull
);
1742 wxPrintf(_T("limited string:\t\"%.22s\"\n"), longstr
);
1744 wxPrintf(_T("e-style >= 1:\t\"%e\"\n"), 12.34);
1745 wxPrintf(_T("e-style >= .1:\t\"%e\"\n"), 0.1234);
1746 wxPrintf(_T("e-style < .1:\t\"%e\"\n"), 0.001234);
1747 wxPrintf(_T("e-style big:\t\"%.60e\"\n"), 1e20
);
1748 wxPrintf(_T("e-style == .1:\t\"%e\"\n"), 0.1);
1749 wxPrintf(_T("f-style >= 1:\t\"%f\"\n"), 12.34);
1750 wxPrintf(_T("f-style >= .1:\t\"%f\"\n"), 0.1234);
1751 wxPrintf(_T("f-style < .1:\t\"%f\"\n"), 0.001234);
1752 wxPrintf(_T("g-style >= 1:\t\"%g\"\n"), 12.34);
1753 wxPrintf(_T("g-style >= .1:\t\"%g\"\n"), 0.1234);
1754 wxPrintf(_T("g-style < .1:\t\"%g\"\n"), 0.001234);
1755 wxPrintf(_T("g-style big:\t\"%.60g\"\n"), 1e20
);
1757 wxPrintf (_T(" %6.5f\n"), .099999999860301614);
1758 wxPrintf (_T(" %6.5f\n"), .1);
1759 wxPrintf (_T("x%5.4fx\n"), .5);
1761 wxPrintf (_T("%#03x\n"), 1);
1763 //wxPrintf (_T("something really insane: %.10000f\n"), 1.0);
1769 while (niter
-- != 0)
1770 wxPrintf (_T("%.17e\n"), d
/ 2);
1775 // Open Watcom cause compiler error here
1776 // Error! E173: col(24) floating-point constant too small to represent
1777 wxPrintf (_T("%15.5e\n"), 4.9406564584124654e-324);
1780 #define FORMAT _T("|%12.4f|%12.4e|%12.4g|\n")
1781 wxPrintf (FORMAT
, 0.0, 0.0, 0.0);
1782 wxPrintf (FORMAT
, 1.0, 1.0, 1.0);
1783 wxPrintf (FORMAT
, -1.0, -1.0, -1.0);
1784 wxPrintf (FORMAT
, 100.0, 100.0, 100.0);
1785 wxPrintf (FORMAT
, 1000.0, 1000.0, 1000.0);
1786 wxPrintf (FORMAT
, 10000.0, 10000.0, 10000.0);
1787 wxPrintf (FORMAT
, 12345.0, 12345.0, 12345.0);
1788 wxPrintf (FORMAT
, 100000.0, 100000.0, 100000.0);
1789 wxPrintf (FORMAT
, 123456.0, 123456.0, 123456.0);
1794 int rc
= wxSnprintf (buf
, WXSIZEOF(buf
), _T("%30s"), _T("foo"));
1796 wxPrintf(_T("snprintf (\"%%30s\", \"foo\") == %d, \"%.*s\"\n"),
1797 rc
, WXSIZEOF(buf
), buf
);
1800 wxPrintf ("snprintf (\"%%.999999u\", 10)\n",
1801 wxSnprintf(buf2
, WXSIZEOFbuf2
), "%.999999u", 10));
1807 wxPrintf (_T("%e should be 1.234568e+06\n"), 1234567.8);
1808 wxPrintf (_T("%f should be 1234567.800000\n"), 1234567.8);
1809 wxPrintf (_T("%g should be 1.23457e+06\n"), 1234567.8);
1810 wxPrintf (_T("%g should be 123.456\n"), 123.456);
1811 wxPrintf (_T("%g should be 1e+06\n"), 1000000.0);
1812 wxPrintf (_T("%g should be 10\n"), 10.0);
1813 wxPrintf (_T("%g should be 0.02\n"), 0.02);
1817 wxPrintf(_T("%.17f\n"),(1.0/x
/10.0+1.0)*x
-x
);
1823 wxSprintf(buf
,_T("%*s%*s%*s"),-1,_T("one"),-20,_T("two"),-30,_T("three"));
1825 result
|= wxStrcmp (buf
,
1826 _T("onetwo three "));
1828 wxPuts (result
!= 0 ? _T("Test failed!") : _T("Test ok."));
1835 wxSprintf(buf
, _T("%07") wxLongLongFmtSpec
_T("o"), wxLL(040000000000));
1837 // for some reason below line fails under Borland
1838 wxPrintf (_T("sprintf (buf, \"%%07Lo\", 040000000000ll) = %s"), buf
);
1841 if (wxStrcmp (buf
, _T("40000000000")) != 0)
1844 wxPuts (_T("\tFAILED"));
1846 wxUnusedVar(result
);
1847 wxPuts (wxEmptyString
);
1849 #endif // wxLongLong_t
1851 wxPrintf (_T("printf (\"%%hhu\", %u) = %hhu\n"), UCHAR_MAX
+ 2, UCHAR_MAX
+ 2);
1852 wxPrintf (_T("printf (\"%%hu\", %u) = %hu\n"), USHRT_MAX
+ 2, USHRT_MAX
+ 2);
1854 wxPuts (_T("--- Should be no further output. ---"));
1863 memset (bytes
, '\xff', sizeof bytes
);
1864 wxSprintf (buf
, _T("foo%hhn\n"), &bytes
[3]);
1865 if (bytes
[0] != '\xff' || bytes
[1] != '\xff' || bytes
[2] != '\xff'
1866 || bytes
[4] != '\xff' || bytes
[5] != '\xff' || bytes
[6] != '\xff')
1868 wxPuts (_T("%hhn overwrite more bytes"));
1873 wxPuts (_T("%hhn wrote incorrect value"));
1885 wxSprintf (buf
, _T("%5.s"), _T("xyz"));
1886 if (wxStrcmp (buf
, _T(" ")) != 0)
1887 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" "));
1888 wxSprintf (buf
, _T("%5.f"), 33.3);
1889 if (wxStrcmp (buf
, _T(" 33")) != 0)
1890 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 33"));
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("%8.E"), 33.3e7
);
1895 if (wxStrcmp (buf
, _T(" 3E+08")) != 0)
1896 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3E+08"));
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"));
1900 wxSprintf (buf
, _T("%.G"), 33.3);
1901 if (wxStrcmp (buf
, _T("3E+01")) != 0)
1902 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3E+01"));
1910 wxString test_format
;
1913 wxSprintf (buf
, _T("%.*g"), prec
, 3.3);
1914 if (wxStrcmp (buf
, _T("3")) != 0)
1915 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
1917 wxSprintf (buf
, _T("%.*G"), prec
, 3.3);
1918 if (wxStrcmp (buf
, _T("3")) != 0)
1919 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
1921 wxSprintf (buf
, _T("%7.*G"), prec
, 3.33);
1922 if (wxStrcmp (buf
, _T(" 3")) != 0)
1923 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3"));
1925 test_format
= _T("%04.*o");
1926 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1927 if (wxStrcmp (buf
, _T(" 041")) != 0)
1928 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 041"));
1930 test_format
= _T("%09.*u");
1931 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1932 if (wxStrcmp (buf
, _T(" 0000033")) != 0)
1933 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 0000033"));
1935 test_format
= _T("%04.*x");
1936 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1937 if (wxStrcmp (buf
, _T(" 021")) != 0)
1938 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
1940 test_format
= _T("%04.*X");
1941 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1942 if (wxStrcmp (buf
, _T(" 021")) != 0)
1943 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
1946 #endif // TEST_PRINTF
1948 // ----------------------------------------------------------------------------
1949 // registry and related stuff
1950 // ----------------------------------------------------------------------------
1952 // this is for MSW only
1955 #undef TEST_REGISTRY
1960 #include "wx/confbase.h"
1961 #include "wx/msw/regconf.h"
1964 static void TestRegConfWrite()
1966 wxConfig
*config
= new wxConfig(_T("myapp"));
1967 config
->SetPath(_T("/group1"));
1968 config
->Write(_T("entry1"), _T("foo"));
1969 config
->SetPath(_T("/group2"));
1970 config
->Write(_T("entry1"), _T("bar"));
1974 static void TestRegConfRead()
1976 wxConfig
*config
= new wxConfig(_T("myapp"));
1980 config
->SetPath(_T("/"));
1981 wxPuts(_T("Enumerating / subgroups:"));
1982 bool bCont
= config
->GetFirstGroup(str
, dummy
);
1986 bCont
= config
->GetNextGroup(str
, dummy
);
1990 #endif // TEST_REGCONF
1992 #ifdef TEST_REGISTRY
1994 #include "wx/msw/registry.h"
1996 // I chose this one because I liked its name, but it probably only exists under
1998 static const wxChar
*TESTKEY
=
1999 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2001 static void TestRegistryRead()
2003 wxPuts(_T("*** testing registry reading ***"));
2005 wxRegKey
key(TESTKEY
);
2006 wxPrintf(_T("The test key name is '%s'.\n"), key
.GetName().c_str());
2009 wxPuts(_T("ERROR: test key can't be opened, aborting test."));
2014 size_t nSubKeys
, nValues
;
2015 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2017 wxPrintf(_T("It has %u subkeys and %u values.\n"), nSubKeys
, nValues
);
2020 wxPrintf(_T("Enumerating values:\n"));
2024 bool cont
= key
.GetFirstValue(value
, dummy
);
2027 wxPrintf(_T("Value '%s': type "), value
.c_str());
2028 switch ( key
.GetValueType(value
) )
2030 case wxRegKey::Type_None
: wxPrintf(_T("ERROR (none)")); break;
2031 case wxRegKey::Type_String
: wxPrintf(_T("SZ")); break;
2032 case wxRegKey::Type_Expand_String
: wxPrintf(_T("EXPAND_SZ")); break;
2033 case wxRegKey::Type_Binary
: wxPrintf(_T("BINARY")); break;
2034 case wxRegKey::Type_Dword
: wxPrintf(_T("DWORD")); break;
2035 case wxRegKey::Type_Multi_String
: wxPrintf(_T("MULTI_SZ")); break;
2036 default: wxPrintf(_T("other (unknown)")); break;
2039 wxPrintf(_T(", value = "));
2040 if ( key
.IsNumericValue(value
) )
2043 key
.QueryValue(value
, &val
);
2044 wxPrintf(_T("%ld"), val
);
2049 key
.QueryValue(value
, val
);
2050 wxPrintf(_T("'%s'"), val
.c_str());
2052 key
.QueryRawValue(value
, val
);
2053 wxPrintf(_T(" (raw value '%s')"), val
.c_str());
2058 cont
= key
.GetNextValue(value
, dummy
);
2062 static void TestRegistryAssociation()
2065 The second call to deleteself genertaes an error message, with a
2066 messagebox saying .flo is crucial to system operation, while the .ddf
2067 call also fails, but with no error message
2072 key
.SetName(_T("HKEY_CLASSES_ROOT\\.ddf") );
2074 key
= _T("ddxf_auto_file") ;
2075 key
.SetName(_T("HKEY_CLASSES_ROOT\\.flo") );
2077 key
= _T("ddxf_auto_file") ;
2078 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2080 key
= _T("program,0") ;
2081 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2083 key
= _T("program \"%1\"") ;
2085 key
.SetName(_T("HKEY_CLASSES_ROOT\\.ddf") );
2087 key
.SetName(_T("HKEY_CLASSES_ROOT\\.flo") );
2089 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2091 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2095 #endif // TEST_REGISTRY
2097 // ----------------------------------------------------------------------------
2099 // ----------------------------------------------------------------------------
2101 #ifdef TEST_SCOPEGUARD
2103 #include "wx/scopeguard.h"
2105 static void function0() { puts("function0()"); }
2106 static void function1(int n
) { printf("function1(%d)\n", n
); }
2107 static void function2(double x
, char c
) { printf("function2(%g, %c)\n", x
, c
); }
2111 void method0() { printf("method0()\n"); }
2112 void method1(int n
) { printf("method1(%d)\n", n
); }
2113 void method2(double x
, char c
) { printf("method2(%g, %c)\n", x
, c
); }
2116 static void TestScopeGuard()
2118 wxON_BLOCK_EXIT0(function0
);
2119 wxON_BLOCK_EXIT1(function1
, 17);
2120 wxON_BLOCK_EXIT2(function2
, 3.14, 'p');
2123 wxON_BLOCK_EXIT_OBJ0(obj
, &Object::method0
);
2124 wxON_BLOCK_EXIT_OBJ1(obj
, &Object::method1
, 7);
2125 wxON_BLOCK_EXIT_OBJ2(obj
, &Object::method2
, 2.71, 'e');
2127 wxScopeGuard dismissed
= wxMakeGuard(function0
);
2128 dismissed
.Dismiss();
2133 // ----------------------------------------------------------------------------
2135 // ----------------------------------------------------------------------------
2139 #include "wx/socket.h"
2140 #include "wx/protocol/protocol.h"
2141 #include "wx/protocol/http.h"
2143 static void TestSocketServer()
2145 wxPuts(_T("*** Testing wxSocketServer ***\n"));
2147 static const int PORT
= 3000;
2152 wxSocketServer
*server
= new wxSocketServer(addr
);
2153 if ( !server
->Ok() )
2155 wxPuts(_T("ERROR: failed to bind"));
2163 wxPrintf(_T("Server: waiting for connection on port %d...\n"), PORT
);
2165 wxSocketBase
*socket
= server
->Accept();
2168 wxPuts(_T("ERROR: wxSocketServer::Accept() failed."));
2172 wxPuts(_T("Server: got a client."));
2174 server
->SetTimeout(60); // 1 min
2177 while ( !close
&& socket
->IsConnected() )
2180 wxChar ch
= _T('\0');
2183 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2185 // don't log error if the client just close the connection
2186 if ( socket
->IsConnected() )
2188 wxPuts(_T("ERROR: in wxSocket::Read."));
2208 wxPrintf(_T("Server: got '%s'.\n"), s
.c_str());
2209 if ( s
== _T("close") )
2211 wxPuts(_T("Closing connection"));
2215 else if ( s
== _T("quit") )
2220 wxPuts(_T("Shutting down the server"));
2222 else // not a special command
2224 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2225 socket
->Write("\r\n", 2);
2226 wxPrintf(_T("Server: wrote '%s'.\n"), s
.c_str());
2232 wxPuts(_T("Server: lost a client unexpectedly."));
2238 // same as "delete server" but is consistent with GUI programs
2242 static void TestSocketClient()
2244 wxPuts(_T("*** Testing wxSocketClient ***\n"));
2246 static const wxChar
*hostname
= _T("www.wxwidgets.org");
2249 addr
.Hostname(hostname
);
2252 wxPrintf(_T("--- Attempting to connect to %s:80...\n"), hostname
);
2254 wxSocketClient client
;
2255 if ( !client
.Connect(addr
) )
2257 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2261 wxPrintf(_T("--- Connected to %s:%u...\n"),
2262 addr
.Hostname().c_str(), addr
.Service());
2266 // could use simply "GET" here I suppose
2268 wxString::Format(_T("GET http://%s/\r\n"), hostname
);
2269 client
.Write(cmdGet
, cmdGet
.length());
2270 wxPrintf(_T("--- Sent command '%s' to the server\n"),
2271 MakePrintable(cmdGet
).c_str());
2272 client
.Read(buf
, WXSIZEOF(buf
));
2273 wxPrintf(_T("--- Server replied:\n%s"), buf
);
2277 #endif // TEST_SOCKETS
2279 // ----------------------------------------------------------------------------
2281 // ----------------------------------------------------------------------------
2285 #include "wx/protocol/ftp.h"
2289 #define FTP_ANONYMOUS
2291 #ifdef FTP_ANONYMOUS
2292 static const wxChar
*directory
= _T("/pub");
2293 static const wxChar
*filename
= _T("welcome.msg");
2295 static const wxChar
*directory
= _T("/etc");
2296 static const wxChar
*filename
= _T("issue");
2299 static bool TestFtpConnect()
2301 wxPuts(_T("*** Testing FTP connect ***"));
2303 #ifdef FTP_ANONYMOUS
2304 static const wxChar
*hostname
= _T("ftp.wxwidgets.org");
2306 wxPrintf(_T("--- Attempting to connect to %s:21 anonymously...\n"), hostname
);
2307 #else // !FTP_ANONYMOUS
2308 static const wxChar
*hostname
= "localhost";
2311 wxFgets(user
, WXSIZEOF(user
), stdin
);
2312 user
[wxStrlen(user
) - 1] = '\0'; // chop off '\n'
2315 wxChar password
[256];
2316 wxPrintf(_T("Password for %s: "), password
);
2317 wxFgets(password
, WXSIZEOF(password
), stdin
);
2318 password
[wxStrlen(password
) - 1] = '\0'; // chop off '\n'
2319 ftp
.SetPassword(password
);
2321 wxPrintf(_T("--- Attempting to connect to %s:21 as %s...\n"), hostname
, user
);
2322 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2324 if ( !ftp
.Connect(hostname
) )
2326 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2332 wxPrintf(_T("--- Connected to %s, current directory is '%s'\n"),
2333 hostname
, ftp
.Pwd().c_str());
2340 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2341 static void TestFtpWuFtpd()
2344 static const wxChar
*hostname
= _T("ftp.eudora.com");
2345 if ( !ftp
.Connect(hostname
) )
2347 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2351 static const wxChar
*filename
= _T("eudora/pubs/draft-gellens-submit-09.txt");
2352 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2355 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
2359 size_t size
= in
->GetSize();
2360 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
2362 wxChar
*data
= new wxChar
[size
];
2363 if ( !in
->Read(data
, size
) )
2365 wxPuts(_T("ERROR: read error"));
2369 wxPrintf(_T("Successfully retrieved the file.\n"));
2378 static void TestFtpList()
2380 wxPuts(_T("*** Testing wxFTP file listing ***\n"));
2383 if ( !ftp
.ChDir(directory
) )
2385 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
2388 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2390 // test NLIST and LIST
2391 wxArrayString files
;
2392 if ( !ftp
.GetFilesList(files
) )
2394 wxPuts(_T("ERROR: failed to get NLIST of files"));
2398 wxPrintf(_T("Brief list of files under '%s':\n"), ftp
.Pwd().c_str());
2399 size_t count
= files
.GetCount();
2400 for ( size_t n
= 0; n
< count
; n
++ )
2402 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2404 wxPuts(_T("End of the file list"));
2407 if ( !ftp
.GetDirList(files
) )
2409 wxPuts(_T("ERROR: failed to get LIST of files"));
2413 wxPrintf(_T("Detailed list of files under '%s':\n"), ftp
.Pwd().c_str());
2414 size_t count
= files
.GetCount();
2415 for ( size_t n
= 0; n
< count
; n
++ )
2417 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2419 wxPuts(_T("End of the file list"));
2422 if ( !ftp
.ChDir(_T("..")) )
2424 wxPuts(_T("ERROR: failed to cd to .."));
2427 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2430 static void TestFtpDownload()
2432 wxPuts(_T("*** Testing wxFTP download ***\n"));
2435 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2438 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
2442 size_t size
= in
->GetSize();
2443 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
2446 wxChar
*data
= new wxChar
[size
];
2447 if ( !in
->Read(data
, size
) )
2449 wxPuts(_T("ERROR: read error"));
2453 wxPrintf(_T("\nContents of %s:\n%s\n"), filename
, data
);
2461 static void TestFtpFileSize()
2463 wxPuts(_T("*** Testing FTP SIZE command ***"));
2465 if ( !ftp
.ChDir(directory
) )
2467 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
2470 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2472 if ( ftp
.FileExists(filename
) )
2474 int size
= ftp
.GetFileSize(filename
);
2476 wxPrintf(_T("ERROR: couldn't get size of '%s'\n"), filename
);
2478 wxPrintf(_T("Size of '%s' is %d bytes.\n"), filename
, size
);
2482 wxPrintf(_T("ERROR: '%s' doesn't exist\n"), filename
);
2486 static void TestFtpMisc()
2488 wxPuts(_T("*** Testing miscellaneous wxFTP functions ***"));
2490 if ( ftp
.SendCommand(_T("STAT")) != '2' )
2492 wxPuts(_T("ERROR: STAT failed"));
2496 wxPrintf(_T("STAT returned:\n\n%s\n"), ftp
.GetLastResult().c_str());
2499 if ( ftp
.SendCommand(_T("HELP SITE")) != '2' )
2501 wxPuts(_T("ERROR: HELP SITE failed"));
2505 wxPrintf(_T("The list of site-specific commands:\n\n%s\n"),
2506 ftp
.GetLastResult().c_str());
2510 static void TestFtpInteractive()
2512 wxPuts(_T("\n*** Interactive wxFTP test ***"));
2518 wxPrintf(_T("Enter FTP command: "));
2519 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
2522 // kill the last '\n'
2523 buf
[wxStrlen(buf
) - 1] = 0;
2525 // special handling of LIST and NLST as they require data connection
2526 wxString
start(buf
, 4);
2528 if ( start
== _T("LIST") || start
== _T("NLST") )
2531 if ( wxStrlen(buf
) > 4 )
2534 wxArrayString files
;
2535 if ( !ftp
.GetList(files
, wildcard
, start
== _T("LIST")) )
2537 wxPrintf(_T("ERROR: failed to get %s of files\n"), start
.c_str());
2541 wxPrintf(_T("--- %s of '%s' under '%s':\n"),
2542 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2543 size_t count
= files
.GetCount();
2544 for ( size_t n
= 0; n
< count
; n
++ )
2546 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2548 wxPuts(_T("--- End of the file list"));
2553 wxChar ch
= ftp
.SendCommand(buf
);
2554 wxPrintf(_T("Command %s"), ch
? _T("succeeded") : _T("failed"));
2557 wxPrintf(_T(" (return code %c)"), ch
);
2560 wxPrintf(_T(", server reply:\n%s\n\n"), ftp
.GetLastResult().c_str());
2564 wxPuts(_T("\n*** done ***"));
2567 static void TestFtpUpload()
2569 wxPuts(_T("*** Testing wxFTP uploading ***\n"));
2572 static const wxChar
*file1
= _T("test1");
2573 static const wxChar
*file2
= _T("test2");
2574 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2577 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
2578 out
->Write("First hello", 11);
2582 // send a command to check the remote file
2583 if ( ftp
.SendCommand(wxString(_T("STAT ")) + file1
) != '2' )
2585 wxPrintf(_T("ERROR: STAT %s failed\n"), file1
);
2589 wxPrintf(_T("STAT %s returned:\n\n%s\n"),
2590 file1
, ftp
.GetLastResult().c_str());
2593 out
= ftp
.GetOutputStream(file2
);
2596 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
2597 out
->Write("Second hello", 12);
2604 // ----------------------------------------------------------------------------
2606 // ----------------------------------------------------------------------------
2608 #ifdef TEST_STDPATHS
2610 #include "wx/stdpaths.h"
2612 static void TestStandardPaths()
2614 wxPuts(_T("*** Testing wxStandardPaths ***\n"));
2616 wxTheApp
->SetAppName(_T("console"));
2618 wxStandardPaths
& stdp
= wxStandardPaths::Get();
2619 wxPrintf(_T("Config dir (sys):\t%s\n"), stdp
.GetConfigDir().c_str());
2620 wxPrintf(_T("Config dir (user):\t%s\n"), stdp
.GetUserConfigDir().c_str());
2621 wxPrintf(_T("Data dir (sys):\t\t%s\n"), stdp
.GetDataDir().c_str());
2622 wxPrintf(_T("Data dir (sys local):\t%s\n"), stdp
.GetLocalDataDir().c_str());
2623 wxPrintf(_T("Data dir (user):\t%s\n"), stdp
.GetUserDataDir().c_str());
2624 wxPrintf(_T("Data dir (user local):\t%s\n"), stdp
.GetUserLocalDataDir().c_str());
2625 wxPrintf(_T("Plugins dir:\t\t%s\n"), stdp
.GetPluginsDir().c_str());
2628 #endif // TEST_STDPATHS
2630 // ----------------------------------------------------------------------------
2632 // ----------------------------------------------------------------------------
2636 #include "wx/wfstream.h"
2637 #include "wx/mstream.h"
2639 static void TestFileStream()
2641 wxPuts(_T("*** Testing wxFileInputStream ***"));
2643 static const wxString filename
= _T("testdata.fs");
2645 wxFileOutputStream
fsOut(filename
);
2646 fsOut
.Write("foo", 3);
2649 wxFileInputStream
fsIn(filename
);
2650 wxPrintf(_T("File stream size: %u\n"), fsIn
.GetSize());
2651 while ( !fsIn
.Eof() )
2653 wxPutchar(fsIn
.GetC());
2656 if ( !wxRemoveFile(filename
) )
2658 wxPrintf(_T("ERROR: failed to remove the file '%s'.\n"), filename
.c_str());
2661 wxPuts(_T("\n*** wxFileInputStream test done ***"));
2664 static void TestMemoryStream()
2666 wxPuts(_T("*** Testing wxMemoryOutputStream ***"));
2668 wxMemoryOutputStream memOutStream
;
2669 wxPrintf(_T("Initially out stream offset: %lu\n"),
2670 (unsigned long)memOutStream
.TellO());
2672 for ( const wxChar
*p
= _T("Hello, stream!"); *p
; p
++ )
2674 memOutStream
.PutC(*p
);
2677 wxPrintf(_T("Final out stream offset: %lu\n"),
2678 (unsigned long)memOutStream
.TellO());
2680 wxPuts(_T("*** Testing wxMemoryInputStream ***"));
2683 size_t len
= memOutStream
.CopyTo(buf
, WXSIZEOF(buf
));
2685 wxMemoryInputStream
memInpStream(buf
, len
);
2686 wxPrintf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2687 while ( !memInpStream
.Eof() )
2689 wxPutchar(memInpStream
.GetC());
2692 wxPuts(_T("\n*** wxMemoryInputStream test done ***"));
2695 #endif // TEST_STREAMS
2697 // ----------------------------------------------------------------------------
2699 // ----------------------------------------------------------------------------
2703 #include "wx/timer.h"
2704 #include "wx/utils.h"
2706 static void TestStopWatch()
2708 wxPuts(_T("*** Testing wxStopWatch ***\n"));
2712 wxPrintf(_T("Initially paused, after 2 seconds time is..."));
2715 wxPrintf(_T("\t%ldms\n"), sw
.Time());
2717 wxPrintf(_T("Resuming stopwatch and sleeping 3 seconds..."));
2721 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2724 wxPrintf(_T("Pausing agan and sleeping 2 more seconds..."));
2727 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2730 wxPrintf(_T("Finally resuming and sleeping 2 more seconds..."));
2733 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2736 wxPuts(_T("\nChecking for 'backwards clock' bug..."));
2737 for ( size_t n
= 0; n
< 70; n
++ )
2741 for ( size_t m
= 0; m
< 100000; m
++ )
2743 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2745 wxPuts(_T("\ntime is negative - ERROR!"));
2753 wxPuts(_T(", ok."));
2756 #endif // TEST_TIMER
2758 // ----------------------------------------------------------------------------
2760 // ----------------------------------------------------------------------------
2764 #include "wx/vcard.h"
2766 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2769 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2772 wxPrintf(_T("%s%s"),
2773 wxString(_T('\t'), level
).c_str(),
2774 vcObj
->GetName().c_str());
2777 switch ( vcObj
->GetType() )
2779 case wxVCardObject::String
:
2780 case wxVCardObject::UString
:
2783 vcObj
->GetValue(&val
);
2784 value
<< _T('"') << val
<< _T('"');
2788 case wxVCardObject::Int
:
2791 vcObj
->GetValue(&i
);
2792 value
.Printf(_T("%u"), i
);
2796 case wxVCardObject::Long
:
2799 vcObj
->GetValue(&l
);
2800 value
.Printf(_T("%lu"), l
);
2804 case wxVCardObject::None
:
2807 case wxVCardObject::Object
:
2808 value
= _T("<node>");
2812 value
= _T("<unknown value type>");
2816 wxPrintf(_T(" = %s"), value
.c_str());
2819 DumpVObject(level
+ 1, *vcObj
);
2822 vcObj
= vcard
.GetNextProp(&cookie
);
2826 static void DumpVCardAddresses(const wxVCard
& vcard
)
2828 wxPuts(_T("\nShowing all addresses from vCard:\n"));
2832 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2836 int flags
= addr
->GetFlags();
2837 if ( flags
& wxVCardAddress::Domestic
)
2839 flagsStr
<< _T("domestic ");
2841 if ( flags
& wxVCardAddress::Intl
)
2843 flagsStr
<< _T("international ");
2845 if ( flags
& wxVCardAddress::Postal
)
2847 flagsStr
<< _T("postal ");
2849 if ( flags
& wxVCardAddress::Parcel
)
2851 flagsStr
<< _T("parcel ");
2853 if ( flags
& wxVCardAddress::Home
)
2855 flagsStr
<< _T("home ");
2857 if ( flags
& wxVCardAddress::Work
)
2859 flagsStr
<< _T("work ");
2862 wxPrintf(_T("Address %u:\n")
2864 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2867 addr
->GetPostOffice().c_str(),
2868 addr
->GetExtAddress().c_str(),
2869 addr
->GetStreet().c_str(),
2870 addr
->GetLocality().c_str(),
2871 addr
->GetRegion().c_str(),
2872 addr
->GetPostalCode().c_str(),
2873 addr
->GetCountry().c_str()
2877 addr
= vcard
.GetNextAddress(&cookie
);
2881 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2883 wxPuts(_T("\nShowing all phone numbers from vCard:\n"));
2887 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2891 int flags
= phone
->GetFlags();
2892 if ( flags
& wxVCardPhoneNumber::Voice
)
2894 flagsStr
<< _T("voice ");
2896 if ( flags
& wxVCardPhoneNumber::Fax
)
2898 flagsStr
<< _T("fax ");
2900 if ( flags
& wxVCardPhoneNumber::Cellular
)
2902 flagsStr
<< _T("cellular ");
2904 if ( flags
& wxVCardPhoneNumber::Modem
)
2906 flagsStr
<< _T("modem ");
2908 if ( flags
& wxVCardPhoneNumber::Home
)
2910 flagsStr
<< _T("home ");
2912 if ( flags
& wxVCardPhoneNumber::Work
)
2914 flagsStr
<< _T("work ");
2917 wxPrintf(_T("Phone number %u:\n")
2922 phone
->GetNumber().c_str()
2926 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2930 static void TestVCardRead()
2932 wxPuts(_T("*** Testing wxVCard reading ***\n"));
2934 wxVCard
vcard(_T("vcard.vcf"));
2935 if ( !vcard
.IsOk() )
2937 wxPuts(_T("ERROR: couldn't load vCard."));
2941 // read individual vCard properties
2942 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2946 vcObj
->GetValue(&value
);
2951 value
= _T("<none>");
2954 wxPrintf(_T("Full name retrieved directly: %s\n"), value
.c_str());
2957 if ( !vcard
.GetFullName(&value
) )
2959 value
= _T("<none>");
2962 wxPrintf(_T("Full name from wxVCard API: %s\n"), value
.c_str());
2964 // now show how to deal with multiply occuring properties
2965 DumpVCardAddresses(vcard
);
2966 DumpVCardPhoneNumbers(vcard
);
2968 // and finally show all
2969 wxPuts(_T("\nNow dumping the entire vCard:\n")
2970 "-----------------------------\n");
2972 DumpVObject(0, vcard
);
2976 static void TestVCardWrite()
2978 wxPuts(_T("*** Testing wxVCard writing ***\n"));
2981 if ( !vcard
.IsOk() )
2983 wxPuts(_T("ERROR: couldn't create vCard."));
2988 vcard
.SetName("Zeitlin", "Vadim");
2989 vcard
.SetFullName("Vadim Zeitlin");
2990 vcard
.SetOrganization("wxWidgets", "R&D");
2992 // just dump the vCard back
2993 wxPuts(_T("Entire vCard follows:\n"));
2994 wxPuts(vcard
.Write());
2998 #endif // TEST_VCARD
3000 // ----------------------------------------------------------------------------
3002 // ----------------------------------------------------------------------------
3004 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
3010 #include "wx/volume.h"
3012 static const wxChar
*volumeKinds
[] =
3018 _T("network volume"),
3022 static void TestFSVolume()
3024 wxPuts(_T("*** Testing wxFSVolume class ***"));
3026 wxArrayString volumes
= wxFSVolume::GetVolumes();
3027 size_t count
= volumes
.GetCount();
3031 wxPuts(_T("ERROR: no mounted volumes?"));
3035 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3037 for ( size_t n
= 0; n
< count
; n
++ )
3039 wxFSVolume
vol(volumes
[n
]);
3042 wxPuts(_T("ERROR: couldn't create volume"));
3046 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3048 vol
.GetDisplayName().c_str(),
3049 vol
.GetName().c_str(),
3050 volumeKinds
[vol
.GetKind()],
3051 vol
.IsWritable() ? _T("rw") : _T("ro"),
3052 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3057 #endif // TEST_VOLUME
3059 // ----------------------------------------------------------------------------
3060 // wide char and Unicode support
3061 // ----------------------------------------------------------------------------
3065 #include "wx/strconv.h"
3066 #include "wx/fontenc.h"
3067 #include "wx/encconv.h"
3068 #include "wx/buffer.h"
3070 static const unsigned char utf8koi8r
[] =
3072 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3073 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3074 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3075 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3076 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3077 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3078 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3081 static const unsigned char utf8iso8859_1
[] =
3083 0x53, 0x79, 0x73, 0x74, 0xc3, 0xa8, 0x6d, 0x65, 0x73, 0x20, 0x49, 0x6e,
3084 0x74, 0xc3, 0xa9, 0x67, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x20, 0x65,
3085 0x6e, 0x20, 0x4d, 0xc3, 0xa9, 0x63, 0x61, 0x6e, 0x69, 0x71, 0x75, 0x65,
3086 0x20, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x69, 0x71, 0x75, 0x65, 0x20, 0x65,
3087 0x74, 0x20, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x71, 0x75, 0x65, 0
3090 static const unsigned char utf8Invalid
[] =
3092 0x3c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x3e, 0x32, 0x30, 0x30,
3093 0x32, 0xe5, 0xb9, 0xb4, 0x30, 0x39, 0xe6, 0x9c, 0x88, 0x32, 0x35, 0xe6,
3094 0x97, 0xa5, 0x20, 0x30, 0x37, 0xe6, 0x99, 0x82, 0x33, 0x39, 0xe5, 0x88,
3095 0x86, 0x35, 0x37, 0xe7, 0xa7, 0x92, 0x3c, 0x2f, 0x64, 0x69, 0x73, 0x70,
3099 static const struct Utf8Data
3101 const unsigned char *text
;
3103 const wxChar
*charset
;
3104 wxFontEncoding encoding
;
3107 { utf8Invalid
, WXSIZEOF(utf8Invalid
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3108 { utf8koi8r
, WXSIZEOF(utf8koi8r
), _T("koi8-r"), wxFONTENCODING_KOI8
},
3109 { utf8iso8859_1
, WXSIZEOF(utf8iso8859_1
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3112 static void TestUtf8()
3114 wxPuts(_T("*** Testing UTF8 support ***\n"));
3119 for ( size_t n
= 0; n
< WXSIZEOF(utf8data
); n
++ )
3121 const Utf8Data
& u8d
= utf8data
[n
];
3122 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)u8d
.text
,
3123 WXSIZEOF(wbuf
)) == (size_t)-1 )
3125 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3129 wxCSConv
conv(u8d
.charset
);
3130 if ( conv
.WC2MB(buf
, wbuf
, WXSIZEOF(buf
)) == (size_t)-1 )
3132 wxPrintf(_T("ERROR: conversion to %s failed.\n"), u8d
.charset
);
3136 wxPrintf(_T("String in %s: %s\n"), u8d
.charset
, buf
);
3140 wxString
s(wxConvUTF8
.cMB2WC((const char *)u8d
.text
));
3142 s
= _T("<< conversion failed >>");
3143 wxPrintf(_T("String in current cset: %s\n"), s
.c_str());
3147 wxPuts(wxEmptyString
);
3150 static void TestEncodingConverter()
3152 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3154 // using wxEncodingConverter should give the same result as above
3157 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)utf8koi8r
,
3158 WXSIZEOF(utf8koi8r
)) == (size_t)-1 )
3160 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3164 wxEncodingConverter ec
;
3165 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3166 ec
.Convert(wbuf
, buf
);
3167 wxPrintf(_T("The same KOI8-R string using wxEC: %s\n"), buf
);
3170 wxPuts(wxEmptyString
);
3173 #endif // TEST_WCHAR
3175 // ----------------------------------------------------------------------------
3177 // ----------------------------------------------------------------------------
3181 #include "wx/filesys.h"
3182 #include "wx/fs_zip.h"
3183 #include "wx/zipstrm.h"
3185 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3187 static void TestZipStreamRead()
3189 wxPuts(_T("*** Testing ZIP reading ***\n"));
3191 static const wxString filename
= _T("foo");
3192 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3193 wxPrintf(_T("Archive size: %u\n"), istr
.GetSize());
3195 wxPrintf(_T("Dumping the file '%s':\n"), filename
.c_str());
3196 while ( !istr
.Eof() )
3198 wxPutchar(istr
.GetC());
3202 wxPuts(_T("\n----- done ------"));
3205 static void DumpZipDirectory(wxFileSystem
& fs
,
3206 const wxString
& dir
,
3207 const wxString
& indent
)
3209 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3210 TESTFILE_ZIP
, dir
.c_str());
3211 wxString wildcard
= prefix
+ _T("/*");
3213 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3214 while ( !dirname
.empty() )
3216 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3218 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3223 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3225 DumpZipDirectory(fs
, dirname
,
3226 indent
+ wxString(_T(' '), 4));
3228 dirname
= fs
.FindNext();
3231 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3232 while ( !filename
.empty() )
3234 if ( !filename
.StartsWith(prefix
, &filename
) )
3236 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3241 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3243 filename
= fs
.FindNext();
3247 static void TestZipFileSystem()
3249 wxPuts(_T("*** Testing ZIP file system ***\n"));
3251 wxFileSystem::AddHandler(new wxZipFSHandler
);
3253 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3255 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3260 // ----------------------------------------------------------------------------
3262 // ----------------------------------------------------------------------------
3264 #ifdef TEST_DATETIME
3266 #include "wx/math.h"
3267 #include "wx/datetime.h"
3269 // this test miscellaneous static wxDateTime functions
3273 static void TestTimeStatic()
3275 wxPuts(_T("\n*** wxDateTime static methods test ***"));
3277 // some info about the current date
3278 int year
= wxDateTime::GetCurrentYear();
3279 wxPrintf(_T("Current year %d is %sa leap one and has %d days.\n"),
3281 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3282 wxDateTime::GetNumberOfDays(year
));
3284 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3285 wxPrintf(_T("Current month is '%s' ('%s') and it has %d days\n"),
3286 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3287 wxDateTime::GetMonthName(month
).c_str(),
3288 wxDateTime::GetNumberOfDays(month
));
3291 // test time zones stuff
3292 static void TestTimeZones()
3294 wxPuts(_T("\n*** wxDateTime timezone test ***"));
3296 wxDateTime now
= wxDateTime::Now();
3298 wxPrintf(_T("Current GMT time:\t%s\n"), now
.Format(_T("%c"), wxDateTime::GMT0
).c_str());
3299 wxPrintf(_T("Unix epoch (GMT):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::GMT0
).c_str());
3300 wxPrintf(_T("Unix epoch (EST):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::EST
).c_str());
3301 wxPrintf(_T("Current time in Paris:\t%s\n"), now
.Format(_T("%c"), wxDateTime::CET
).c_str());
3302 wxPrintf(_T(" Moscow:\t%s\n"), now
.Format(_T("%c"), wxDateTime::MSK
).c_str());
3303 wxPrintf(_T(" New York:\t%s\n"), now
.Format(_T("%c"), wxDateTime::EST
).c_str());
3305 wxPrintf(_T("%s\n"), wxDateTime::Now().Format(_T("Our timezone is %Z")).c_str());
3307 wxDateTime::Tm tm
= now
.GetTm();
3308 if ( wxDateTime(tm
) != now
)
3310 wxPrintf(_T("ERROR: got %s instead of %s\n"),
3311 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3315 // test some minimal support for the dates outside the standard range
3316 static void TestTimeRange()
3318 wxPuts(_T("\n*** wxDateTime out-of-standard-range dates test ***"));
3320 static const wxChar
*fmt
= _T("%d-%b-%Y %H:%M:%S");
3322 wxPrintf(_T("Unix epoch:\t%s\n"),
3323 wxDateTime(2440587.5).Format(fmt
).c_str());
3324 wxPrintf(_T("Feb 29, 0: \t%s\n"),
3325 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3326 wxPrintf(_T("JDN 0: \t%s\n"),
3327 wxDateTime(0.0).Format(fmt
).c_str());
3328 wxPrintf(_T("Jan 1, 1AD:\t%s\n"),
3329 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3330 wxPrintf(_T("May 29, 2099:\t%s\n"),
3331 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3334 // test DST calculations
3335 static void TestTimeDST()
3337 wxPuts(_T("\n*** wxDateTime DST test ***"));
3339 wxPrintf(_T("DST is%s in effect now.\n\n"),
3340 wxDateTime::Now().IsDST() ? wxEmptyString
: _T(" not"));
3342 for ( int year
= 1990; year
< 2005; year
++ )
3344 wxPrintf(_T("DST period in Europe for year %d: from %s to %s\n"),
3346 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3347 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3353 #if TEST_INTERACTIVE
3355 static void TestDateTimeInteractive()
3357 wxPuts(_T("\n*** interactive wxDateTime tests ***"));
3363 wxPrintf(_T("Enter a date: "));
3364 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
3367 // kill the last '\n'
3368 buf
[wxStrlen(buf
) - 1] = 0;
3371 const wxChar
*p
= dt
.ParseDate(buf
);
3374 wxPrintf(_T("ERROR: failed to parse the date '%s'.\n"), buf
);
3380 wxPrintf(_T("WARNING: parsed only first %u characters.\n"), p
- buf
);
3383 wxPrintf(_T("%s: day %u, week of month %u/%u, week of year %u\n"),
3384 dt
.Format(_T("%b %d, %Y")).c_str(),
3386 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3387 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3388 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3391 wxPuts(_T("\n*** done ***"));
3394 #endif // TEST_INTERACTIVE
3398 static void TestTimeMS()
3400 wxPuts(_T("*** testing millisecond-resolution support in wxDateTime ***"));
3402 wxDateTime dt1
= wxDateTime::Now(),
3403 dt2
= wxDateTime::UNow();
3405 wxPrintf(_T("Now = %s\n"), dt1
.Format(_T("%H:%M:%S:%l")).c_str());
3406 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
3407 wxPrintf(_T("Dummy loop: "));
3408 for ( int i
= 0; i
< 6000; i
++ )
3410 //for ( int j = 0; j < 10; j++ )
3413 s
.Printf(_T("%g"), sqrt((float)i
));
3419 wxPuts(_T(", done"));
3422 dt2
= wxDateTime::UNow();
3423 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
3425 wxPrintf(_T("Loop executed in %s ms\n"), (dt2
- dt1
).Format(_T("%l")).c_str());
3427 wxPuts(_T("\n*** done ***"));
3430 static void TestTimeHolidays()
3432 wxPuts(_T("\n*** testing wxDateTimeHolidayAuthority ***\n"));
3434 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3435 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3436 dtEnd
= dtStart
.GetLastMonthDay();
3438 wxDateTimeArray hol
;
3439 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3441 const wxChar
*format
= _T("%d-%b-%Y (%a)");
3443 wxPrintf(_T("All holidays between %s and %s:\n"),
3444 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3446 size_t count
= hol
.GetCount();
3447 for ( size_t n
= 0; n
< count
; n
++ )
3449 wxPrintf(_T("\t%s\n"), hol
[n
].Format(format
).c_str());
3452 wxPuts(wxEmptyString
);
3455 static void TestTimeZoneBug()
3457 wxPuts(_T("\n*** testing for DST/timezone bug ***\n"));
3459 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3460 for ( int i
= 0; i
< 31; i
++ )
3462 wxPrintf(_T("Date %s: week day %s.\n"),
3463 date
.Format(_T("%d-%m-%Y")).c_str(),
3464 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3466 date
+= wxDateSpan::Day();
3469 wxPuts(wxEmptyString
);
3472 static void TestTimeSpanFormat()
3474 wxPuts(_T("\n*** wxTimeSpan tests ***"));
3476 static const wxChar
*formats
[] =
3478 _T("(default) %H:%M:%S"),
3479 _T("%E weeks and %D days"),
3480 _T("%l milliseconds"),
3481 _T("(with ms) %H:%M:%S:%l"),
3482 _T("100%% of minutes is %M"), // test "%%"
3483 _T("%D days and %H hours"),
3484 _T("or also %S seconds"),
3487 wxTimeSpan
ts1(1, 2, 3, 4),
3489 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3491 wxPrintf(_T("ts1 = %s\tts2 = %s\n"),
3492 ts1
.Format(formats
[n
]).c_str(),
3493 ts2
.Format(formats
[n
]).c_str());
3496 wxPuts(wxEmptyString
);
3501 #endif // TEST_DATETIME
3503 // ----------------------------------------------------------------------------
3504 // wxTextInput/OutputStream
3505 // ----------------------------------------------------------------------------
3507 #ifdef TEST_TEXTSTREAM
3509 #include "wx/txtstrm.h"
3510 #include "wx/wfstream.h"
3512 static void TestTextInputStream()
3514 wxPuts(_T("\n*** wxTextInputStream test ***"));
3516 wxString filename
= _T("testdata.fc");
3517 wxFileInputStream
fsIn(filename
);
3520 wxPuts(_T("ERROR: couldn't open file."));
3524 wxTextInputStream
tis(fsIn
);
3529 const wxString s
= tis
.ReadLine();
3531 // line could be non empty if the last line of the file isn't
3532 // terminated with EOL
3533 if ( fsIn
.Eof() && s
.empty() )
3536 wxPrintf(_T("Line %d: %s\n"), line
++, s
.c_str());
3541 #endif // TEST_TEXTSTREAM
3543 // ----------------------------------------------------------------------------
3545 // ----------------------------------------------------------------------------
3549 #include "wx/thread.h"
3551 static size_t gs_counter
= (size_t)-1;
3552 static wxCriticalSection gs_critsect
;
3553 static wxSemaphore gs_cond
;
3555 class MyJoinableThread
: public wxThread
3558 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3559 { m_n
= n
; Create(); }
3561 // thread execution starts here
3562 virtual ExitCode
Entry();
3568 wxThread::ExitCode
MyJoinableThread::Entry()
3570 unsigned long res
= 1;
3571 for ( size_t n
= 1; n
< m_n
; n
++ )
3575 // it's a loooong calculation :-)
3579 return (ExitCode
)res
;
3582 class MyDetachedThread
: public wxThread
3585 MyDetachedThread(size_t n
, wxChar ch
)
3589 m_cancelled
= false;
3594 // thread execution starts here
3595 virtual ExitCode
Entry();
3598 virtual void OnExit();
3601 size_t m_n
; // number of characters to write
3602 wxChar m_ch
; // character to write
3604 bool m_cancelled
; // false if we exit normally
3607 wxThread::ExitCode
MyDetachedThread::Entry()
3610 wxCriticalSectionLocker
lock(gs_critsect
);
3611 if ( gs_counter
== (size_t)-1 )
3617 for ( size_t n
= 0; n
< m_n
; n
++ )
3619 if ( TestDestroy() )
3629 wxThread::Sleep(100);
3635 void MyDetachedThread::OnExit()
3637 wxLogTrace(_T("thread"), _T("Thread %ld is in OnExit"), GetId());
3639 wxCriticalSectionLocker
lock(gs_critsect
);
3640 if ( !--gs_counter
&& !m_cancelled
)
3644 static void TestDetachedThreads()
3646 wxPuts(_T("\n*** Testing detached threads ***"));
3648 static const size_t nThreads
= 3;
3649 MyDetachedThread
*threads
[nThreads
];
3651 for ( n
= 0; n
< nThreads
; n
++ )
3653 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3656 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3657 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3659 for ( n
= 0; n
< nThreads
; n
++ )
3664 // wait until all threads terminate
3667 wxPuts(wxEmptyString
);
3670 static void TestJoinableThreads()
3672 wxPuts(_T("\n*** Testing a joinable thread (a loooong calculation...) ***"));
3674 // calc 10! in the background
3675 MyJoinableThread
thread(10);
3678 wxPrintf(_T("\nThread terminated with exit code %lu.\n"),
3679 (unsigned long)thread
.Wait());
3682 static void TestThreadSuspend()
3684 wxPuts(_T("\n*** Testing thread suspend/resume functions ***"));
3686 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3690 // this is for this demo only, in a real life program we'd use another
3691 // condition variable which would be signaled from wxThread::Entry() to
3692 // tell us that the thread really started running - but here just wait a
3693 // bit and hope that it will be enough (the problem is, of course, that
3694 // the thread might still not run when we call Pause() which will result
3696 wxThread::Sleep(300);
3698 for ( size_t n
= 0; n
< 3; n
++ )
3702 wxPuts(_T("\nThread suspended"));
3705 // don't sleep but resume immediately the first time
3706 wxThread::Sleep(300);
3708 wxPuts(_T("Going to resume the thread"));
3713 wxPuts(_T("Waiting until it terminates now"));
3715 // wait until the thread terminates
3718 wxPuts(wxEmptyString
);
3721 static void TestThreadDelete()
3723 // As above, using Sleep() is only for testing here - we must use some
3724 // synchronisation object instead to ensure that the thread is still
3725 // running when we delete it - deleting a detached thread which already
3726 // terminated will lead to a crash!
3728 wxPuts(_T("\n*** Testing thread delete function ***"));
3730 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3734 wxPuts(_T("\nDeleted a thread which didn't start to run yet."));
3736 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3740 wxThread::Sleep(300);
3744 wxPuts(_T("\nDeleted a running thread."));
3746 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3750 wxThread::Sleep(300);
3756 wxPuts(_T("\nDeleted a sleeping thread."));
3758 MyJoinableThread
thread3(20);
3763 wxPuts(_T("\nDeleted a joinable thread."));
3765 MyJoinableThread
thread4(2);
3768 wxThread::Sleep(300);
3772 wxPuts(_T("\nDeleted a joinable thread which already terminated."));
3774 wxPuts(wxEmptyString
);
3777 class MyWaitingThread
: public wxThread
3780 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
3783 m_condition
= condition
;
3788 virtual ExitCode
Entry()
3790 wxPrintf(_T("Thread %lu has started running.\n"), GetId());
3795 wxPrintf(_T("Thread %lu starts to wait...\n"), GetId());
3799 m_condition
->Wait();
3802 wxPrintf(_T("Thread %lu finished to wait, exiting.\n"), GetId());
3810 wxCondition
*m_condition
;
3813 static void TestThreadConditions()
3816 wxCondition
condition(mutex
);
3818 // otherwise its difficult to understand which log messages pertain to
3820 //wxLogTrace(_T("thread"), _T("Local condition var is %08x, gs_cond = %08x"),
3821 // condition.GetId(), gs_cond.GetId());
3823 // create and launch threads
3824 MyWaitingThread
*threads
[10];
3827 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
3829 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
3832 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
3837 // wait until all threads run
3838 wxPuts(_T("Main thread is waiting for the other threads to start"));
3841 size_t nRunning
= 0;
3842 while ( nRunning
< WXSIZEOF(threads
) )
3848 wxPrintf(_T("Main thread: %u already running\n"), nRunning
);
3852 wxPuts(_T("Main thread: all threads started up."));
3855 wxThread::Sleep(500);
3858 // now wake one of them up
3859 wxPrintf(_T("Main thread: about to signal the condition.\n"));
3864 wxThread::Sleep(200);
3866 // wake all the (remaining) threads up, so that they can exit
3867 wxPrintf(_T("Main thread: about to broadcast the condition.\n"));
3869 condition
.Broadcast();
3871 // give them time to terminate (dirty!)
3872 wxThread::Sleep(500);
3875 #include "wx/utils.h"
3877 class MyExecThread
: public wxThread
3880 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
3886 virtual ExitCode
Entry()
3888 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
3895 static void TestThreadExec()
3897 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
3899 MyExecThread
thread(_T("true"));
3902 wxPrintf(_T("Main program exit code: %ld.\n"),
3903 wxExecute(_T("false"), wxEXEC_SYNC
));
3905 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
3909 #include "wx/datetime.h"
3911 class MySemaphoreThread
: public wxThread
3914 MySemaphoreThread(int i
, wxSemaphore
*sem
)
3915 : wxThread(wxTHREAD_JOINABLE
),
3922 virtual ExitCode
Entry()
3924 wxPrintf(_T("%s: Thread #%d (%ld) starting to wait for semaphore...\n"),
3925 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
3929 wxPrintf(_T("%s: Thread #%d (%ld) acquired the semaphore.\n"),
3930 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
3934 wxPrintf(_T("%s: Thread #%d (%ld) releasing the semaphore.\n"),
3935 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
3947 WX_DEFINE_ARRAY_PTR(wxThread
*, ArrayThreads
);
3949 static void TestSemaphore()
3951 wxPuts(_T("*** Testing wxSemaphore class. ***"));
3953 static const int SEM_LIMIT
= 3;
3955 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
3956 ArrayThreads threads
;
3958 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
3960 threads
.Add(new MySemaphoreThread(i
, &sem
));
3961 threads
.Last()->Run();
3964 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
3971 #endif // TEST_THREADS
3973 // ----------------------------------------------------------------------------
3975 // ----------------------------------------------------------------------------
3977 #ifdef TEST_SNGLINST
3978 #include "wx/snglinst.h"
3979 #endif // TEST_SNGLINST
3981 int main(int argc
, char **argv
)
3983 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "program");
3985 wxInitializer initializer
;
3988 fprintf(stderr
, "Failed to initialize the wxWidgets library, aborting.");
3993 #ifdef TEST_SNGLINST
3994 wxSingleInstanceChecker checker
;
3995 if ( checker
.Create(_T(".wxconsole.lock")) )
3997 if ( checker
.IsAnotherRunning() )
3999 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4004 // wait some time to give time to launch another instance
4005 wxPrintf(_T("Press \"Enter\" to continue..."));
4008 else // failed to create
4010 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4012 #endif // TEST_SNGLINST
4015 TestCmdLineConvert();
4017 #if wxUSE_CMDLINE_PARSER
4018 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4020 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), _T("show this help message"),
4021 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
4022 { wxCMD_LINE_SWITCH
, _T("v"), _T("verbose"), _T("be verbose") },
4023 { wxCMD_LINE_SWITCH
, _T("q"), _T("quiet"), _T("be quiet") },
4025 { wxCMD_LINE_OPTION
, _T("o"), _T("output"), _T("output file") },
4026 { wxCMD_LINE_OPTION
, _T("i"), _T("input"), _T("input dir") },
4027 { wxCMD_LINE_OPTION
, _T("s"), _T("size"), _T("output block size"),
4028 wxCMD_LINE_VAL_NUMBER
},
4029 { wxCMD_LINE_OPTION
, _T("d"), _T("date"), _T("output file date"),
4030 wxCMD_LINE_VAL_DATE
},
4032 { wxCMD_LINE_PARAM
, NULL
, NULL
, _T("input file"),
4033 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4039 wxChar
**wargv
= new wxChar
*[argc
+ 1];
4044 for (n
= 0; n
< argc
; n
++ )
4046 wxMB2WXbuf warg
= wxConvertMB2WX(argv
[n
]);
4047 wargv
[n
] = wxStrdup(warg
);
4054 #endif // wxUSE_UNICODE
4056 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4060 for ( int n
= 0; n
< argc
; n
++ )
4065 #endif // wxUSE_UNICODE
4067 parser
.AddOption(_T("project_name"), _T(""), _T("full path to project file"),
4068 wxCMD_LINE_VAL_STRING
,
4069 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4071 switch ( parser
.Parse() )
4074 wxLogMessage(_T("Help was given, terminating."));
4078 ShowCmdLine(parser
);
4082 wxLogMessage(_T("Syntax error detected, aborting."));
4085 #endif // wxUSE_CMDLINE_PARSER
4087 #endif // TEST_CMDLINE
4097 #ifdef TEST_DLLLOADER
4099 #endif // TEST_DLLLOADER
4103 #endif // TEST_ENVIRON
4107 #endif // TEST_EXECUTE
4109 #ifdef TEST_FILECONF
4111 #endif // TEST_FILECONF
4115 #endif // TEST_LOCALE
4118 wxPuts(_T("*** Testing wxLog ***"));
4121 for ( size_t n
= 0; n
< 8000; n
++ )
4123 s
<< (wxChar
)(_T('A') + (n
% 26));
4126 wxLogWarning(_T("The length of the string is %lu"),
4127 (unsigned long)s
.length());
4130 msg
.Printf(_T("A very very long message: '%s', the end!\n"), s
.c_str());
4132 // this one shouldn't be truncated
4135 // but this one will because log functions use fixed size buffer
4136 // (note that it doesn't need '\n' at the end neither - will be added
4138 wxLogMessage(_T("A very very long message 2: '%s', the end!"), s
.c_str());
4147 #ifdef TEST_FILENAME
4148 TestFileNameConstruction();
4149 TestFileNameMakeRelative();
4150 TestFileNameMakeAbsolute();
4151 TestFileNameSplit();
4154 TestFileNameDirManip();
4155 TestFileNameComparison();
4156 TestFileNameOperations();
4157 #endif // TEST_FILENAME
4159 #ifdef TEST_FILETIME
4164 #endif // TEST_FILETIME
4167 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4168 if ( TestFtpConnect() )
4178 #if TEST_INTERACTIVE
4179 TestFtpInteractive();
4182 //else: connecting to the FTP server failed
4190 wxLog::AddTraceMask(_T("mime"));
4194 TestMimeAssociate();
4199 #ifdef TEST_INFO_FUNCTIONS
4204 #if TEST_INTERACTIVE
4208 #endif // TEST_INFO_FUNCTIONS
4210 #ifdef TEST_PATHLIST
4212 #endif // TEST_PATHLIST
4220 #endif // TEST_PRINTF
4227 #endif // TEST_REGCONF
4229 #if defined TEST_REGEX && TEST_INTERACTIVE
4230 TestRegExInteractive();
4231 #endif // defined TEST_REGEX && TEST_INTERACTIVE
4233 #ifdef TEST_REGISTRY
4235 TestRegistryAssociation();
4236 #endif // TEST_REGISTRY
4241 #endif // TEST_SOCKETS
4248 #endif // TEST_STREAMS
4250 #ifdef TEST_TEXTSTREAM
4251 TestTextInputStream();
4252 #endif // TEST_TEXTSTREAM
4255 int nCPUs
= wxThread::GetCPUCount();
4256 wxPrintf(_T("This system has %d CPUs\n"), nCPUs
);
4258 wxThread::SetConcurrency(nCPUs
);
4260 TestJoinableThreads();
4263 TestJoinableThreads();
4264 TestDetachedThreads();
4265 TestThreadSuspend();
4267 TestThreadConditions();
4271 #endif // TEST_THREADS
4275 #endif // TEST_TIMER
4277 #ifdef TEST_DATETIME
4289 TestTimeArithmetics();
4291 TestTimeSpanFormat();
4297 #if TEST_INTERACTIVE
4298 TestDateTimeInteractive();
4300 #endif // TEST_DATETIME
4302 #ifdef TEST_SCOPEGUARD
4306 #ifdef TEST_STDPATHS
4307 TestStandardPaths();
4311 wxPuts(_T("Sleeping for 3 seconds... z-z-z-z-z..."));
4313 #endif // TEST_USLEEP
4318 #endif // TEST_VCARD
4322 #endif // TEST_VOLUME
4326 TestEncodingConverter();
4327 #endif // TEST_WCHAR
4330 TestZipStreamRead();
4331 TestZipFileSystem();