1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: A sample console (as opposed to GUI) program using wxWidgets
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // IMPORTANT NOTE FOR WXWIDGETS USERS:
13 // If you're a wxWidgets user and you're looking at this file to learn how to
14 // structure a wxWidgets console application, then you don't have much to learn.
15 // This application is used more for testing rather than as sample but
16 // basically the following simple block is enough for you to start your
17 // own console application:
20 int main(int argc, char **argv)
22 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "program");
24 wxInitializer initializer;
27 fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.");
31 static const wxCmdLineEntryDesc cmdLineDesc[] =
33 { wxCMD_LINE_SWITCH, "h", "help", "show this help message",
34 wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
35 // ... your other command line options here...
40 wxCmdLineParser parser(cmdLineDesc, argc, wxArgv);
41 switch ( parser.Parse() )
44 wxLogMessage(_T("Help was given, terminating."));
48 // everything is ok; proceed
52 wxLogMessage(_T("Syntax error detected, aborting."));
56 // do something useful here
63 // ============================================================================
65 // ============================================================================
67 // ----------------------------------------------------------------------------
69 // ----------------------------------------------------------------------------
75 #include "wx/string.h"
77 #include "wx/filename.h"
80 #include "wx/apptrait.h"
81 #include "wx/platinfo.h"
82 #include "wx/wxchar.h"
84 // without this pragma, the stupid compiler precompiles #defines below so that
85 // changing them doesn't "take place" later!
90 // ----------------------------------------------------------------------------
91 // conditional compilation
92 // ----------------------------------------------------------------------------
95 A note about all these conditional compilation macros: this file is used
96 both as a test suite for various non-GUI wxWidgets classes and as a
97 scratchpad for quick tests. So there are two compilation modes: if you
98 define TEST_ALL all tests are run, otherwise you may enable the individual
99 tests individually in the "#else" branch below.
102 // what to test (in alphabetic order)? Define TEST_ALL to 0 to do a single
103 // test, define it to 1 to do all tests.
109 #define TEST_DATETIME
114 #define TEST_FILECONF
115 #define TEST_FILENAME
116 #define TEST_FILETIME
118 #define TEST_INFO_FUNCTIONS
123 #define TEST_PATHLIST
127 #define TEST_REGISTRY
128 #define TEST_SCOPEGUARD
129 #define TEST_SNGLINST
130 // #define TEST_SOCKETS --FIXME! (RN)
131 #define TEST_STACKWALKER
132 #define TEST_STDPATHS
134 #define TEST_TEXTSTREAM
137 // #define TEST_VCARD -- don't enable this (VZ)
138 // #define TEST_VOLUME --FIXME! (RN)
141 #else // #if TEST_ALL
145 // some tests are interactive, define this to run them
146 #ifdef TEST_INTERACTIVE
147 #undef TEST_INTERACTIVE
149 #define TEST_INTERACTIVE 1
151 #define TEST_INTERACTIVE 0
154 // ============================================================================
156 // ============================================================================
158 // ----------------------------------------------------------------------------
160 // ----------------------------------------------------------------------------
162 #if defined(TEST_SOCKETS)
164 // replace TABs with \t and CRs with \n
165 static wxString
MakePrintable(const wxChar
*s
)
168 (void)str
.Replace(_T("\t"), _T("\\t"));
169 (void)str
.Replace(_T("\n"), _T("\\n"));
170 (void)str
.Replace(_T("\r"), _T("\\r"));
175 #endif // MakePrintable() is used
177 // ----------------------------------------------------------------------------
179 // ----------------------------------------------------------------------------
183 #include "wx/cmdline.h"
184 #include "wx/datetime.h"
186 #if wxUSE_CMDLINE_PARSER
188 static void ShowCmdLine(const wxCmdLineParser
& parser
)
190 wxString s
= _T("Command line parsed successfully:\nInput files: ");
192 size_t count
= parser
.GetParamCount();
193 for ( size_t param
= 0; param
< count
; param
++ )
195 s
<< parser
.GetParam(param
) << ' ';
199 << _T("Verbose:\t") << (parser
.Found(_T("v")) ? _T("yes") : _T("no")) << '\n'
200 << _T("Quiet:\t") << (parser
.Found(_T("q")) ? _T("yes") : _T("no")) << '\n';
206 if ( parser
.Found(_T("o"), &strVal
) )
207 s
<< _T("Output file:\t") << strVal
<< '\n';
208 if ( parser
.Found(_T("i"), &strVal
) )
209 s
<< _T("Input dir:\t") << strVal
<< '\n';
210 if ( parser
.Found(_T("s"), &lVal
) )
211 s
<< _T("Size:\t") << lVal
<< '\n';
212 if ( parser
.Found(_T("f"), &dVal
) )
213 s
<< _T("Double:\t") << dVal
<< '\n';
214 if ( parser
.Found(_T("d"), &dt
) )
215 s
<< _T("Date:\t") << dt
.FormatISODate() << '\n';
216 if ( parser
.Found(_T("project_name"), &strVal
) )
217 s
<< _T("Project:\t") << strVal
<< '\n';
222 #endif // wxUSE_CMDLINE_PARSER
224 static void TestCmdLineConvert()
226 static const wxChar
*cmdlines
[] =
229 _T("-a \"-bstring 1\" -c\"string 2\" \"string 3\""),
230 _T("literal \\\" and \"\""),
233 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
235 const wxChar
*cmdline
= cmdlines
[n
];
236 wxPrintf(_T("Parsing: %s\n"), cmdline
);
237 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
239 size_t count
= args
.GetCount();
240 wxPrintf(_T("\targc = %u\n"), count
);
241 for ( size_t arg
= 0; arg
< count
; arg
++ )
243 wxPrintf(_T("\targv[%u] = %s\n"), arg
, args
[arg
].c_str());
248 #endif // TEST_CMDLINE
250 // ----------------------------------------------------------------------------
252 // ----------------------------------------------------------------------------
259 static const wxChar
*ROOTDIR
= _T("/");
260 static const wxChar
*TESTDIR
= _T("/usr/local/share");
261 #elif defined(__WXMSW__) || defined(__DOS__) || defined(__OS2__)
262 static const wxChar
*ROOTDIR
= _T("c:\\");
263 static const wxChar
*TESTDIR
= _T("d:\\");
265 #error "don't know where the root directory is"
268 static void TestDirEnumHelper(wxDir
& dir
,
269 int flags
= wxDIR_DEFAULT
,
270 const wxString
& filespec
= wxEmptyString
)
274 if ( !dir
.IsOpened() )
277 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
280 wxPrintf(_T("\t%s\n"), filename
.c_str());
282 cont
= dir
.GetNext(&filename
);
285 wxPuts(wxEmptyString
);
290 static void TestDirEnum()
292 wxPuts(_T("*** Testing wxDir::GetFirst/GetNext ***"));
294 wxString cwd
= wxGetCwd();
295 if ( !wxDir::Exists(cwd
) )
297 wxPrintf(_T("ERROR: current directory '%s' doesn't exist?\n"), cwd
.c_str());
302 if ( !dir
.IsOpened() )
304 wxPrintf(_T("ERROR: failed to open current directory '%s'.\n"), cwd
.c_str());
308 wxPuts(_T("Enumerating everything in current directory:"));
309 TestDirEnumHelper(dir
);
311 wxPuts(_T("Enumerating really everything in current directory:"));
312 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
314 wxPuts(_T("Enumerating object files in current directory:"));
315 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, _T("*.o*"));
317 wxPuts(_T("Enumerating directories in current directory:"));
318 TestDirEnumHelper(dir
, wxDIR_DIRS
);
320 wxPuts(_T("Enumerating files in current directory:"));
321 TestDirEnumHelper(dir
, wxDIR_FILES
);
323 wxPuts(_T("Enumerating files including hidden in current directory:"));
324 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
328 wxPuts(_T("Enumerating everything in root directory:"));
329 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
331 wxPuts(_T("Enumerating directories in root directory:"));
332 TestDirEnumHelper(dir
, wxDIR_DIRS
);
334 wxPuts(_T("Enumerating files in root directory:"));
335 TestDirEnumHelper(dir
, wxDIR_FILES
);
337 wxPuts(_T("Enumerating files including hidden in root directory:"));
338 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
340 wxPuts(_T("Enumerating files in non existing directory:"));
341 wxDir
dirNo(_T("nosuchdir"));
342 TestDirEnumHelper(dirNo
);
347 class DirPrintTraverser
: public wxDirTraverser
350 virtual wxDirTraverseResult
OnFile(const wxString
& WXUNUSED(filename
))
352 return wxDIR_CONTINUE
;
355 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
357 wxString path
, name
, ext
;
358 wxFileName::SplitPath(dirname
, &path
, &name
, &ext
);
361 name
<< _T('.') << ext
;
364 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
366 if ( wxIsPathSeparator(*p
) )
370 wxPrintf(_T("%s%s\n"), indent
.c_str(), name
.c_str());
372 return wxDIR_CONTINUE
;
376 static void TestDirTraverse()
378 wxPuts(_T("*** Testing wxDir::Traverse() ***"));
382 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
383 wxPrintf(_T("There are %u files under '%s'\n"), n
, TESTDIR
);
386 wxPrintf(_T("First one is '%s'\n"), files
[0u].c_str());
387 wxPrintf(_T(" last one is '%s'\n"), files
[n
- 1].c_str());
390 // enum again with custom traverser
391 wxPuts(_T("Now enumerating directories:"));
393 DirPrintTraverser traverser
;
394 dir
.Traverse(traverser
, wxEmptyString
, wxDIR_DIRS
| wxDIR_HIDDEN
);
399 static void TestDirExists()
401 wxPuts(_T("*** Testing wxDir::Exists() ***"));
403 static const wxChar
*dirnames
[] =
406 #if defined(__WXMSW__)
409 _T("\\\\share\\file"),
413 _T("c:\\autoexec.bat"),
414 #elif defined(__UNIX__)
423 for ( size_t n
= 0; n
< WXSIZEOF(dirnames
); n
++ )
425 wxPrintf(_T("%-40s: %s\n"),
427 wxDir::Exists(dirnames
[n
]) ? _T("exists")
428 : _T("doesn't exist"));
436 // ----------------------------------------------------------------------------
438 // ----------------------------------------------------------------------------
442 #include "wx/dynlib.h"
444 static void TestDllLoad()
446 #if defined(__WXMSW__)
447 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
448 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
449 #elif defined(__UNIX__)
450 // weird: using just libc.so does *not* work!
451 static const wxChar
*LIB_NAME
= _T("/lib/libc.so.6");
452 static const wxChar
*FUNC_NAME
= _T("strlen");
454 #error "don't know how to test wxDllLoader on this platform"
457 wxPuts(_T("*** testing basic wxDynamicLibrary functions ***\n"));
459 wxDynamicLibrary
lib(LIB_NAME
);
460 if ( !lib
.IsLoaded() )
462 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
466 typedef int (wxSTDCALL
*wxStrlenType
)(const char *);
467 wxStrlenType pfnStrlen
= (wxStrlenType
)lib
.GetSymbol(FUNC_NAME
);
470 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
471 FUNC_NAME
, LIB_NAME
);
475 wxPrintf(_T("Calling %s dynamically loaded from %s "),
476 FUNC_NAME
, LIB_NAME
);
478 if ( pfnStrlen("foo") != 3 )
480 wxPrintf(_T("ERROR: loaded function is not wxStrlen()!\n"));
484 wxPuts(_T("... ok"));
489 static const wxChar
*FUNC_NAME_AW
= _T("lstrlen");
491 typedef int (wxSTDCALL
*wxStrlenTypeAorW
)(const wxChar
*);
493 pfnStrlenAorW
= (wxStrlenTypeAorW
)lib
.GetSymbolAorW(FUNC_NAME_AW
);
494 if ( !pfnStrlenAorW
)
496 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
497 FUNC_NAME_AW
, LIB_NAME
);
501 if ( pfnStrlenAorW(_T("foobar")) != 6 )
503 wxPrintf(_T("ERROR: loaded function is not wxStrlen()!\n"));
510 #if defined(__WXMSW__) || defined(__UNIX__)
512 static void TestDllListLoaded()
514 wxPuts(_T("*** testing wxDynamicLibrary::ListLoaded() ***\n"));
516 puts("\nLoaded modules:");
517 wxDynamicLibraryDetailsArray dlls
= wxDynamicLibrary::ListLoaded();
518 const size_t count
= dlls
.GetCount();
519 for ( size_t n
= 0; n
< count
; ++n
)
521 const wxDynamicLibraryDetails
& details
= dlls
[n
];
522 printf("%-45s", (const char *)details
.GetPath().mb_str());
526 if ( details
.GetAddress(&addr
, &len
) )
528 printf(" %08lx:%08lx",
529 (unsigned long)addr
, (unsigned long)((char *)addr
+ len
));
532 printf(" %s\n", (const char *)details
.GetVersion().mb_str());
538 #endif // TEST_DYNLIB
540 // ----------------------------------------------------------------------------
542 // ----------------------------------------------------------------------------
546 #include "wx/utils.h"
548 static wxString
MyGetEnv(const wxString
& var
)
551 if ( !wxGetEnv(var
, &val
) )
554 val
= wxString(_T('\'')) + val
+ _T('\'');
559 static void TestEnvironment()
561 const wxChar
*var
= _T("wxTestVar");
563 wxPuts(_T("*** testing environment access functions ***"));
565 wxPrintf(_T("Initially getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
566 wxSetEnv(var
, _T("value for wxTestVar"));
567 wxPrintf(_T("After wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
568 wxSetEnv(var
, _T("another value"));
569 wxPrintf(_T("After 2nd wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
571 wxPrintf(_T("After wxUnsetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
572 wxPrintf(_T("PATH = %s\n"), MyGetEnv(_T("PATH")).c_str());
575 #endif // TEST_ENVIRON
577 // ----------------------------------------------------------------------------
579 // ----------------------------------------------------------------------------
584 #include "wx/ffile.h"
585 #include "wx/textfile.h"
587 static void TestFileRead()
589 wxPuts(_T("*** wxFile read test ***"));
591 wxFile
file(_T("testdata.fc"));
592 if ( file
.IsOpened() )
594 wxPrintf(_T("File length: %lu\n"), file
.Length());
596 wxPuts(_T("File dump:\n----------"));
598 static const size_t len
= 1024;
602 size_t nRead
= file
.Read(buf
, len
);
603 if ( nRead
== (size_t)wxInvalidOffset
)
605 wxPrintf(_T("Failed to read the file."));
609 fwrite(buf
, nRead
, 1, stdout
);
615 wxPuts(_T("----------"));
619 wxPrintf(_T("ERROR: can't open test file.\n"));
622 wxPuts(wxEmptyString
);
625 static void TestTextFileRead()
627 wxPuts(_T("*** wxTextFile read test ***"));
629 wxTextFile
file(_T("testdata.fc"));
632 wxPrintf(_T("Number of lines: %u\n"), file
.GetLineCount());
633 wxPrintf(_T("Last line: '%s'\n"), file
.GetLastLine().c_str());
637 wxPuts(_T("\nDumping the entire file:"));
638 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
640 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
642 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
644 wxPuts(_T("\nAnd now backwards:"));
645 for ( s
= file
.GetLastLine();
646 file
.GetCurrentLine() != 0;
647 s
= file
.GetPrevLine() )
649 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
651 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
655 wxPrintf(_T("ERROR: can't open '%s'\n"), file
.GetName());
658 wxPuts(wxEmptyString
);
661 static void TestFileCopy()
663 wxPuts(_T("*** Testing wxCopyFile ***"));
665 static const wxChar
*filename1
= _T("testdata.fc");
666 static const wxChar
*filename2
= _T("test2");
667 if ( !wxCopyFile(filename1
, filename2
) )
669 wxPuts(_T("ERROR: failed to copy file"));
673 wxFFile
f1(filename1
, _T("rb")),
674 f2(filename2
, _T("rb"));
676 if ( !f1
.IsOpened() || !f2
.IsOpened() )
678 wxPuts(_T("ERROR: failed to open file(s)"));
683 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
685 wxPuts(_T("ERROR: failed to read file(s)"));
689 if ( (s1
.length() != s2
.length()) ||
690 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
692 wxPuts(_T("ERROR: copy error!"));
696 wxPuts(_T("File was copied ok."));
702 if ( !wxRemoveFile(filename2
) )
704 wxPuts(_T("ERROR: failed to remove the file"));
707 wxPuts(wxEmptyString
);
710 static void TestTempFile()
712 wxPuts(_T("*** wxTempFile test ***"));
715 if ( tmpFile
.Open(_T("test2")) && tmpFile
.Write(_T("the answer is 42")) )
717 if ( tmpFile
.Commit() )
718 wxPuts(_T("File committed."));
720 wxPuts(_T("ERROR: could't commit temp file."));
722 wxRemoveFile(_T("test2"));
725 wxPuts(wxEmptyString
);
730 // ----------------------------------------------------------------------------
732 // ----------------------------------------------------------------------------
736 #include "wx/confbase.h"
737 #include "wx/fileconf.h"
739 static const struct FileConfTestData
741 const wxChar
*name
; // value name
742 const wxChar
*value
; // the value from the file
745 { _T("value1"), _T("one") },
746 { _T("value2"), _T("two") },
747 { _T("novalue"), _T("default") },
750 static void TestFileConfRead()
752 wxPuts(_T("*** testing wxFileConfig loading/reading ***"));
754 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
755 _T("testdata.fc"), wxEmptyString
,
756 wxCONFIG_USE_RELATIVE_PATH
);
758 // test simple reading
759 wxPuts(_T("\nReading config file:"));
760 wxString
defValue(_T("default")), value
;
761 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
763 const FileConfTestData
& data
= fcTestData
[n
];
764 value
= fileconf
.Read(data
.name
, defValue
);
765 wxPrintf(_T("\t%s = %s "), data
.name
, value
.c_str());
766 if ( value
== data
.value
)
772 wxPrintf(_T("(ERROR: should be %s)\n"), data
.value
);
776 // test enumerating the entries
777 wxPuts(_T("\nEnumerating all root entries:"));
780 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
783 wxPrintf(_T("\t%s = %s\n"),
785 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
787 cont
= fileconf
.GetNextEntry(name
, dummy
);
790 static const wxChar
*testEntry
= _T("TestEntry");
791 wxPrintf(_T("\nTesting deletion of newly created \"Test\" entry: "));
792 fileconf
.Write(testEntry
, _T("A value"));
793 fileconf
.DeleteEntry(testEntry
);
794 wxPrintf(fileconf
.HasEntry(testEntry
) ? _T("ERROR\n") : _T("ok\n"));
797 #endif // TEST_FILECONF
799 // ----------------------------------------------------------------------------
801 // ----------------------------------------------------------------------------
805 #include "wx/filename.h"
808 static void DumpFileName(const wxChar
*desc
, const wxFileName
& fn
)
812 wxString full
= fn
.GetFullPath();
814 wxString vol
, path
, name
, ext
;
815 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
817 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
818 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
820 wxFileName::SplitPath(full
, &path
, &name
, &ext
);
821 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
822 path
.c_str(), name
.c_str(), ext
.c_str());
824 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
825 wxPrintf(_T("with volume: \t'%s'\n"),
826 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
827 wxPrintf(_T("with separator:\t'%s'\n"),
828 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
829 wxPrintf(_T("with both: \t'%s'\n"),
830 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
832 wxPuts(_T("The directories in the path are:"));
833 wxArrayString dirs
= fn
.GetDirs();
834 size_t count
= dirs
.GetCount();
835 for ( size_t n
= 0; n
< count
; n
++ )
837 wxPrintf(_T("\t%u: %s\n"), n
, dirs
[n
].c_str());
842 static void TestFileNameTemp()
844 wxPuts(_T("*** testing wxFileName temp file creation ***"));
846 static const wxChar
*tmpprefixes
[] =
854 _T("/tmp/foo/bar"), // this one must be an error
858 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
860 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
863 // "error" is not in upper case because it may be ok
864 wxPrintf(_T("Prefix '%s'\t-> error\n"), tmpprefixes
[n
]);
868 wxPrintf(_T("Prefix '%s'\t-> temp file '%s'\n"),
869 tmpprefixes
[n
], path
.c_str());
871 if ( !wxRemoveFile(path
) )
873 wxLogWarning(_T("Failed to remove temp file '%s'"),
880 static void TestFileNameDirManip()
882 // TODO: test AppendDir(), RemoveDir(), ...
885 static void TestFileNameComparison()
890 static void TestFileNameOperations()
895 static void TestFileNameCwd()
900 #endif // TEST_FILENAME
902 // ----------------------------------------------------------------------------
903 // wxFileName time functions
904 // ----------------------------------------------------------------------------
908 #include "wx/filename.h"
909 #include "wx/datetime.h"
911 static void TestFileGetTimes()
913 wxFileName
fn(_T("testdata.fc"));
915 wxDateTime dtAccess
, dtMod
, dtCreate
;
916 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
918 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
922 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
924 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
925 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
926 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
927 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
932 static void TestFileSetTimes()
934 wxFileName
fn(_T("testdata.fc"));
938 wxPrintf(_T("ERROR: Touch() failed.\n"));
943 #endif // TEST_FILETIME
945 // ----------------------------------------------------------------------------
947 // ----------------------------------------------------------------------------
952 #include "wx/utils.h" // for wxSetEnv
954 static wxLocale gs_localeDefault
;
955 // NOTE: don't init it here as it needs a wxAppTraits object
956 // and thus must be init-ed after creation of the wxInitializer
957 // class in the main()
959 // find the name of the language from its value
960 static const wxChar
*GetLangName(int lang
)
962 static const wxChar
*languageNames
[] =
972 _T("ARABIC_ALGERIA"),
973 _T("ARABIC_BAHRAIN"),
978 _T("ARABIC_LEBANON"),
980 _T("ARABIC_MOROCCO"),
983 _T("ARABIC_SAUDI_ARABIA"),
986 _T("ARABIC_TUNISIA"),
993 _T("AZERI_CYRILLIC"),
1008 _T("CHINESE_SIMPLIFIED"),
1009 _T("CHINESE_TRADITIONAL"),
1010 _T("CHINESE_HONGKONG"),
1011 _T("CHINESE_MACAU"),
1012 _T("CHINESE_SINGAPORE"),
1013 _T("CHINESE_TAIWAN"),
1019 _T("DUTCH_BELGIAN"),
1023 _T("ENGLISH_AUSTRALIA"),
1024 _T("ENGLISH_BELIZE"),
1025 _T("ENGLISH_BOTSWANA"),
1026 _T("ENGLISH_CANADA"),
1027 _T("ENGLISH_CARIBBEAN"),
1028 _T("ENGLISH_DENMARK"),
1030 _T("ENGLISH_JAMAICA"),
1031 _T("ENGLISH_NEW_ZEALAND"),
1032 _T("ENGLISH_PHILIPPINES"),
1033 _T("ENGLISH_SOUTH_AFRICA"),
1034 _T("ENGLISH_TRINIDAD"),
1035 _T("ENGLISH_ZIMBABWE"),
1043 _T("FRENCH_BELGIAN"),
1044 _T("FRENCH_CANADIAN"),
1045 _T("FRENCH_LUXEMBOURG"),
1046 _T("FRENCH_MONACO"),
1052 _T("GERMAN_AUSTRIAN"),
1053 _T("GERMAN_BELGIUM"),
1054 _T("GERMAN_LIECHTENSTEIN"),
1055 _T("GERMAN_LUXEMBOURG"),
1073 _T("ITALIAN_SWISS"),
1078 _T("KASHMIRI_INDIA"),
1096 _T("MALAY_BRUNEI_DARUSSALAM"),
1097 _T("MALAY_MALAYSIA"),
1107 _T("NORWEGIAN_BOKMAL"),
1108 _T("NORWEGIAN_NYNORSK"),
1115 _T("PORTUGUESE_BRAZILIAN"),
1118 _T("RHAETO_ROMANCE"),
1121 _T("RUSSIAN_UKRAINE"),
1127 _T("SERBIAN_CYRILLIC"),
1128 _T("SERBIAN_LATIN"),
1129 _T("SERBO_CROATIAN"),
1140 _T("SPANISH_ARGENTINA"),
1141 _T("SPANISH_BOLIVIA"),
1142 _T("SPANISH_CHILE"),
1143 _T("SPANISH_COLOMBIA"),
1144 _T("SPANISH_COSTA_RICA"),
1145 _T("SPANISH_DOMINICAN_REPUBLIC"),
1146 _T("SPANISH_ECUADOR"),
1147 _T("SPANISH_EL_SALVADOR"),
1148 _T("SPANISH_GUATEMALA"),
1149 _T("SPANISH_HONDURAS"),
1150 _T("SPANISH_MEXICAN"),
1151 _T("SPANISH_MODERN"),
1152 _T("SPANISH_NICARAGUA"),
1153 _T("SPANISH_PANAMA"),
1154 _T("SPANISH_PARAGUAY"),
1156 _T("SPANISH_PUERTO_RICO"),
1157 _T("SPANISH_URUGUAY"),
1159 _T("SPANISH_VENEZUELA"),
1163 _T("SWEDISH_FINLAND"),
1181 _T("URDU_PAKISTAN"),
1183 _T("UZBEK_CYRILLIC"),
1196 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1197 return languageNames
[lang
];
1199 return _T("INVALID");
1202 static void TestDefaultLang()
1204 wxPuts(_T("*** Testing wxLocale::GetSystemLanguage ***"));
1206 gs_localeDefault
.Init(wxLANGUAGE_ENGLISH
);
1208 static const wxChar
*langStrings
[] =
1210 NULL
, // system default
1217 _T("de_DE.iso88591"),
1219 _T("?"), // invalid lang spec
1220 _T("klingonese"), // I bet on some systems it does exist...
1223 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1224 wxLocale::GetSystemEncodingName().c_str(),
1225 wxLocale::GetSystemEncoding());
1227 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1229 const wxChar
*langStr
= langStrings
[n
];
1232 // FIXME: this doesn't do anything at all under Windows, we need
1233 // to create a new wxLocale!
1234 wxSetEnv(_T("LC_ALL"), langStr
);
1237 int lang
= gs_localeDefault
.GetSystemLanguage();
1238 wxPrintf(_T("Locale for '%s' is %s.\n"),
1239 langStr
? langStr
: _T("system default"), GetLangName(lang
));
1243 #endif // TEST_LOCALE
1245 // ----------------------------------------------------------------------------
1247 // ----------------------------------------------------------------------------
1251 #include "wx/mimetype.h"
1253 static void TestMimeEnum()
1255 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1257 wxArrayString mimetypes
;
1259 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1261 wxPrintf(_T("*** All %u known filetypes: ***\n"), count
);
1266 for ( size_t n
= 0; n
< count
; n
++ )
1268 wxFileType
*filetype
=
1269 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1272 wxPrintf(_T("nothing known about the filetype '%s'!\n"),
1273 mimetypes
[n
].c_str());
1277 filetype
->GetDescription(&desc
);
1278 filetype
->GetExtensions(exts
);
1280 filetype
->GetIcon(NULL
);
1283 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1286 extsAll
<< _T(", ");
1290 wxPrintf(_T("\t%s: %s (%s)\n"),
1291 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1294 wxPuts(wxEmptyString
);
1297 static void TestMimeFilename()
1299 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1301 static const wxChar
*filenames
[] =
1309 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1311 const wxString fname
= filenames
[n
];
1312 wxString ext
= fname
.AfterLast(_T('.'));
1313 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1316 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1321 if ( !ft
->GetDescription(&desc
) )
1322 desc
= _T("<no description>");
1325 if ( !ft
->GetOpenCommand(&cmd
,
1326 wxFileType::MessageParameters(fname
, wxEmptyString
)) )
1327 cmd
= _T("<no command available>");
1329 cmd
= wxString(_T('"')) + cmd
+ _T('"');
1331 wxPrintf(_T("To open %s (%s) do %s.\n"),
1332 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1338 wxPuts(wxEmptyString
);
1341 // these tests were broken by wxMimeTypesManager changes, temporarily disabling
1344 static void TestMimeOverride()
1346 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1348 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1349 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1351 if ( wxFile::Exists(mailcap
) )
1352 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1354 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1356 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1359 if ( wxFile::Exists(mimetypes
) )
1360 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1362 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1364 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1367 wxPuts(wxEmptyString
);
1370 static void TestMimeAssociate()
1372 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1374 wxFileTypeInfo
ftInfo(
1375 _T("application/x-xyz"),
1376 _T("xyzview '%s'"), // open cmd
1377 _T(""), // print cmd
1378 _T("XYZ File"), // description
1379 _T(".xyz"), // extensions
1380 wxNullPtr
// end of extensions
1382 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1384 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1387 wxPuts(_T("ERROR: failed to create association!"));
1391 // TODO: read it back
1395 wxPuts(wxEmptyString
);
1402 // ----------------------------------------------------------------------------
1403 // module dependencies feature
1404 // ----------------------------------------------------------------------------
1408 #include "wx/module.h"
1410 class wxTestModule
: public wxModule
1413 virtual bool OnInit() { wxPrintf(_T("Load module: %s\n"), GetClassInfo()->GetClassName()); return true; }
1414 virtual void OnExit() { wxPrintf(_T("Unload module: %s\n"), GetClassInfo()->GetClassName()); }
1417 class wxTestModuleA
: public wxTestModule
1422 DECLARE_DYNAMIC_CLASS(wxTestModuleA
)
1425 class wxTestModuleB
: public wxTestModule
1430 DECLARE_DYNAMIC_CLASS(wxTestModuleB
)
1433 class wxTestModuleC
: public wxTestModule
1438 DECLARE_DYNAMIC_CLASS(wxTestModuleC
)
1441 class wxTestModuleD
: public wxTestModule
1446 DECLARE_DYNAMIC_CLASS(wxTestModuleD
)
1449 IMPLEMENT_DYNAMIC_CLASS(wxTestModuleC
, wxModule
)
1450 wxTestModuleC::wxTestModuleC()
1452 AddDependency(CLASSINFO(wxTestModuleD
));
1455 IMPLEMENT_DYNAMIC_CLASS(wxTestModuleA
, wxModule
)
1456 wxTestModuleA::wxTestModuleA()
1458 AddDependency(CLASSINFO(wxTestModuleB
));
1459 AddDependency(CLASSINFO(wxTestModuleD
));
1462 IMPLEMENT_DYNAMIC_CLASS(wxTestModuleD
, wxModule
)
1463 wxTestModuleD::wxTestModuleD()
1467 IMPLEMENT_DYNAMIC_CLASS(wxTestModuleB
, wxModule
)
1468 wxTestModuleB::wxTestModuleB()
1470 AddDependency(CLASSINFO(wxTestModuleD
));
1471 AddDependency(CLASSINFO(wxTestModuleC
));
1474 #endif // TEST_MODULE
1476 // ----------------------------------------------------------------------------
1477 // misc information functions
1478 // ----------------------------------------------------------------------------
1480 #ifdef TEST_INFO_FUNCTIONS
1482 #include "wx/utils.h"
1484 #if TEST_INTERACTIVE
1485 static void TestDiskInfo()
1487 wxPuts(_T("*** Testing wxGetDiskSpace() ***"));
1491 wxChar pathname
[128];
1492 wxPrintf(_T("\nEnter a directory name: "));
1493 if ( !wxFgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1496 // kill the last '\n'
1497 pathname
[wxStrlen(pathname
) - 1] = 0;
1499 wxLongLong total
, free
;
1500 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1502 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1506 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1507 (total
/ 1024).ToString().c_str(),
1508 (free
/ 1024).ToString().c_str(),
1513 #endif // TEST_INTERACTIVE
1515 static void TestOsInfo()
1517 wxPuts(_T("*** Testing OS info functions ***\n"));
1520 wxGetOsVersion(&major
, &minor
);
1521 wxPrintf(_T("Running under: %s, version %d.%d\n"),
1522 wxGetOsDescription().c_str(), major
, minor
);
1524 wxPrintf(_T("%ld free bytes of memory left.\n"), wxGetFreeMemory().ToLong());
1526 wxPrintf(_T("Host name is %s (%s).\n"),
1527 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1529 wxPuts(wxEmptyString
);
1532 static void TestPlatformInfo()
1534 wxPuts(_T("*** Testing wxPlatformInfo functions ***\n"));
1536 // get this platform
1537 wxPlatformInfo plat
;
1539 wxPrintf(_T("Operating system family name is: %s\n"), plat
.GetOperatingSystemFamilyName().c_str());
1540 wxPrintf(_T("Operating system name is: %s\n"), plat
.GetOperatingSystemIdName().c_str());
1541 wxPrintf(_T("Port ID name is: %s\n"), plat
.GetPortIdName().c_str());
1542 wxPrintf(_T("Port ID short name is: %s\n"), plat
.GetPortIdShortName().c_str());
1543 wxPrintf(_T("Architecture is: %s\n"), plat
.GetArchName().c_str());
1544 wxPrintf(_T("Endianness is: %s\n"), plat
.GetEndiannessName().c_str());
1546 wxPuts(wxEmptyString
);
1549 static void TestUserInfo()
1551 wxPuts(_T("*** Testing user info functions ***\n"));
1553 wxPrintf(_T("User id is:\t%s\n"), wxGetUserId().c_str());
1554 wxPrintf(_T("User name is:\t%s\n"), wxGetUserName().c_str());
1555 wxPrintf(_T("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
1556 wxPrintf(_T("Email address:\t%s\n"), wxGetEmailAddress().c_str());
1558 wxPuts(wxEmptyString
);
1561 #endif // TEST_INFO_FUNCTIONS
1563 // ----------------------------------------------------------------------------
1565 // ----------------------------------------------------------------------------
1567 #ifdef TEST_PATHLIST
1570 #define CMD_IN_PATH _T("ls")
1572 #define CMD_IN_PATH _T("command.com")
1575 static void TestPathList()
1577 wxPuts(_T("*** Testing wxPathList ***\n"));
1579 wxPathList pathlist
;
1580 pathlist
.AddEnvList(_T("PATH"));
1581 wxString path
= pathlist
.FindValidPath(CMD_IN_PATH
);
1584 wxPrintf(_T("ERROR: command not found in the path.\n"));
1588 wxPrintf(_T("Command found in the path as '%s'.\n"), path
.c_str());
1592 #endif // TEST_PATHLIST
1594 // ----------------------------------------------------------------------------
1595 // regular expressions
1596 // ----------------------------------------------------------------------------
1598 #if defined TEST_REGEX && TEST_INTERACTIVE
1600 #include "wx/regex.h"
1602 static void TestRegExInteractive()
1604 wxPuts(_T("*** Testing RE interactively ***"));
1608 wxChar pattern
[128];
1609 wxPrintf(_T("\nEnter a pattern: "));
1610 if ( !wxFgets(pattern
, WXSIZEOF(pattern
), stdin
) )
1613 // kill the last '\n'
1614 pattern
[wxStrlen(pattern
) - 1] = 0;
1617 if ( !re
.Compile(pattern
) )
1625 wxPrintf(_T("Enter text to match: "));
1626 if ( !wxFgets(text
, WXSIZEOF(text
), stdin
) )
1629 // kill the last '\n'
1630 text
[wxStrlen(text
) - 1] = 0;
1632 if ( !re
.Matches(text
) )
1634 wxPrintf(_T("No match.\n"));
1638 wxPrintf(_T("Pattern matches at '%s'\n"), re
.GetMatch(text
).c_str());
1641 for ( size_t n
= 1; ; n
++ )
1643 if ( !re
.GetMatch(&start
, &len
, n
) )
1648 wxPrintf(_T("Subexpr %u matched '%s'\n"),
1649 n
, wxString(text
+ start
, len
).c_str());
1656 #endif // TEST_REGEX
1658 // ----------------------------------------------------------------------------
1660 // ----------------------------------------------------------------------------
1663 NB: this stuff was taken from the glibc test suite and modified to build
1664 in wxWidgets: if I read the copyright below properly, this shouldn't
1670 #ifdef wxTEST_PRINTF
1671 // use our functions from wxchar.cpp
1675 // NB: do _not_ use WX_ATTRIBUTE_PRINTF here, we have some invalid formats
1676 // in the tests below
1677 int wxPrintf( const wxChar
*format
, ... );
1678 int wxSprintf( wxChar
*str
, const wxChar
*format
, ... );
1681 #include "wx/longlong.h"
1685 static void rfg1 (void);
1686 static void rfg2 (void);
1690 fmtchk (const wxChar
*fmt
)
1692 (void) wxPrintf(_T("%s:\t`"), fmt
);
1693 (void) wxPrintf(fmt
, 0x12);
1694 (void) wxPrintf(_T("'\n"));
1698 fmtst1chk (const wxChar
*fmt
)
1700 (void) wxPrintf(_T("%s:\t`"), fmt
);
1701 (void) wxPrintf(fmt
, 4, 0x12);
1702 (void) wxPrintf(_T("'\n"));
1706 fmtst2chk (const wxChar
*fmt
)
1708 (void) wxPrintf(_T("%s:\t`"), fmt
);
1709 (void) wxPrintf(fmt
, 4, 4, 0x12);
1710 (void) wxPrintf(_T("'\n"));
1713 /* This page is covered by the following copyright: */
1715 /* (C) Copyright C E Chew
1717 * Feel free to copy, use and distribute this software provided:
1719 * 1. you do not pretend that you wrote it
1720 * 2. you leave this copyright notice intact.
1724 * Extracted from exercise.c for glibc-1.05 bug report by Bruce Evans.
1731 /* Formatted Output Test
1733 * This exercises the output formatting code.
1736 wxChar
*PointerNull
= NULL
;
1743 wxChar
*prefix
= buf
;
1746 wxPuts(_T("\nFormatted output test"));
1747 wxPrintf(_T("prefix 6d 6o 6x 6X 6u\n"));
1748 wxStrcpy(prefix
, _T("%"));
1749 for (i
= 0; i
< 2; i
++) {
1750 for (j
= 0; j
< 2; j
++) {
1751 for (k
= 0; k
< 2; k
++) {
1752 for (l
= 0; l
< 2; l
++) {
1753 wxStrcpy(prefix
, _T("%"));
1754 if (i
== 0) wxStrcat(prefix
, _T("-"));
1755 if (j
== 0) wxStrcat(prefix
, _T("+"));
1756 if (k
== 0) wxStrcat(prefix
, _T("#"));
1757 if (l
== 0) wxStrcat(prefix
, _T("0"));
1758 wxPrintf(_T("%5s |"), prefix
);
1759 wxStrcpy(tp
, prefix
);
1760 wxStrcat(tp
, _T("6d |"));
1762 wxStrcpy(tp
, prefix
);
1763 wxStrcat(tp
, _T("6o |"));
1765 wxStrcpy(tp
, prefix
);
1766 wxStrcat(tp
, _T("6x |"));
1768 wxStrcpy(tp
, prefix
);
1769 wxStrcat(tp
, _T("6X |"));
1771 wxStrcpy(tp
, prefix
);
1772 wxStrcat(tp
, _T("6u |"));
1779 wxPrintf(_T("%10s\n"), PointerNull
);
1780 wxPrintf(_T("%-10s\n"), PointerNull
);
1783 static void TestPrintf()
1785 static wxChar shortstr
[] = _T("Hi, Z.");
1786 static wxChar longstr
[] = _T("Good morning, Doctor Chandra. This is Hal. \
1787 I am ready for my first lesson today.");
1789 wxString test_format
;
1793 fmtchk(_T("%4.4x"));
1794 fmtchk(_T("%04.4x"));
1795 fmtchk(_T("%4.3x"));
1796 fmtchk(_T("%04.3x"));
1798 fmtst1chk(_T("%.*x"));
1799 fmtst1chk(_T("%0*x"));
1800 fmtst2chk(_T("%*.*x"));
1801 fmtst2chk(_T("%0*.*x"));
1803 wxString bad_format
= _T("bad format:\t\"%b\"\n");
1804 wxPrintf(bad_format
.c_str());
1805 wxPrintf(_T("nil pointer (padded):\t\"%10p\"\n"), (void *) NULL
);
1807 wxPrintf(_T("decimal negative:\t\"%d\"\n"), -2345);
1808 wxPrintf(_T("octal negative:\t\"%o\"\n"), -2345);
1809 wxPrintf(_T("hex negative:\t\"%x\"\n"), -2345);
1810 wxPrintf(_T("long decimal number:\t\"%ld\"\n"), -123456L);
1811 wxPrintf(_T("long octal negative:\t\"%lo\"\n"), -2345L);
1812 wxPrintf(_T("long unsigned decimal number:\t\"%lu\"\n"), -123456L);
1813 wxPrintf(_T("zero-padded LDN:\t\"%010ld\"\n"), -123456L);
1814 test_format
= _T("left-adjusted ZLDN:\t\"%-010ld\"\n");
1815 wxPrintf(test_format
.c_str(), -123456);
1816 wxPrintf(_T("space-padded LDN:\t\"%10ld\"\n"), -123456L);
1817 wxPrintf(_T("left-adjusted SLDN:\t\"%-10ld\"\n"), -123456L);
1819 test_format
= _T("zero-padded string:\t\"%010s\"\n");
1820 wxPrintf(test_format
.c_str(), shortstr
);
1821 test_format
= _T("left-adjusted Z string:\t\"%-010s\"\n");
1822 wxPrintf(test_format
.c_str(), shortstr
);
1823 wxPrintf(_T("space-padded string:\t\"%10s\"\n"), shortstr
);
1824 wxPrintf(_T("left-adjusted S string:\t\"%-10s\"\n"), shortstr
);
1825 wxPrintf(_T("null string:\t\"%s\"\n"), PointerNull
);
1826 wxPrintf(_T("limited string:\t\"%.22s\"\n"), longstr
);
1828 wxPrintf(_T("e-style >= 1:\t\"%e\"\n"), 12.34);
1829 wxPrintf(_T("e-style >= .1:\t\"%e\"\n"), 0.1234);
1830 wxPrintf(_T("e-style < .1:\t\"%e\"\n"), 0.001234);
1831 wxPrintf(_T("e-style big:\t\"%.60e\"\n"), 1e20
);
1832 wxPrintf(_T("e-style == .1:\t\"%e\"\n"), 0.1);
1833 wxPrintf(_T("f-style >= 1:\t\"%f\"\n"), 12.34);
1834 wxPrintf(_T("f-style >= .1:\t\"%f\"\n"), 0.1234);
1835 wxPrintf(_T("f-style < .1:\t\"%f\"\n"), 0.001234);
1836 wxPrintf(_T("g-style >= 1:\t\"%g\"\n"), 12.34);
1837 wxPrintf(_T("g-style >= .1:\t\"%g\"\n"), 0.1234);
1838 wxPrintf(_T("g-style < .1:\t\"%g\"\n"), 0.001234);
1839 wxPrintf(_T("g-style big:\t\"%.60g\"\n"), 1e20
);
1841 wxPrintf (_T(" %6.5f\n"), .099999999860301614);
1842 wxPrintf (_T(" %6.5f\n"), .1);
1843 wxPrintf (_T("x%5.4fx\n"), .5);
1845 wxPrintf (_T("%#03x\n"), 1);
1847 //wxPrintf (_T("something really insane: %.10000f\n"), 1.0);
1853 while (niter
-- != 0)
1854 wxPrintf (_T("%.17e\n"), d
/ 2);
1859 // Open Watcom cause compiler error here
1860 // Error! E173: col(24) floating-point constant too small to represent
1861 wxPrintf (_T("%15.5e\n"), 4.9406564584124654e-324);
1864 #define FORMAT _T("|%12.4f|%12.4e|%12.4g|\n")
1865 wxPrintf (FORMAT
, 0.0, 0.0, 0.0);
1866 wxPrintf (FORMAT
, 1.0, 1.0, 1.0);
1867 wxPrintf (FORMAT
, -1.0, -1.0, -1.0);
1868 wxPrintf (FORMAT
, 100.0, 100.0, 100.0);
1869 wxPrintf (FORMAT
, 1000.0, 1000.0, 1000.0);
1870 wxPrintf (FORMAT
, 10000.0, 10000.0, 10000.0);
1871 wxPrintf (FORMAT
, 12345.0, 12345.0, 12345.0);
1872 wxPrintf (FORMAT
, 100000.0, 100000.0, 100000.0);
1873 wxPrintf (FORMAT
, 123456.0, 123456.0, 123456.0);
1878 int rc
= wxSnprintf (buf
, WXSIZEOF(buf
), _T("%30s"), _T("foo"));
1880 wxPrintf(_T("snprintf (\"%%30s\", \"foo\") == %d, \"%.*s\"\n"),
1881 rc
, WXSIZEOF(buf
), buf
);
1884 wxPrintf ("snprintf (\"%%.999999u\", 10)\n",
1885 wxSnprintf(buf2
, WXSIZEOFbuf2
), "%.999999u", 10));
1891 wxPrintf (_T("%e should be 1.234568e+06\n"), 1234567.8);
1892 wxPrintf (_T("%f should be 1234567.800000\n"), 1234567.8);
1893 wxPrintf (_T("%g should be 1.23457e+06\n"), 1234567.8);
1894 wxPrintf (_T("%g should be 123.456\n"), 123.456);
1895 wxPrintf (_T("%g should be 1e+06\n"), 1000000.0);
1896 wxPrintf (_T("%g should be 10\n"), 10.0);
1897 wxPrintf (_T("%g should be 0.02\n"), 0.02);
1901 wxPrintf(_T("%.17f\n"),(1.0/x
/10.0+1.0)*x
-x
);
1907 wxSprintf(buf
,_T("%*s%*s%*s"),-1,_T("one"),-20,_T("two"),-30,_T("three"));
1909 result
|= wxStrcmp (buf
,
1910 _T("onetwo three "));
1912 wxPuts (result
!= 0 ? _T("Test failed!") : _T("Test ok."));
1919 wxSprintf(buf
, _T("%07") wxLongLongFmtSpec
_T("o"), wxLL(040000000000));
1921 // for some reason below line fails under Borland
1922 wxPrintf (_T("sprintf (buf, \"%%07Lo\", 040000000000ll) = %s"), buf
);
1925 if (wxStrcmp (buf
, _T("40000000000")) != 0)
1928 wxPuts (_T("\tFAILED"));
1930 wxUnusedVar(result
);
1931 wxPuts (wxEmptyString
);
1933 #endif // wxLongLong_t
1935 wxPrintf (_T("printf (\"%%hhu\", %u) = %hhu\n"), UCHAR_MAX
+ 2, UCHAR_MAX
+ 2);
1936 wxPrintf (_T("printf (\"%%hu\", %u) = %hu\n"), USHRT_MAX
+ 2, USHRT_MAX
+ 2);
1938 wxPuts (_T("--- Should be no further output. ---"));
1947 memset (bytes
, '\xff', sizeof bytes
);
1948 wxSprintf (buf
, _T("foo%hhn\n"), &bytes
[3]);
1949 if (bytes
[0] != '\xff' || bytes
[1] != '\xff' || bytes
[2] != '\xff'
1950 || bytes
[4] != '\xff' || bytes
[5] != '\xff' || bytes
[6] != '\xff')
1952 wxPuts (_T("%hhn overwrite more bytes"));
1957 wxPuts (_T("%hhn wrote incorrect value"));
1969 wxSprintf (buf
, _T("%5.s"), _T("xyz"));
1970 if (wxStrcmp (buf
, _T(" ")) != 0)
1971 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" "));
1972 wxSprintf (buf
, _T("%5.f"), 33.3);
1973 if (wxStrcmp (buf
, _T(" 33")) != 0)
1974 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 33"));
1975 wxSprintf (buf
, _T("%8.e"), 33.3e7
);
1976 if (wxStrcmp (buf
, _T(" 3e+08")) != 0)
1977 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3e+08"));
1978 wxSprintf (buf
, _T("%8.E"), 33.3e7
);
1979 if (wxStrcmp (buf
, _T(" 3E+08")) != 0)
1980 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3E+08"));
1981 wxSprintf (buf
, _T("%.g"), 33.3);
1982 if (wxStrcmp (buf
, _T("3e+01")) != 0)
1983 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3e+01"));
1984 wxSprintf (buf
, _T("%.G"), 33.3);
1985 if (wxStrcmp (buf
, _T("3E+01")) != 0)
1986 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3E+01"));
1994 wxString test_format
;
1997 wxSprintf (buf
, _T("%.*g"), prec
, 3.3);
1998 if (wxStrcmp (buf
, _T("3")) != 0)
1999 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
2001 wxSprintf (buf
, _T("%.*G"), prec
, 3.3);
2002 if (wxStrcmp (buf
, _T("3")) != 0)
2003 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
2005 wxSprintf (buf
, _T("%7.*G"), prec
, 3.33);
2006 if (wxStrcmp (buf
, _T(" 3")) != 0)
2007 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3"));
2009 test_format
= _T("%04.*o");
2010 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
2011 if (wxStrcmp (buf
, _T(" 041")) != 0)
2012 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 041"));
2014 test_format
= _T("%09.*u");
2015 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
2016 if (wxStrcmp (buf
, _T(" 0000033")) != 0)
2017 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 0000033"));
2019 test_format
= _T("%04.*x");
2020 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
2021 if (wxStrcmp (buf
, _T(" 021")) != 0)
2022 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
2024 test_format
= _T("%04.*X");
2025 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
2026 if (wxStrcmp (buf
, _T(" 021")) != 0)
2027 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
2030 #endif // TEST_PRINTF
2032 // ----------------------------------------------------------------------------
2033 // registry and related stuff
2034 // ----------------------------------------------------------------------------
2036 // this is for MSW only
2039 #undef TEST_REGISTRY
2044 #include "wx/confbase.h"
2045 #include "wx/msw/regconf.h"
2048 static void TestRegConfWrite()
2050 wxConfig
*config
= new wxConfig(_T("myapp"));
2051 config
->SetPath(_T("/group1"));
2052 config
->Write(_T("entry1"), _T("foo"));
2053 config
->SetPath(_T("/group2"));
2054 config
->Write(_T("entry1"), _T("bar"));
2058 static void TestRegConfRead()
2060 wxRegConfig
*config
= new wxRegConfig(_T("myapp"));
2064 config
->SetPath(_T("/"));
2065 wxPuts(_T("Enumerating / subgroups:"));
2066 bool bCont
= config
->GetFirstGroup(str
, dummy
);
2070 bCont
= config
->GetNextGroup(str
, dummy
);
2074 #endif // TEST_REGCONF
2076 #ifdef TEST_REGISTRY
2078 #include "wx/msw/registry.h"
2080 // I chose this one because I liked its name, but it probably only exists under
2082 static const wxChar
*TESTKEY
=
2083 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2085 static void TestRegistryRead()
2087 wxPuts(_T("*** testing registry reading ***"));
2089 wxRegKey
key(TESTKEY
);
2090 wxPrintf(_T("The test key name is '%s'.\n"), key
.GetName().c_str());
2093 wxPuts(_T("ERROR: test key can't be opened, aborting test."));
2098 size_t nSubKeys
, nValues
;
2099 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2101 wxPrintf(_T("It has %u subkeys and %u values.\n"), nSubKeys
, nValues
);
2104 wxPrintf(_T("Enumerating values:\n"));
2108 bool cont
= key
.GetFirstValue(value
, dummy
);
2111 wxPrintf(_T("Value '%s': type "), value
.c_str());
2112 switch ( key
.GetValueType(value
) )
2114 case wxRegKey::Type_None
: wxPrintf(_T("ERROR (none)")); break;
2115 case wxRegKey::Type_String
: wxPrintf(_T("SZ")); break;
2116 case wxRegKey::Type_Expand_String
: wxPrintf(_T("EXPAND_SZ")); break;
2117 case wxRegKey::Type_Binary
: wxPrintf(_T("BINARY")); break;
2118 case wxRegKey::Type_Dword
: wxPrintf(_T("DWORD")); break;
2119 case wxRegKey::Type_Multi_String
: wxPrintf(_T("MULTI_SZ")); break;
2120 default: wxPrintf(_T("other (unknown)")); break;
2123 wxPrintf(_T(", value = "));
2124 if ( key
.IsNumericValue(value
) )
2127 key
.QueryValue(value
, &val
);
2128 wxPrintf(_T("%ld"), val
);
2133 key
.QueryValue(value
, val
);
2134 wxPrintf(_T("'%s'"), val
.c_str());
2136 key
.QueryRawValue(value
, val
);
2137 wxPrintf(_T(" (raw value '%s')"), val
.c_str());
2142 cont
= key
.GetNextValue(value
, dummy
);
2146 static void TestRegistryAssociation()
2149 The second call to deleteself genertaes an error message, with a
2150 messagebox saying .flo is crucial to system operation, while the .ddf
2151 call also fails, but with no error message
2156 key
.SetName(_T("HKEY_CLASSES_ROOT\\.ddf") );
2158 key
= _T("ddxf_auto_file") ;
2159 key
.SetName(_T("HKEY_CLASSES_ROOT\\.flo") );
2161 key
= _T("ddxf_auto_file") ;
2162 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2164 key
= _T("program,0") ;
2165 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2167 key
= _T("program \"%1\"") ;
2169 key
.SetName(_T("HKEY_CLASSES_ROOT\\.ddf") );
2171 key
.SetName(_T("HKEY_CLASSES_ROOT\\.flo") );
2173 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2175 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2179 #endif // TEST_REGISTRY
2181 // ----------------------------------------------------------------------------
2183 // ----------------------------------------------------------------------------
2185 #ifdef TEST_SCOPEGUARD
2187 #include "wx/scopeguard.h"
2189 static void function0() { puts("function0()"); }
2190 static void function1(int n
) { printf("function1(%d)\n", n
); }
2191 static void function2(double x
, char c
) { printf("function2(%g, %c)\n", x
, c
); }
2195 void method0() { printf("method0()\n"); }
2196 void method1(int n
) { printf("method1(%d)\n", n
); }
2197 void method2(double x
, char c
) { printf("method2(%g, %c)\n", x
, c
); }
2200 static void TestScopeGuard()
2202 wxON_BLOCK_EXIT0(function0
);
2203 wxON_BLOCK_EXIT1(function1
, 17);
2204 wxON_BLOCK_EXIT2(function2
, 3.14, 'p');
2207 wxON_BLOCK_EXIT_OBJ0(obj
, Object::method0
);
2208 wxON_BLOCK_EXIT_OBJ1(obj
, Object::method1
, 7);
2209 wxON_BLOCK_EXIT_OBJ2(obj
, Object::method2
, 2.71, 'e');
2211 wxScopeGuard dismissed
= wxMakeGuard(function0
);
2212 dismissed
.Dismiss();
2217 // ----------------------------------------------------------------------------
2219 // ----------------------------------------------------------------------------
2223 #include "wx/socket.h"
2224 #include "wx/protocol/protocol.h"
2225 #include "wx/protocol/http.h"
2227 static void TestSocketServer()
2229 wxPuts(_T("*** Testing wxSocketServer ***\n"));
2231 static const int PORT
= 3000;
2236 wxSocketServer
*server
= new wxSocketServer(addr
);
2237 if ( !server
->Ok() )
2239 wxPuts(_T("ERROR: failed to bind"));
2247 wxPrintf(_T("Server: waiting for connection on port %d...\n"), PORT
);
2249 wxSocketBase
*socket
= server
->Accept();
2252 wxPuts(_T("ERROR: wxSocketServer::Accept() failed."));
2256 wxPuts(_T("Server: got a client."));
2258 server
->SetTimeout(60); // 1 min
2261 while ( !close
&& socket
->IsConnected() )
2264 wxChar ch
= _T('\0');
2267 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2269 // don't log error if the client just close the connection
2270 if ( socket
->IsConnected() )
2272 wxPuts(_T("ERROR: in wxSocket::Read."));
2292 wxPrintf(_T("Server: got '%s'.\n"), s
.c_str());
2293 if ( s
== _T("close") )
2295 wxPuts(_T("Closing connection"));
2299 else if ( s
== _T("quit") )
2304 wxPuts(_T("Shutting down the server"));
2306 else // not a special command
2308 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2309 socket
->Write("\r\n", 2);
2310 wxPrintf(_T("Server: wrote '%s'.\n"), s
.c_str());
2316 wxPuts(_T("Server: lost a client unexpectedly."));
2322 // same as "delete server" but is consistent with GUI programs
2326 static void TestSocketClient()
2328 wxPuts(_T("*** Testing wxSocketClient ***\n"));
2330 static const wxChar
*hostname
= _T("www.wxwidgets.org");
2333 addr
.Hostname(hostname
);
2336 wxPrintf(_T("--- Attempting to connect to %s:80...\n"), hostname
);
2338 wxSocketClient client
;
2339 if ( !client
.Connect(addr
) )
2341 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2345 wxPrintf(_T("--- Connected to %s:%u...\n"),
2346 addr
.Hostname().c_str(), addr
.Service());
2350 // could use simply "GET" here I suppose
2352 wxString::Format(_T("GET http://%s/\r\n"), hostname
);
2353 client
.Write(cmdGet
, cmdGet
.length());
2354 wxPrintf(_T("--- Sent command '%s' to the server\n"),
2355 MakePrintable(cmdGet
).c_str());
2356 client
.Read(buf
, WXSIZEOF(buf
));
2357 wxPrintf(_T("--- Server replied:\n%s"), buf
);
2361 #endif // TEST_SOCKETS
2363 // ----------------------------------------------------------------------------
2365 // ----------------------------------------------------------------------------
2369 #include "wx/protocol/ftp.h"
2370 #include "wx/protocol/log.h"
2372 #define FTP_ANONYMOUS
2376 #ifdef FTP_ANONYMOUS
2377 static const wxChar
*directory
= _T("/pub");
2378 static const wxChar
*filename
= _T("welcome.msg");
2380 static const wxChar
*directory
= _T("/etc");
2381 static const wxChar
*filename
= _T("issue");
2384 static bool TestFtpConnect()
2386 wxPuts(_T("*** Testing FTP connect ***"));
2388 #ifdef FTP_ANONYMOUS
2389 static const wxChar
*hostname
= _T("ftp.wxwidgets.org");
2391 wxPrintf(_T("--- Attempting to connect to %s:21 anonymously...\n"), hostname
);
2392 #else // !FTP_ANONYMOUS
2393 static const wxChar
*hostname
= "localhost";
2396 wxFgets(user
, WXSIZEOF(user
), stdin
);
2397 user
[wxStrlen(user
) - 1] = '\0'; // chop off '\n'
2400 wxChar password
[256];
2401 wxPrintf(_T("Password for %s: "), password
);
2402 wxFgets(password
, WXSIZEOF(password
), stdin
);
2403 password
[wxStrlen(password
) - 1] = '\0'; // chop off '\n'
2404 ftp
->SetPassword(password
);
2406 wxPrintf(_T("--- Attempting to connect to %s:21 as %s...\n"), hostname
, user
);
2407 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2409 if ( !ftp
->Connect(hostname
) )
2411 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2417 wxPrintf(_T("--- Connected to %s, current directory is '%s'\n"),
2418 hostname
, ftp
->Pwd().c_str());
2425 static void TestFtpList()
2427 wxPuts(_T("*** Testing wxFTP file listing ***\n"));
2430 if ( !ftp
->ChDir(directory
) )
2432 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
2435 wxPrintf(_T("Current directory is '%s'\n"), ftp
->Pwd().c_str());
2437 // test NLIST and LIST
2438 wxArrayString files
;
2439 if ( !ftp
->GetFilesList(files
) )
2441 wxPuts(_T("ERROR: failed to get NLIST of files"));
2445 wxPrintf(_T("Brief list of files under '%s':\n"), ftp
->Pwd().c_str());
2446 size_t count
= files
.GetCount();
2447 for ( size_t n
= 0; n
< count
; n
++ )
2449 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2451 wxPuts(_T("End of the file list"));
2454 if ( !ftp
->GetDirList(files
) )
2456 wxPuts(_T("ERROR: failed to get LIST of files"));
2460 wxPrintf(_T("Detailed list of files under '%s':\n"), ftp
->Pwd().c_str());
2461 size_t count
= files
.GetCount();
2462 for ( size_t n
= 0; n
< count
; n
++ )
2464 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2466 wxPuts(_T("End of the file list"));
2469 if ( !ftp
->ChDir(_T("..")) )
2471 wxPuts(_T("ERROR: failed to cd to .."));
2474 wxPrintf(_T("Current directory is '%s'\n"), ftp
->Pwd().c_str());
2477 static void TestFtpDownload()
2479 wxPuts(_T("*** Testing wxFTP download ***\n"));
2482 wxInputStream
*in
= ftp
->GetInputStream(filename
);
2485 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
2489 size_t size
= in
->GetSize();
2490 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
2493 wxChar
*data
= new wxChar
[size
];
2494 if ( !in
->Read(data
, size
) )
2496 wxPuts(_T("ERROR: read error"));
2500 wxPrintf(_T("\nContents of %s:\n%s\n"), filename
, data
);
2508 static void TestFtpFileSize()
2510 wxPuts(_T("*** Testing FTP SIZE command ***"));
2512 if ( !ftp
->ChDir(directory
) )
2514 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
2517 wxPrintf(_T("Current directory is '%s'\n"), ftp
->Pwd().c_str());
2519 if ( ftp
->FileExists(filename
) )
2521 int size
= ftp
->GetFileSize(filename
);
2523 wxPrintf(_T("ERROR: couldn't get size of '%s'\n"), filename
);
2525 wxPrintf(_T("Size of '%s' is %d bytes.\n"), filename
, size
);
2529 wxPrintf(_T("ERROR: '%s' doesn't exist\n"), filename
);
2533 static void TestFtpMisc()
2535 wxPuts(_T("*** Testing miscellaneous wxFTP functions ***"));
2537 if ( ftp
->SendCommand(_T("STAT")) != '2' )
2539 wxPuts(_T("ERROR: STAT failed"));
2543 wxPrintf(_T("STAT returned:\n\n%s\n"), ftp
->GetLastResult().c_str());
2546 if ( ftp
->SendCommand(_T("HELP SITE")) != '2' )
2548 wxPuts(_T("ERROR: HELP SITE failed"));
2552 wxPrintf(_T("The list of site-specific commands:\n\n%s\n"),
2553 ftp
->GetLastResult().c_str());
2557 #if TEST_INTERACTIVE
2559 static void TestFtpInteractive()
2561 wxPuts(_T("\n*** Interactive wxFTP test ***"));
2567 wxPrintf(_T("Enter FTP command: "));
2568 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
2571 // kill the last '\n'
2572 buf
[wxStrlen(buf
) - 1] = 0;
2574 // special handling of LIST and NLST as they require data connection
2575 wxString
start(buf
, 4);
2577 if ( start
== _T("LIST") || start
== _T("NLST") )
2580 if ( wxStrlen(buf
) > 4 )
2583 wxArrayString files
;
2584 if ( !ftp
->GetList(files
, wildcard
, start
== _T("LIST")) )
2586 wxPrintf(_T("ERROR: failed to get %s of files\n"), start
.c_str());
2590 wxPrintf(_T("--- %s of '%s' under '%s':\n"),
2591 start
.c_str(), wildcard
.c_str(), ftp
->Pwd().c_str());
2592 size_t count
= files
.GetCount();
2593 for ( size_t n
= 0; n
< count
; n
++ )
2595 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2597 wxPuts(_T("--- End of the file list"));
2602 wxChar ch
= ftp
->SendCommand(buf
);
2603 wxPrintf(_T("Command %s"), ch
? _T("succeeded") : _T("failed"));
2606 wxPrintf(_T(" (return code %c)"), ch
);
2609 wxPrintf(_T(", server reply:\n%s\n\n"), ftp
->GetLastResult().c_str());
2613 wxPuts(_T("\n*** done ***"));
2616 #endif // TEST_INTERACTIVE
2618 static void TestFtpUpload()
2620 wxPuts(_T("*** Testing wxFTP uploading ***\n"));
2623 static const wxChar
*file1
= _T("test1");
2624 static const wxChar
*file2
= _T("test2");
2625 wxOutputStream
*out
= ftp
->GetOutputStream(file1
);
2628 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
2629 out
->Write("First hello", 11);
2633 // send a command to check the remote file
2634 if ( ftp
->SendCommand(wxString(_T("STAT ")) + file1
) != '2' )
2636 wxPrintf(_T("ERROR: STAT %s failed\n"), file1
);
2640 wxPrintf(_T("STAT %s returned:\n\n%s\n"),
2641 file1
, ftp
->GetLastResult().c_str());
2644 out
= ftp
->GetOutputStream(file2
);
2647 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
2648 out
->Write("Second hello", 12);
2655 // ----------------------------------------------------------------------------
2657 // ----------------------------------------------------------------------------
2659 #ifdef TEST_STACKWALKER
2661 #if wxUSE_STACKWALKER
2663 #include "wx/stackwalk.h"
2665 class StackDump
: public wxStackWalker
2668 StackDump(const char *argv0
)
2669 : wxStackWalker(argv0
)
2673 virtual void Walk(size_t skip
= 1, size_t maxdepth
= wxSTACKWALKER_MAX_DEPTH
)
2675 wxPuts(_T("Stack dump:"));
2677 wxStackWalker::Walk(skip
, maxdepth
);
2681 virtual void OnStackFrame(const wxStackFrame
& frame
)
2683 printf("[%2d] ", (int) frame
.GetLevel());
2685 wxString name
= frame
.GetName();
2686 if ( !name
.empty() )
2688 printf("%-20.40s", (const char*)name
.mb_str());
2692 printf("0x%08lx", (unsigned long)frame
.GetAddress());
2695 if ( frame
.HasSourceLocation() )
2698 (const char*)frame
.GetFileName().mb_str(),
2699 (int)frame
.GetLine());
2705 for ( size_t n
= 0; frame
.GetParam(n
, &type
, &name
, &val
); n
++ )
2707 printf("\t%s %s = %s\n", (const char*)type
.mb_str(),
2708 (const char*)name
.mb_str(),
2709 (const char*)val
.mb_str());
2714 static void TestStackWalk(const char *argv0
)
2716 wxPuts(_T("*** Testing wxStackWalker ***\n"));
2718 StackDump
dump(argv0
);
2722 #endif // wxUSE_STACKWALKER
2724 #endif // TEST_STACKWALKER
2726 // ----------------------------------------------------------------------------
2728 // ----------------------------------------------------------------------------
2730 #ifdef TEST_STDPATHS
2732 #include "wx/stdpaths.h"
2733 #include "wx/wxchar.h" // wxPrintf
2735 static void TestStandardPaths()
2737 wxPuts(_T("*** Testing wxStandardPaths ***\n"));
2739 wxTheApp
->SetAppName(_T("console"));
2741 wxStandardPathsBase
& stdp
= wxStandardPaths::Get();
2742 wxPrintf(_T("Config dir (sys):\t%s\n"), stdp
.GetConfigDir().c_str());
2743 wxPrintf(_T("Config dir (user):\t%s\n"), stdp
.GetUserConfigDir().c_str());
2744 wxPrintf(_T("Data dir (sys):\t\t%s\n"), stdp
.GetDataDir().c_str());
2745 wxPrintf(_T("Data dir (sys local):\t%s\n"), stdp
.GetLocalDataDir().c_str());
2746 wxPrintf(_T("Data dir (user):\t%s\n"), stdp
.GetUserDataDir().c_str());
2747 wxPrintf(_T("Data dir (user local):\t%s\n"), stdp
.GetUserLocalDataDir().c_str());
2748 wxPrintf(_T("Documents dir:\t\t%s\n"), stdp
.GetDocumentsDir().c_str());
2749 wxPrintf(_T("Executable path:\t%s\n"), stdp
.GetExecutablePath().c_str());
2750 wxPrintf(_T("Plugins dir:\t\t%s\n"), stdp
.GetPluginsDir().c_str());
2751 wxPrintf(_T("Resources dir:\t\t%s\n"), stdp
.GetResourcesDir().c_str());
2752 wxPrintf(_T("Localized res. dir:\t%s\n"),
2753 stdp
.GetLocalizedResourcesDir(_T("fr")).c_str());
2754 wxPrintf(_T("Message catalogs dir:\t%s\n"),
2755 stdp
.GetLocalizedResourcesDir
2758 wxStandardPaths::ResourceCat_Messages
2762 #endif // TEST_STDPATHS
2764 // ----------------------------------------------------------------------------
2766 // ----------------------------------------------------------------------------
2770 #include "wx/wfstream.h"
2771 #include "wx/mstream.h"
2773 static void TestFileStream()
2775 wxPuts(_T("*** Testing wxFileInputStream ***"));
2777 static const wxString filename
= _T("testdata.fs");
2779 wxFileOutputStream
fsOut(filename
);
2780 fsOut
.Write("foo", 3);
2784 wxFileInputStream
fsIn(filename
);
2785 wxPrintf(_T("File stream size: %u\n"), fsIn
.GetSize());
2787 while ( (c
=fsIn
.GetC()) != wxEOF
)
2793 if ( !wxRemoveFile(filename
) )
2795 wxPrintf(_T("ERROR: failed to remove the file '%s'.\n"), filename
.c_str());
2798 wxPuts(_T("\n*** wxFileInputStream test done ***"));
2801 static void TestMemoryStream()
2803 wxPuts(_T("*** Testing wxMemoryOutputStream ***"));
2805 wxMemoryOutputStream memOutStream
;
2806 wxPrintf(_T("Initially out stream offset: %lu\n"),
2807 (unsigned long)memOutStream
.TellO());
2809 for ( const wxChar
*p
= _T("Hello, stream!"); *p
; p
++ )
2811 memOutStream
.PutC(*p
);
2814 wxPrintf(_T("Final out stream offset: %lu\n"),
2815 (unsigned long)memOutStream
.TellO());
2817 wxPuts(_T("*** Testing wxMemoryInputStream ***"));
2820 size_t len
= memOutStream
.CopyTo(buf
, WXSIZEOF(buf
));
2822 wxMemoryInputStream
memInpStream(buf
, len
);
2823 wxPrintf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2825 while ( (c
=memInpStream
.GetC()) != wxEOF
)
2830 wxPuts(_T("\n*** wxMemoryInputStream test done ***"));
2833 #endif // TEST_STREAMS
2835 // ----------------------------------------------------------------------------
2837 // ----------------------------------------------------------------------------
2841 #include "wx/stopwatch.h"
2842 #include "wx/utils.h"
2844 static void TestStopWatch()
2846 wxPuts(_T("*** Testing wxStopWatch ***\n"));
2850 wxPrintf(_T("Initially paused, after 2 seconds time is..."));
2853 wxPrintf(_T("\t%ldms\n"), sw
.Time());
2855 wxPrintf(_T("Resuming stopwatch and sleeping 3 seconds..."));
2859 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2862 wxPrintf(_T("Pausing agan and sleeping 2 more seconds..."));
2865 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2868 wxPrintf(_T("Finally resuming and sleeping 2 more seconds..."));
2871 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2874 wxPuts(_T("\nChecking for 'backwards clock' bug..."));
2875 for ( size_t n
= 0; n
< 70; n
++ )
2879 for ( size_t m
= 0; m
< 100000; m
++ )
2881 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2883 wxPuts(_T("\ntime is negative - ERROR!"));
2891 wxPuts(_T(", ok."));
2894 #include "wx/timer.h"
2895 #include "wx/evtloop.h"
2899 wxPuts(_T("*** Testing wxTimer ***\n"));
2901 class MyTimer
: public wxTimer
2904 MyTimer() : wxTimer() { m_num
= 0; }
2906 virtual void Notify()
2908 wxPrintf(_T("%d"), m_num
++);
2913 wxPrintf(_T("... exiting the event loop"));
2916 wxEventLoop::GetActive()->Exit(0);
2917 wxPuts(_T(", ok."));
2930 timer1
.Start(100, true /* one shot */);
2932 timer1
.Start(100, true /* one shot */);
2940 #endif // TEST_TIMER
2942 // ----------------------------------------------------------------------------
2944 // ----------------------------------------------------------------------------
2948 #include "wx/vcard.h"
2950 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2953 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2956 wxPrintf(_T("%s%s"),
2957 wxString(_T('\t'), level
).c_str(),
2958 vcObj
->GetName().c_str());
2961 switch ( vcObj
->GetType() )
2963 case wxVCardObject::String
:
2964 case wxVCardObject::UString
:
2967 vcObj
->GetValue(&val
);
2968 value
<< _T('"') << val
<< _T('"');
2972 case wxVCardObject::Int
:
2975 vcObj
->GetValue(&i
);
2976 value
.Printf(_T("%u"), i
);
2980 case wxVCardObject::Long
:
2983 vcObj
->GetValue(&l
);
2984 value
.Printf(_T("%lu"), l
);
2988 case wxVCardObject::None
:
2991 case wxVCardObject::Object
:
2992 value
= _T("<node>");
2996 value
= _T("<unknown value type>");
3000 wxPrintf(_T(" = %s"), value
.c_str());
3003 DumpVObject(level
+ 1, *vcObj
);
3006 vcObj
= vcard
.GetNextProp(&cookie
);
3010 static void DumpVCardAddresses(const wxVCard
& vcard
)
3012 wxPuts(_T("\nShowing all addresses from vCard:\n"));
3016 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3020 int flags
= addr
->GetFlags();
3021 if ( flags
& wxVCardAddress::Domestic
)
3023 flagsStr
<< _T("domestic ");
3025 if ( flags
& wxVCardAddress::Intl
)
3027 flagsStr
<< _T("international ");
3029 if ( flags
& wxVCardAddress::Postal
)
3031 flagsStr
<< _T("postal ");
3033 if ( flags
& wxVCardAddress::Parcel
)
3035 flagsStr
<< _T("parcel ");
3037 if ( flags
& wxVCardAddress::Home
)
3039 flagsStr
<< _T("home ");
3041 if ( flags
& wxVCardAddress::Work
)
3043 flagsStr
<< _T("work ");
3046 wxPrintf(_T("Address %u:\n")
3048 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3051 addr
->GetPostOffice().c_str(),
3052 addr
->GetExtAddress().c_str(),
3053 addr
->GetStreet().c_str(),
3054 addr
->GetLocality().c_str(),
3055 addr
->GetRegion().c_str(),
3056 addr
->GetPostalCode().c_str(),
3057 addr
->GetCountry().c_str()
3061 addr
= vcard
.GetNextAddress(&cookie
);
3065 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3067 wxPuts(_T("\nShowing all phone numbers from vCard:\n"));
3071 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3075 int flags
= phone
->GetFlags();
3076 if ( flags
& wxVCardPhoneNumber::Voice
)
3078 flagsStr
<< _T("voice ");
3080 if ( flags
& wxVCardPhoneNumber::Fax
)
3082 flagsStr
<< _T("fax ");
3084 if ( flags
& wxVCardPhoneNumber::Cellular
)
3086 flagsStr
<< _T("cellular ");
3088 if ( flags
& wxVCardPhoneNumber::Modem
)
3090 flagsStr
<< _T("modem ");
3092 if ( flags
& wxVCardPhoneNumber::Home
)
3094 flagsStr
<< _T("home ");
3096 if ( flags
& wxVCardPhoneNumber::Work
)
3098 flagsStr
<< _T("work ");
3101 wxPrintf(_T("Phone number %u:\n")
3106 phone
->GetNumber().c_str()
3110 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3114 static void TestVCardRead()
3116 wxPuts(_T("*** Testing wxVCard reading ***\n"));
3118 wxVCard
vcard(_T("vcard.vcf"));
3119 if ( !vcard
.IsOk() )
3121 wxPuts(_T("ERROR: couldn't load vCard."));
3125 // read individual vCard properties
3126 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3130 vcObj
->GetValue(&value
);
3135 value
= _T("<none>");
3138 wxPrintf(_T("Full name retrieved directly: %s\n"), value
.c_str());
3141 if ( !vcard
.GetFullName(&value
) )
3143 value
= _T("<none>");
3146 wxPrintf(_T("Full name from wxVCard API: %s\n"), value
.c_str());
3148 // now show how to deal with multiply occurring properties
3149 DumpVCardAddresses(vcard
);
3150 DumpVCardPhoneNumbers(vcard
);
3152 // and finally show all
3153 wxPuts(_T("\nNow dumping the entire vCard:\n")
3154 "-----------------------------\n");
3156 DumpVObject(0, vcard
);
3160 static void TestVCardWrite()
3162 wxPuts(_T("*** Testing wxVCard writing ***\n"));
3165 if ( !vcard
.IsOk() )
3167 wxPuts(_T("ERROR: couldn't create vCard."));
3172 vcard
.SetName("Zeitlin", "Vadim");
3173 vcard
.SetFullName("Vadim Zeitlin");
3174 vcard
.SetOrganization("wxWidgets", "R&D");
3176 // just dump the vCard back
3177 wxPuts(_T("Entire vCard follows:\n"));
3178 wxPuts(vcard
.Write());
3182 #endif // TEST_VCARD
3184 // ----------------------------------------------------------------------------
3186 // ----------------------------------------------------------------------------
3188 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
3194 #include "wx/volume.h"
3196 static const wxChar
*volumeKinds
[] =
3202 _T("network volume"),
3206 static void TestFSVolume()
3208 wxPuts(_T("*** Testing wxFSVolume class ***"));
3210 wxArrayString volumes
= wxFSVolume::GetVolumes();
3211 size_t count
= volumes
.GetCount();
3215 wxPuts(_T("ERROR: no mounted volumes?"));
3219 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3221 for ( size_t n
= 0; n
< count
; n
++ )
3223 wxFSVolume
vol(volumes
[n
]);
3226 wxPuts(_T("ERROR: couldn't create volume"));
3230 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3232 vol
.GetDisplayName().c_str(),
3233 vol
.GetName().c_str(),
3234 volumeKinds
[vol
.GetKind()],
3235 vol
.IsWritable() ? _T("rw") : _T("ro"),
3236 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3241 #endif // TEST_VOLUME
3243 // ----------------------------------------------------------------------------
3244 // wide char and Unicode support
3245 // ----------------------------------------------------------------------------
3249 #include "wx/strconv.h"
3250 #include "wx/fontenc.h"
3251 #include "wx/encconv.h"
3252 #include "wx/buffer.h"
3254 static const unsigned char utf8koi8r
[] =
3256 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3257 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3258 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3259 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3260 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3261 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3262 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3265 static const unsigned char utf8iso8859_1
[] =
3267 0x53, 0x79, 0x73, 0x74, 0xc3, 0xa8, 0x6d, 0x65, 0x73, 0x20, 0x49, 0x6e,
3268 0x74, 0xc3, 0xa9, 0x67, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x20, 0x65,
3269 0x6e, 0x20, 0x4d, 0xc3, 0xa9, 0x63, 0x61, 0x6e, 0x69, 0x71, 0x75, 0x65,
3270 0x20, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x69, 0x71, 0x75, 0x65, 0x20, 0x65,
3271 0x74, 0x20, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x71, 0x75, 0x65, 0
3274 static const unsigned char utf8Invalid
[] =
3276 0x3c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x3e, 0x32, 0x30, 0x30,
3277 0x32, 0xe5, 0xb9, 0xb4, 0x30, 0x39, 0xe6, 0x9c, 0x88, 0x32, 0x35, 0xe6,
3278 0x97, 0xa5, 0x20, 0x30, 0x37, 0xe6, 0x99, 0x82, 0x33, 0x39, 0xe5, 0x88,
3279 0x86, 0x35, 0x37, 0xe7, 0xa7, 0x92, 0x3c, 0x2f, 0x64, 0x69, 0x73, 0x70,
3283 static const struct Utf8Data
3285 const unsigned char *text
;
3287 const wxChar
*charset
;
3288 wxFontEncoding encoding
;
3291 { utf8Invalid
, WXSIZEOF(utf8Invalid
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3292 { utf8koi8r
, WXSIZEOF(utf8koi8r
), _T("koi8-r"), wxFONTENCODING_KOI8
},
3293 { utf8iso8859_1
, WXSIZEOF(utf8iso8859_1
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3296 static void TestUtf8()
3298 wxPuts(_T("*** Testing UTF8 support ***\n"));
3303 for ( size_t n
= 0; n
< WXSIZEOF(utf8data
); n
++ )
3305 const Utf8Data
& u8d
= utf8data
[n
];
3306 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)u8d
.text
,
3307 WXSIZEOF(wbuf
)) == (size_t)-1 )
3309 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3313 wxCSConv
conv(u8d
.charset
);
3314 if ( conv
.WC2MB(buf
, wbuf
, WXSIZEOF(buf
)) == (size_t)-1 )
3316 wxPrintf(_T("ERROR: conversion to %s failed.\n"), u8d
.charset
);
3320 wxPrintf(_T("String in %s: %s\n"), u8d
.charset
, buf
);
3324 wxString
s(wxConvUTF8
.cMB2WC((const char *)u8d
.text
));
3326 s
= _T("<< conversion failed >>");
3327 wxPrintf(_T("String in current cset: %s\n"), s
.c_str());
3331 wxPuts(wxEmptyString
);
3334 static void TestEncodingConverter()
3336 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3338 // using wxEncodingConverter should give the same result as above
3341 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)utf8koi8r
,
3342 WXSIZEOF(utf8koi8r
)) == (size_t)-1 )
3344 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3348 wxEncodingConverter ec
;
3349 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3350 ec
.Convert(wbuf
, buf
);
3351 wxPrintf(_T("The same KOI8-R string using wxEC: %s\n"), buf
);
3354 wxPuts(wxEmptyString
);
3357 #endif // TEST_WCHAR
3359 // ----------------------------------------------------------------------------
3361 // ----------------------------------------------------------------------------
3365 #include "wx/filesys.h"
3366 #include "wx/fs_zip.h"
3367 #include "wx/zipstrm.h"
3369 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3371 static void TestZipStreamRead()
3373 wxPuts(_T("*** Testing ZIP reading ***\n"));
3375 static const wxString filename
= _T("foo");
3376 wxFFileInputStream
in(TESTFILE_ZIP
);
3377 wxZipInputStream
istr(in
);
3378 wxZipEntry
entry(filename
);
3379 istr
.OpenEntry(entry
);
3381 wxPrintf(_T("Archive size: %u\n"), istr
.GetSize());
3383 wxPrintf(_T("Dumping the file '%s':\n"), filename
.c_str());
3385 while ( (c
=istr
.GetC()) != wxEOF
)
3391 wxPuts(_T("\n----- done ------"));
3394 static void DumpZipDirectory(wxFileSystem
& fs
,
3395 const wxString
& dir
,
3396 const wxString
& indent
)
3398 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3399 TESTFILE_ZIP
, dir
.c_str());
3400 wxString wildcard
= prefix
+ _T("/*");
3402 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3403 while ( !dirname
.empty() )
3405 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3407 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3412 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3414 DumpZipDirectory(fs
, dirname
,
3415 indent
+ wxString(_T(' '), 4));
3417 dirname
= fs
.FindNext();
3420 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3421 while ( !filename
.empty() )
3423 if ( !filename
.StartsWith(prefix
, &filename
) )
3425 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3430 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3432 filename
= fs
.FindNext();
3436 static void TestZipFileSystem()
3438 wxPuts(_T("*** Testing ZIP file system ***\n"));
3440 wxFileSystem::AddHandler(new wxZipFSHandler
);
3442 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3444 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3449 // ----------------------------------------------------------------------------
3451 // ----------------------------------------------------------------------------
3453 #ifdef TEST_DATETIME
3455 #include "wx/math.h"
3456 #include "wx/datetime.h"
3458 // this test miscellaneous static wxDateTime functions
3462 static void TestTimeStatic()
3464 wxPuts(_T("\n*** wxDateTime static methods test ***"));
3466 // some info about the current date
3467 int year
= wxDateTime::GetCurrentYear();
3468 wxPrintf(_T("Current year %d is %sa leap one and has %d days.\n"),
3470 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3471 wxDateTime::GetNumberOfDays(year
));
3473 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3474 wxPrintf(_T("Current month is '%s' ('%s') and it has %d days\n"),
3475 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3476 wxDateTime::GetMonthName(month
).c_str(),
3477 wxDateTime::GetNumberOfDays(month
));
3480 // test time zones stuff
3481 static void TestTimeZones()
3483 wxPuts(_T("\n*** wxDateTime timezone test ***"));
3485 wxDateTime now
= wxDateTime::Now();
3487 wxPrintf(_T("Current GMT time:\t%s\n"), now
.Format(_T("%c"), wxDateTime::GMT0
).c_str());
3488 wxPrintf(_T("Unix epoch (GMT):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::GMT0
).c_str());
3489 wxPrintf(_T("Unix epoch (EST):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::EST
).c_str());
3490 wxPrintf(_T("Current time in Paris:\t%s\n"), now
.Format(_T("%c"), wxDateTime::CET
).c_str());
3491 wxPrintf(_T(" Moscow:\t%s\n"), now
.Format(_T("%c"), wxDateTime::MSK
).c_str());
3492 wxPrintf(_T(" New York:\t%s\n"), now
.Format(_T("%c"), wxDateTime::EST
).c_str());
3494 wxPrintf(_T("%s\n"), wxDateTime::Now().Format(_T("Our timezone is %Z")).c_str());
3496 wxDateTime::Tm tm
= now
.GetTm();
3497 if ( wxDateTime(tm
) != now
)
3499 wxPrintf(_T("ERROR: got %s instead of %s\n"),
3500 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3504 // test some minimal support for the dates outside the standard range
3505 static void TestTimeRange()
3507 wxPuts(_T("\n*** wxDateTime out-of-standard-range dates test ***"));
3509 static const wxChar
*fmt
= _T("%d-%b-%Y %H:%M:%S");
3511 wxPrintf(_T("Unix epoch:\t%s\n"),
3512 wxDateTime(2440587.5).Format(fmt
).c_str());
3513 wxPrintf(_T("Feb 29, 0: \t%s\n"),
3514 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3515 wxPrintf(_T("JDN 0: \t%s\n"),
3516 wxDateTime(0.0).Format(fmt
).c_str());
3517 wxPrintf(_T("Jan 1, 1AD:\t%s\n"),
3518 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3519 wxPrintf(_T("May 29, 2099:\t%s\n"),
3520 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3523 // test DST calculations
3524 static void TestTimeDST()
3526 wxPuts(_T("\n*** wxDateTime DST test ***"));
3528 wxPrintf(_T("DST is%s in effect now.\n\n"),
3529 wxDateTime::Now().IsDST() ? wxEmptyString
: _T(" not"));
3531 for ( int year
= 1990; year
< 2005; year
++ )
3533 wxPrintf(_T("DST period in Europe for year %d: from %s to %s\n"),
3535 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3536 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3542 #if TEST_INTERACTIVE
3544 static void TestDateTimeInteractive()
3546 wxPuts(_T("\n*** interactive wxDateTime tests ***"));
3552 wxPrintf(_T("Enter a date: "));
3553 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
3556 // kill the last '\n'
3557 buf
[wxStrlen(buf
) - 1] = 0;
3560 const wxChar
*p
= dt
.ParseDate(buf
);
3563 wxPrintf(_T("ERROR: failed to parse the date '%s'.\n"), buf
);
3569 wxPrintf(_T("WARNING: parsed only first %u characters.\n"), p
- buf
);
3572 wxPrintf(_T("%s: day %u, week of month %u/%u, week of year %u\n"),
3573 dt
.Format(_T("%b %d, %Y")).c_str(),
3575 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3576 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3577 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3580 wxPuts(_T("\n*** done ***"));
3583 #endif // TEST_INTERACTIVE
3587 static void TestTimeMS()
3589 wxPuts(_T("*** testing millisecond-resolution support in wxDateTime ***"));
3591 wxDateTime dt1
= wxDateTime::Now(),
3592 dt2
= wxDateTime::UNow();
3594 wxPrintf(_T("Now = %s\n"), dt1
.Format(_T("%H:%M:%S:%l")).c_str());
3595 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
3596 wxPrintf(_T("Dummy loop: "));
3597 for ( int i
= 0; i
< 6000; i
++ )
3599 //for ( int j = 0; j < 10; j++ )
3602 s
.Printf(_T("%g"), sqrt((float)i
));
3608 wxPuts(_T(", done"));
3611 dt2
= wxDateTime::UNow();
3612 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
3614 wxPrintf(_T("Loop executed in %s ms\n"), (dt2
- dt1
).Format(_T("%l")).c_str());
3616 wxPuts(_T("\n*** done ***"));
3619 static void TestTimeHolidays()
3621 wxPuts(_T("\n*** testing wxDateTimeHolidayAuthority ***\n"));
3623 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3624 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3625 dtEnd
= dtStart
.GetLastMonthDay();
3627 wxDateTimeArray hol
;
3628 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3630 const wxChar
*format
= _T("%d-%b-%Y (%a)");
3632 wxPrintf(_T("All holidays between %s and %s:\n"),
3633 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3635 size_t count
= hol
.GetCount();
3636 for ( size_t n
= 0; n
< count
; n
++ )
3638 wxPrintf(_T("\t%s\n"), hol
[n
].Format(format
).c_str());
3641 wxPuts(wxEmptyString
);
3644 static void TestTimeZoneBug()
3646 wxPuts(_T("\n*** testing for DST/timezone bug ***\n"));
3648 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3649 for ( int i
= 0; i
< 31; i
++ )
3651 wxPrintf(_T("Date %s: week day %s.\n"),
3652 date
.Format(_T("%d-%m-%Y")).c_str(),
3653 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3655 date
+= wxDateSpan::Day();
3658 wxPuts(wxEmptyString
);
3661 static void TestTimeSpanFormat()
3663 wxPuts(_T("\n*** wxTimeSpan tests ***"));
3665 static const wxChar
*formats
[] =
3667 _T("(default) %H:%M:%S"),
3668 _T("%E weeks and %D days"),
3669 _T("%l milliseconds"),
3670 _T("(with ms) %H:%M:%S:%l"),
3671 _T("100%% of minutes is %M"), // test "%%"
3672 _T("%D days and %H hours"),
3673 _T("or also %S seconds"),
3676 wxTimeSpan
ts1(1, 2, 3, 4),
3678 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3680 wxPrintf(_T("ts1 = %s\tts2 = %s\n"),
3681 ts1
.Format(formats
[n
]).c_str(),
3682 ts2
.Format(formats
[n
]).c_str());
3685 wxPuts(wxEmptyString
);
3690 #endif // TEST_DATETIME
3692 // ----------------------------------------------------------------------------
3693 // wxTextInput/OutputStream
3694 // ----------------------------------------------------------------------------
3696 #ifdef TEST_TEXTSTREAM
3698 #include "wx/txtstrm.h"
3699 #include "wx/wfstream.h"
3701 static void TestTextInputStream()
3703 wxPuts(_T("\n*** wxTextInputStream test ***"));
3705 wxString filename
= _T("testdata.fc");
3706 wxFileInputStream
fsIn(filename
);
3709 wxPuts(_T("ERROR: couldn't open file."));
3713 wxTextInputStream
tis(fsIn
);
3718 const wxString s
= tis
.ReadLine();
3720 // line could be non empty if the last line of the file isn't
3721 // terminated with EOL
3722 if ( fsIn
.Eof() && s
.empty() )
3725 wxPrintf(_T("Line %d: %s\n"), line
++, s
.c_str());
3730 #endif // TEST_TEXTSTREAM
3732 // ----------------------------------------------------------------------------
3734 // ----------------------------------------------------------------------------
3738 #include "wx/thread.h"
3740 static size_t gs_counter
= (size_t)-1;
3741 static wxCriticalSection gs_critsect
;
3742 static wxSemaphore gs_cond
;
3744 class MyJoinableThread
: public wxThread
3747 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3748 { m_n
= n
; Create(); }
3750 // thread execution starts here
3751 virtual ExitCode
Entry();
3757 wxThread::ExitCode
MyJoinableThread::Entry()
3759 unsigned long res
= 1;
3760 for ( size_t n
= 1; n
< m_n
; n
++ )
3764 // it's a loooong calculation :-)
3768 return (ExitCode
)res
;
3771 class MyDetachedThread
: public wxThread
3774 MyDetachedThread(size_t n
, wxChar ch
)
3778 m_cancelled
= false;
3783 // thread execution starts here
3784 virtual ExitCode
Entry();
3787 virtual void OnExit();
3790 size_t m_n
; // number of characters to write
3791 wxChar m_ch
; // character to write
3793 bool m_cancelled
; // false if we exit normally
3796 wxThread::ExitCode
MyDetachedThread::Entry()
3799 wxCriticalSectionLocker
lock(gs_critsect
);
3800 if ( gs_counter
== (size_t)-1 )
3806 for ( size_t n
= 0; n
< m_n
; n
++ )
3808 if ( TestDestroy() )
3818 wxThread::Sleep(100);
3824 void MyDetachedThread::OnExit()
3826 wxLogTrace(_T("thread"), _T("Thread %ld is in OnExit"), GetId());
3828 wxCriticalSectionLocker
lock(gs_critsect
);
3829 if ( !--gs_counter
&& !m_cancelled
)
3833 static void TestDetachedThreads()
3835 wxPuts(_T("\n*** Testing detached threads ***"));
3837 static const size_t nThreads
= 3;
3838 MyDetachedThread
*threads
[nThreads
];
3840 for ( n
= 0; n
< nThreads
; n
++ )
3842 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3845 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3846 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3848 for ( n
= 0; n
< nThreads
; n
++ )
3853 // wait until all threads terminate
3856 wxPuts(wxEmptyString
);
3859 static void TestJoinableThreads()
3861 wxPuts(_T("\n*** Testing a joinable thread (a loooong calculation...) ***"));
3863 // calc 10! in the background
3864 MyJoinableThread
thread(10);
3867 wxPrintf(_T("\nThread terminated with exit code %lu.\n"),
3868 (unsigned long)thread
.Wait());
3871 static void TestThreadSuspend()
3873 wxPuts(_T("\n*** Testing thread suspend/resume functions ***"));
3875 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3879 // this is for this demo only, in a real life program we'd use another
3880 // condition variable which would be signaled from wxThread::Entry() to
3881 // tell us that the thread really started running - but here just wait a
3882 // bit and hope that it will be enough (the problem is, of course, that
3883 // the thread might still not run when we call Pause() which will result
3885 wxThread::Sleep(300);
3887 for ( size_t n
= 0; n
< 3; n
++ )
3891 wxPuts(_T("\nThread suspended"));
3894 // don't sleep but resume immediately the first time
3895 wxThread::Sleep(300);
3897 wxPuts(_T("Going to resume the thread"));
3902 wxPuts(_T("Waiting until it terminates now"));
3904 // wait until the thread terminates
3907 wxPuts(wxEmptyString
);
3910 static void TestThreadDelete()
3912 // As above, using Sleep() is only for testing here - we must use some
3913 // synchronisation object instead to ensure that the thread is still
3914 // running when we delete it - deleting a detached thread which already
3915 // terminated will lead to a crash!
3917 wxPuts(_T("\n*** Testing thread delete function ***"));
3919 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3923 wxPuts(_T("\nDeleted a thread which didn't start to run yet."));
3925 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3929 wxThread::Sleep(300);
3933 wxPuts(_T("\nDeleted a running thread."));
3935 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3939 wxThread::Sleep(300);
3945 wxPuts(_T("\nDeleted a sleeping thread."));
3947 MyJoinableThread
thread3(20);
3952 wxPuts(_T("\nDeleted a joinable thread."));
3954 MyJoinableThread
thread4(2);
3957 wxThread::Sleep(300);
3961 wxPuts(_T("\nDeleted a joinable thread which already terminated."));
3963 wxPuts(wxEmptyString
);
3966 class MyWaitingThread
: public wxThread
3969 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
3972 m_condition
= condition
;
3977 virtual ExitCode
Entry()
3979 wxPrintf(_T("Thread %lu has started running.\n"), GetId());
3984 wxPrintf(_T("Thread %lu starts to wait...\n"), GetId());
3988 m_condition
->Wait();
3991 wxPrintf(_T("Thread %lu finished to wait, exiting.\n"), GetId());
3999 wxCondition
*m_condition
;
4002 static void TestThreadConditions()
4005 wxCondition
condition(mutex
);
4007 // otherwise its difficult to understand which log messages pertain to
4009 //wxLogTrace(_T("thread"), _T("Local condition var is %08x, gs_cond = %08x"),
4010 // condition.GetId(), gs_cond.GetId());
4012 // create and launch threads
4013 MyWaitingThread
*threads
[10];
4016 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4018 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
4021 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4026 // wait until all threads run
4027 wxPuts(_T("Main thread is waiting for the other threads to start"));
4030 size_t nRunning
= 0;
4031 while ( nRunning
< WXSIZEOF(threads
) )
4037 wxPrintf(_T("Main thread: %u already running\n"), nRunning
);
4041 wxPuts(_T("Main thread: all threads started up."));
4044 wxThread::Sleep(500);
4047 // now wake one of them up
4048 wxPrintf(_T("Main thread: about to signal the condition.\n"));
4053 wxThread::Sleep(200);
4055 // wake all the (remaining) threads up, so that they can exit
4056 wxPrintf(_T("Main thread: about to broadcast the condition.\n"));
4058 condition
.Broadcast();
4060 // give them time to terminate (dirty!)
4061 wxThread::Sleep(500);
4065 #include "wx/datetime.h"
4067 class MySemaphoreThread
: public wxThread
4070 MySemaphoreThread(int i
, wxSemaphore
*sem
)
4071 : wxThread(wxTHREAD_JOINABLE
),
4078 virtual ExitCode
Entry()
4080 wxPrintf(_T("%s: Thread #%d (%ld) starting to wait for semaphore...\n"),
4081 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
4085 wxPrintf(_T("%s: Thread #%d (%ld) acquired the semaphore.\n"),
4086 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
4090 wxPrintf(_T("%s: Thread #%d (%ld) releasing the semaphore.\n"),
4091 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
4103 WX_DEFINE_ARRAY_PTR(wxThread
*, ArrayThreads
);
4105 static void TestSemaphore()
4107 wxPuts(_T("*** Testing wxSemaphore class. ***"));
4109 static const int SEM_LIMIT
= 3;
4111 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
4112 ArrayThreads threads
;
4114 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
4116 threads
.Add(new MySemaphoreThread(i
, &sem
));
4117 threads
.Last()->Run();
4120 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
4127 #endif // TEST_THREADS
4129 // ----------------------------------------------------------------------------
4131 // ----------------------------------------------------------------------------
4133 #ifdef TEST_SNGLINST
4134 #include "wx/snglinst.h"
4135 #endif // TEST_SNGLINST
4137 int main(int argc
, char **argv
)
4140 wxChar
**wxArgv
= new wxChar
*[argc
+ 1];
4145 for (n
= 0; n
< argc
; n
++ )
4147 wxMB2WXbuf warg
= wxConvertMB2WX(argv
[n
]);
4148 wxArgv
[n
] = wxStrdup(warg
);
4153 #else // !wxUSE_UNICODE
4155 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
4157 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "program");
4159 wxInitializer initializer
;
4162 fprintf(stderr
, "Failed to initialize the wxWidgets library, aborting.");
4167 #ifdef TEST_SNGLINST
4168 wxSingleInstanceChecker checker
;
4169 if ( checker
.Create(_T(".wxconsole.lock")) )
4171 if ( checker
.IsAnotherRunning() )
4173 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4178 // wait some time to give time to launch another instance
4179 wxPrintf(_T("Press \"Enter\" to continue..."));
4182 else // failed to create
4184 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4186 #endif // TEST_SNGLINST
4189 TestCmdLineConvert();
4191 #if wxUSE_CMDLINE_PARSER
4192 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4194 { wxCMD_LINE_SWITCH
, "h", "help", "show this help message",
4195 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
4196 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4197 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4199 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4200 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4201 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
4202 wxCMD_LINE_VAL_NUMBER
},
4203 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
4204 wxCMD_LINE_VAL_DATE
},
4205 { wxCMD_LINE_OPTION
, "f", "double", "output double",
4206 wxCMD_LINE_VAL_DOUBLE
},
4208 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4209 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4214 wxCmdLineParser
parser(cmdLineDesc
, argc
, wxArgv
);
4216 parser
.AddOption(_T("project_name"), _T(""), _T("full path to project file"),
4217 wxCMD_LINE_VAL_STRING
,
4218 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4220 switch ( parser
.Parse() )
4223 wxLogMessage(_T("Help was given, terminating."));
4227 ShowCmdLine(parser
);
4231 wxLogMessage(_T("Syntax error detected, aborting."));
4234 #endif // wxUSE_CMDLINE_PARSER
4236 #endif // TEST_CMDLINE
4248 TestDllListLoaded();
4249 #endif // TEST_DYNLIB
4253 #endif // TEST_ENVIRON
4255 #ifdef TEST_FILECONF
4257 #endif // TEST_FILECONF
4261 #endif // TEST_LOCALE
4264 wxPuts(_T("*** Testing wxLog ***"));
4267 for ( size_t n
= 0; n
< 8000; n
++ )
4269 s
<< (wxChar
)(_T('A') + (n
% 26));
4272 wxLogWarning(_T("The length of the string is %lu"),
4273 (unsigned long)s
.length());
4276 msg
.Printf(_T("A very very long message: '%s', the end!\n"), s
.c_str());
4278 // this one shouldn't be truncated
4281 // but this one will because log functions use fixed size buffer
4282 // (note that it doesn't need '\n' at the end neither - will be added
4284 wxLogMessage(_T("A very very long message 2: '%s', the end!"), s
.c_str());
4294 #ifdef TEST_FILENAME
4297 TestFileNameDirManip();
4298 TestFileNameComparison();
4299 TestFileNameOperations();
4300 #endif // TEST_FILENAME
4302 #ifdef TEST_FILETIME
4307 #endif // TEST_FILETIME
4310 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4312 // wxFTP cannot be a static variable as its ctor needs to access
4313 // wxWidgets internals after it has been initialized
4315 ftp
->SetLog(new wxProtocolLog(FTP_TRACE_MASK
));
4317 if ( TestFtpConnect() )
4327 #if TEST_INTERACTIVE
4328 //TestFtpInteractive();
4331 //else: connecting to the FTP server failed
4337 //wxLog::AddTraceMask(_T("mime"));
4341 TestMimeAssociate();
4346 #ifdef TEST_INFO_FUNCTIONS
4351 #if TEST_INTERACTIVE
4354 #endif // TEST_INFO_FUNCTIONS
4356 #ifdef TEST_PATHLIST
4358 #endif // TEST_PATHLIST
4362 #endif // TEST_PRINTF
4369 #endif // TEST_REGCONF
4371 #if defined TEST_REGEX && TEST_INTERACTIVE
4372 TestRegExInteractive();
4373 #endif // defined TEST_REGEX && TEST_INTERACTIVE
4375 #ifdef TEST_REGISTRY
4377 TestRegistryAssociation();
4378 #endif // TEST_REGISTRY
4383 #endif // TEST_SOCKETS
4390 #endif // TEST_STREAMS
4392 #ifdef TEST_TEXTSTREAM
4393 TestTextInputStream();
4394 #endif // TEST_TEXTSTREAM
4397 int nCPUs
= wxThread::GetCPUCount();
4398 wxPrintf(_T("This system has %d CPUs\n"), nCPUs
);
4400 wxThread::SetConcurrency(nCPUs
);
4402 TestJoinableThreads();
4405 TestJoinableThreads();
4406 TestDetachedThreads();
4407 TestThreadSuspend();
4409 TestThreadConditions();
4412 #endif // TEST_THREADS
4417 #endif // TEST_TIMER
4419 #ifdef TEST_DATETIME
4426 TestTimeSpanFormat();
4432 #if TEST_INTERACTIVE
4433 TestDateTimeInteractive();
4435 #endif // TEST_DATETIME
4437 #ifdef TEST_SCOPEGUARD
4441 #ifdef TEST_STACKWALKER
4442 #if wxUSE_STACKWALKER
4443 TestStackWalk(argv
[0]);
4445 #endif // TEST_STACKWALKER
4447 #ifdef TEST_STDPATHS
4448 TestStandardPaths();
4452 wxPuts(_T("Sleeping for 3 seconds... z-z-z-z-z..."));
4454 #endif // TEST_USLEEP
4459 #endif // TEST_VCARD
4463 #endif // TEST_VOLUME
4467 TestEncodingConverter();
4468 #endif // TEST_WCHAR
4471 TestZipStreamRead();
4472 TestZipFileSystem();
4477 for ( int n
= 0; n
< argc
; n
++ )
4482 #endif // wxUSE_UNICODE