1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWindows
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
22 #include <wx/string.h>
26 // without this pragma, the stupid compiler precompiles #defines below so that
27 // changing them doesn't "take place" later!
32 // ----------------------------------------------------------------------------
33 // conditional compilation
34 // ----------------------------------------------------------------------------
36 // what to test (in alphabetic order)?
39 //#define TEST_CMDLINE
40 //#define TEST_DATETIME
42 //#define TEST_DLLLOADER
43 //#define TEST_ENVIRON
44 //#define TEST_EXECUTE
46 //#define TEST_FILECONF
47 //#define TEST_FILENAME
50 //#define TEST_INFO_FUNCTIONS
54 //#define TEST_LONGLONG
56 //#define TEST_PATHLIST
58 //#define TEST_REGISTRY
59 //#define TEST_SOCKETS
60 //#define TEST_STREAMS
61 //#define TEST_STRINGS
62 //#define TEST_THREADS
64 //#define TEST_VCARD -- don't enable this (VZ)
75 // ----------------------------------------------------------------------------
76 // test class for container objects
77 // ----------------------------------------------------------------------------
79 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
81 class Bar
// Foo is already taken in the hash test
84 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
87 static size_t GetNumber() { return ms_bars
; }
89 const char *GetName() const { return m_name
; }
94 static size_t ms_bars
;
97 size_t Bar::ms_bars
= 0;
99 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
101 // ============================================================================
103 // ============================================================================
105 // ----------------------------------------------------------------------------
107 // ----------------------------------------------------------------------------
109 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
111 // replace TABs with \t and CRs with \n
112 static wxString
MakePrintable(const wxChar
*s
)
115 (void)str
.Replace(_T("\t"), _T("\\t"));
116 (void)str
.Replace(_T("\n"), _T("\\n"));
117 (void)str
.Replace(_T("\r"), _T("\\r"));
122 #endif // MakePrintable() is used
124 // ----------------------------------------------------------------------------
126 // ----------------------------------------------------------------------------
130 #include <wx/cmdline.h>
131 #include <wx/datetime.h>
133 static void ShowCmdLine(const wxCmdLineParser
& parser
)
135 wxString s
= "Input files: ";
137 size_t count
= parser
.GetParamCount();
138 for ( size_t param
= 0; param
< count
; param
++ )
140 s
<< parser
.GetParam(param
) << ' ';
144 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
145 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
150 if ( parser
.Found("o", &strVal
) )
151 s
<< "Output file:\t" << strVal
<< '\n';
152 if ( parser
.Found("i", &strVal
) )
153 s
<< "Input dir:\t" << strVal
<< '\n';
154 if ( parser
.Found("s", &lVal
) )
155 s
<< "Size:\t" << lVal
<< '\n';
156 if ( parser
.Found("d", &dt
) )
157 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
158 if ( parser
.Found("project_name", &strVal
) )
159 s
<< "Project:\t" << strVal
<< '\n';
164 #endif // TEST_CMDLINE
166 // ----------------------------------------------------------------------------
168 // ----------------------------------------------------------------------------
174 static void TestDirEnumHelper(wxDir
& dir
,
175 int flags
= wxDIR_DEFAULT
,
176 const wxString
& filespec
= wxEmptyString
)
180 if ( !dir
.IsOpened() )
183 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
186 printf("\t%s\n", filename
.c_str());
188 cont
= dir
.GetNext(&filename
);
194 static void TestDirEnum()
196 wxDir
dir(wxGetCwd());
198 puts("Enumerating everything in current directory:");
199 TestDirEnumHelper(dir
);
201 puts("Enumerating really everything in current directory:");
202 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
204 puts("Enumerating object files in current directory:");
205 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
207 puts("Enumerating directories in current directory:");
208 TestDirEnumHelper(dir
, wxDIR_DIRS
);
210 puts("Enumerating files in current directory:");
211 TestDirEnumHelper(dir
, wxDIR_FILES
);
213 puts("Enumerating files including hidden in current directory:");
214 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
218 #elif defined(__WXMSW__)
221 #error "don't know where the root directory is"
224 puts("Enumerating everything in root directory:");
225 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
227 puts("Enumerating directories in root directory:");
228 TestDirEnumHelper(dir
, wxDIR_DIRS
);
230 puts("Enumerating files in root directory:");
231 TestDirEnumHelper(dir
, wxDIR_FILES
);
233 puts("Enumerating files including hidden in root directory:");
234 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
236 puts("Enumerating files in non existing directory:");
237 wxDir
dirNo("nosuchdir");
238 TestDirEnumHelper(dirNo
);
243 // ----------------------------------------------------------------------------
245 // ----------------------------------------------------------------------------
247 #ifdef TEST_DLLLOADER
249 #include <wx/dynlib.h>
251 static void TestDllLoad()
253 #if defined(__WXMSW__)
254 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
255 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
256 #elif defined(__UNIX__)
257 // weird: using just libc.so does *not* work!
258 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
259 static const wxChar
*FUNC_NAME
= _T("strlen");
261 #error "don't know how to test wxDllLoader on this platform"
264 puts("*** testing wxDllLoader ***\n");
266 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
269 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
273 typedef int (*strlenType
)(char *);
274 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
277 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
278 FUNC_NAME
, LIB_NAME
);
282 if ( pfnStrlen("foo") != 3 )
284 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
292 wxDllLoader::UnloadLibrary(dllHandle
);
296 #endif // TEST_DLLLOADER
298 // ----------------------------------------------------------------------------
300 // ----------------------------------------------------------------------------
304 #include <wx/utils.h>
306 static wxString
MyGetEnv(const wxString
& var
)
309 if ( !wxGetEnv(var
, &val
) )
312 val
= wxString(_T('\'')) + val
+ _T('\'');
317 static void TestEnvironment()
319 const wxChar
*var
= _T("wxTestVar");
321 puts("*** testing environment access functions ***");
323 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
324 wxSetEnv(var
, _T("value for wxTestVar"));
325 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
326 wxSetEnv(var
, _T("another value"));
327 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
329 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
330 printf("PATH = %s\n", MyGetEnv(_T("PATH")));
333 #endif // TEST_ENVIRON
335 // ----------------------------------------------------------------------------
337 // ----------------------------------------------------------------------------
341 #include <wx/utils.h>
343 static void TestExecute()
345 puts("*** testing wxExecute ***");
348 #define COMMAND "cat -n ../../Makefile" // "echo hi"
349 #define SHELL_COMMAND "echo hi from shell"
350 #define REDIRECT_COMMAND COMMAND // "date"
351 #elif defined(__WXMSW__)
352 #define COMMAND "command.com -c 'echo hi'"
353 #define SHELL_COMMAND "echo hi"
354 #define REDIRECT_COMMAND COMMAND
356 #error "no command to exec"
359 printf("Testing wxShell: ");
361 if ( wxShell(SHELL_COMMAND
) )
366 printf("Testing wxExecute: ");
368 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
373 #if 0 // no, it doesn't work (yet?)
374 printf("Testing async wxExecute: ");
376 if ( wxExecute(COMMAND
) != 0 )
377 puts("Ok (command launched).");
382 printf("Testing wxExecute with redirection:\n");
383 wxArrayString output
;
384 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
390 size_t count
= output
.GetCount();
391 for ( size_t n
= 0; n
< count
; n
++ )
393 printf("\t%s\n", output
[n
].c_str());
400 #endif // TEST_EXECUTE
402 // ----------------------------------------------------------------------------
404 // ----------------------------------------------------------------------------
409 #include <wx/ffile.h>
410 #include <wx/textfile.h>
412 static void TestFileRead()
414 puts("*** wxFile read test ***");
416 wxFile
file(_T("testdata.fc"));
417 if ( file
.IsOpened() )
419 printf("File length: %lu\n", file
.Length());
421 puts("File dump:\n----------");
423 static const off_t len
= 1024;
427 off_t nRead
= file
.Read(buf
, len
);
428 if ( nRead
== wxInvalidOffset
)
430 printf("Failed to read the file.");
434 fwrite(buf
, nRead
, 1, stdout
);
444 printf("ERROR: can't open test file.\n");
450 static void TestTextFileRead()
452 puts("*** wxTextFile read test ***");
454 wxTextFile
file(_T("testdata.fc"));
457 printf("Number of lines: %u\n", file
.GetLineCount());
458 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
462 puts("\nDumping the entire file:");
463 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
465 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
467 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
469 puts("\nAnd now backwards:");
470 for ( s
= file
.GetLastLine();
471 file
.GetCurrentLine() != 0;
472 s
= file
.GetPrevLine() )
474 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
476 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
480 printf("ERROR: can't open '%s'\n", file
.GetName());
486 static void TestFileCopy()
488 puts("*** Testing wxCopyFile ***");
490 static const wxChar
*filename1
= _T("testdata.fc");
491 static const wxChar
*filename2
= _T("test2");
492 if ( !wxCopyFile(filename1
, filename2
) )
494 puts("ERROR: failed to copy file");
498 wxFFile
f1(filename1
, "rb"),
501 if ( !f1
.IsOpened() || !f2
.IsOpened() )
503 puts("ERROR: failed to open file(s)");
508 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
510 puts("ERROR: failed to read file(s)");
514 if ( (s1
.length() != s2
.length()) ||
515 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
517 puts("ERROR: copy error!");
521 puts("File was copied ok.");
527 if ( !wxRemoveFile(filename2
) )
529 puts("ERROR: failed to remove the file");
537 // ----------------------------------------------------------------------------
539 // ----------------------------------------------------------------------------
543 #include <wx/confbase.h>
544 #include <wx/fileconf.h>
546 static const struct FileConfTestData
548 const wxChar
*name
; // value name
549 const wxChar
*value
; // the value from the file
552 { _T("value1"), _T("one") },
553 { _T("value2"), _T("two") },
554 { _T("novalue"), _T("default") },
557 static void TestFileConfRead()
559 puts("*** testing wxFileConfig loading/reading ***");
561 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
562 _T("testdata.fc"), wxEmptyString
,
563 wxCONFIG_USE_RELATIVE_PATH
);
565 // test simple reading
566 puts("\nReading config file:");
567 wxString
defValue(_T("default")), value
;
568 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
570 const FileConfTestData
& data
= fcTestData
[n
];
571 value
= fileconf
.Read(data
.name
, defValue
);
572 printf("\t%s = %s ", data
.name
, value
.c_str());
573 if ( value
== data
.value
)
579 printf("(ERROR: should be %s)\n", data
.value
);
583 // test enumerating the entries
584 puts("\nEnumerating all root entries:");
587 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
590 printf("\t%s = %s\n",
592 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
594 cont
= fileconf
.GetNextEntry(name
, dummy
);
598 #endif // TEST_FILECONF
600 // ----------------------------------------------------------------------------
602 // ----------------------------------------------------------------------------
606 #include <wx/filename.h>
608 static struct FileNameInfo
610 const wxChar
*fullname
;
616 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
617 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
618 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
619 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
620 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
621 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
622 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
623 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
626 static void TestFileNameConstruction()
628 puts("*** testing wxFileName construction ***");
630 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
632 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
634 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
635 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
637 puts("ERROR (couldn't be normalized)");
641 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
648 static void TestFileNameSplit()
650 puts("*** testing wxFileName splitting ***");
652 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
654 const FileNameInfo
&fni
= filenames
[n
];
655 wxString path
, name
, ext
;
656 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
658 printf("%s -> path = '%s', name = '%s', ext = '%s'",
659 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
660 if ( path
!= fni
.path
)
661 printf(" (ERROR: path = '%s')", fni
.path
);
662 if ( name
!= fni
.name
)
663 printf(" (ERROR: name = '%s')", fni
.name
);
664 if ( ext
!= fni
.ext
)
665 printf(" (ERROR: ext = '%s')", fni
.ext
);
672 static void TestFileNameComparison()
677 static void TestFileNameOperations()
682 static void TestFileNameCwd()
687 #endif // TEST_FILENAME
689 // ----------------------------------------------------------------------------
691 // ----------------------------------------------------------------------------
699 Foo(int n_
) { n
= n_
; count
++; }
707 size_t Foo::count
= 0;
709 WX_DECLARE_LIST(Foo
, wxListFoos
);
710 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
712 #include <wx/listimpl.cpp>
714 WX_DEFINE_LIST(wxListFoos
);
716 static void TestHash()
718 puts("*** Testing wxHashTable ***\n");
722 hash
.DeleteContents(TRUE
);
724 printf("Hash created: %u foos in hash, %u foos totally\n",
725 hash
.GetCount(), Foo::count
);
727 static const int hashTestData
[] =
729 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
733 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
735 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
738 printf("Hash filled: %u foos in hash, %u foos totally\n",
739 hash
.GetCount(), Foo::count
);
741 puts("Hash access test:");
742 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
744 printf("\tGetting element with key %d, value %d: ",
746 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
749 printf("ERROR, not found.\n");
753 printf("%d (%s)\n", foo
->n
,
754 (size_t)foo
->n
== n
? "ok" : "ERROR");
758 printf("\nTrying to get an element not in hash: ");
760 if ( hash
.Get(1234) || hash
.Get(1, 0) )
762 puts("ERROR: found!");
766 puts("ok (not found)");
770 printf("Hash destroyed: %u foos left\n", Foo::count
);
775 // ----------------------------------------------------------------------------
777 // ----------------------------------------------------------------------------
783 WX_DECLARE_LIST(Bar
, wxListBars
);
784 #include <wx/listimpl.cpp>
785 WX_DEFINE_LIST(wxListBars
);
787 static void TestListCtor()
789 puts("*** Testing wxList construction ***\n");
793 list1
.Append(new Bar(_T("first")));
794 list1
.Append(new Bar(_T("second")));
796 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
797 list1
.GetCount(), Bar::GetNumber());
802 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
803 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
805 list1
.DeleteContents(TRUE
);
808 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
813 // ----------------------------------------------------------------------------
815 // ----------------------------------------------------------------------------
820 #include "wx/utils.h" // for wxSetEnv
822 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
824 // find the name of the language from its value
825 static const char *GetLangName(int lang
)
827 static const char *languageNames
[] =
848 "ARABIC_SAUDI_ARABIA",
873 "CHINESE_SIMPLIFIED",
874 "CHINESE_TRADITIONAL",
896 "ENGLISH_NEW_ZEALAND",
897 "ENGLISH_PHILIPPINES",
898 "ENGLISH_SOUTH_AFRICA",
919 "GERMAN_LIECHTENSTEIN",
961 "MALAY_BRUNEI_DARUSSALAM",
980 "PORTUGUESE_BRAZILIAN",
1005 "SPANISH_ARGENTINA",
1009 "SPANISH_COSTA_RICA",
1010 "SPANISH_DOMINICAN_REPUBLIC",
1012 "SPANISH_EL_SALVADOR",
1013 "SPANISH_GUATEMALA",
1017 "SPANISH_NICARAGUA",
1021 "SPANISH_PUERTO_RICO",
1024 "SPANISH_VENEZUELA",
1061 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1062 return languageNames
[lang
];
1067 static void TestDefaultLang()
1069 puts("*** Testing wxLocale::GetSystemLanguage ***");
1071 static const wxChar
*langStrings
[] =
1073 NULL
, // system default
1080 _T("de_DE.iso88591"),
1082 _T("?"), // invalid lang spec
1083 _T("klingonese"), // I bet on some systems it does exist...
1086 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1088 const char *langStr
= langStrings
[n
];
1090 wxSetEnv(_T("LC_ALL"), langStr
);
1092 int lang
= gs_localeDefault
.GetSystemLanguage();
1093 printf("Locale for '%s' is %s.\n",
1094 langStr
? langStr
: "system default", GetLangName(lang
));
1098 #endif // TEST_LOCALE
1100 // ----------------------------------------------------------------------------
1102 // ----------------------------------------------------------------------------
1106 #include <wx/mimetype.h>
1108 static void TestMimeEnum()
1110 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1112 wxArrayString mimetypes
;
1114 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1116 printf("*** All %u known filetypes: ***\n", count
);
1121 for ( size_t n
= 0; n
< count
; n
++ )
1123 wxFileType
*filetype
=
1124 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1127 printf("nothing known about the filetype '%s'!\n",
1128 mimetypes
[n
].c_str());
1132 filetype
->GetDescription(&desc
);
1133 filetype
->GetExtensions(exts
);
1135 filetype
->GetIcon(NULL
);
1138 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1141 extsAll
<< _T(", ");
1145 printf("\t%s: %s (%s)\n",
1146 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1152 static void TestMimeOverride()
1154 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1156 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1157 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1159 if ( wxFile::Exists(mailcap
) )
1160 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1162 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1164 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1167 if ( wxFile::Exists(mimetypes
) )
1168 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1170 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1172 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1178 static void TestMimeFilename()
1180 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1182 static const wxChar
*filenames
[] =
1189 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1191 const wxString fname
= filenames
[n
];
1192 wxString ext
= fname
.AfterLast(_T('.'));
1193 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1196 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1201 if ( !ft
->GetDescription(&desc
) )
1202 desc
= _T("<no description>");
1205 if ( !ft
->GetOpenCommand(&cmd
,
1206 wxFileType::MessageParameters(fname
, _T(""))) )
1207 cmd
= _T("<no command available>");
1209 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1210 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1219 static void TestMimeAssociate()
1221 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1223 wxFileTypeInfo
ftInfo(
1224 _T("application/x-xyz"),
1225 _T("xyzview '%s'"), // open cmd
1226 _T(""), // print cmd
1227 _T("XYZ File") // description
1228 _T(".xyz"), // extensions
1229 NULL
// end of extensions
1231 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1233 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1236 wxPuts(_T("ERROR: failed to create association!"));
1240 // TODO: read it back
1249 // ----------------------------------------------------------------------------
1250 // misc information functions
1251 // ----------------------------------------------------------------------------
1253 #ifdef TEST_INFO_FUNCTIONS
1255 #include <wx/utils.h>
1257 static void TestOsInfo()
1259 puts("*** Testing OS info functions ***\n");
1262 wxGetOsVersion(&major
, &minor
);
1263 printf("Running under: %s, version %d.%d\n",
1264 wxGetOsDescription().c_str(), major
, minor
);
1266 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1268 printf("Host name is %s (%s).\n",
1269 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1274 static void TestUserInfo()
1276 puts("*** Testing user info functions ***\n");
1278 printf("User id is:\t%s\n", wxGetUserId().c_str());
1279 printf("User name is:\t%s\n", wxGetUserName().c_str());
1280 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1281 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1286 #endif // TEST_INFO_FUNCTIONS
1288 // ----------------------------------------------------------------------------
1290 // ----------------------------------------------------------------------------
1292 #ifdef TEST_LONGLONG
1294 #include <wx/longlong.h>
1295 #include <wx/timer.h>
1297 // make a 64 bit number from 4 16 bit ones
1298 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1300 // get a random 64 bit number
1301 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1303 #if wxUSE_LONGLONG_WX
1304 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1305 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1306 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1307 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1308 #endif // wxUSE_LONGLONG_WX
1310 static void TestSpeed()
1312 static const long max
= 100000000;
1319 for ( n
= 0; n
< max
; n
++ )
1324 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1327 #if wxUSE_LONGLONG_NATIVE
1332 for ( n
= 0; n
< max
; n
++ )
1337 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1339 #endif // wxUSE_LONGLONG_NATIVE
1345 for ( n
= 0; n
< max
; n
++ )
1350 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1354 static void TestLongLongConversion()
1356 puts("*** Testing wxLongLong conversions ***\n");
1360 for ( size_t n
= 0; n
< 100000; n
++ )
1364 #if wxUSE_LONGLONG_NATIVE
1365 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1367 wxASSERT_MSG( a
== b
, "conversions failure" );
1369 puts("Can't do it without native long long type, test skipped.");
1372 #endif // wxUSE_LONGLONG_NATIVE
1374 if ( !(nTested
% 1000) )
1386 static void TestMultiplication()
1388 puts("*** Testing wxLongLong multiplication ***\n");
1392 for ( size_t n
= 0; n
< 100000; n
++ )
1397 #if wxUSE_LONGLONG_NATIVE
1398 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1399 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1401 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1402 #else // !wxUSE_LONGLONG_NATIVE
1403 puts("Can't do it without native long long type, test skipped.");
1406 #endif // wxUSE_LONGLONG_NATIVE
1408 if ( !(nTested
% 1000) )
1420 static void TestDivision()
1422 puts("*** Testing wxLongLong division ***\n");
1426 for ( size_t n
= 0; n
< 100000; n
++ )
1428 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1429 // multiplication will not overflow)
1430 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1432 // get a random long (not wxLongLong for now) to divide it with
1437 #if wxUSE_LONGLONG_NATIVE
1438 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1440 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1441 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1442 #else // !wxUSE_LONGLONG_NATIVE
1443 // verify the result
1444 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1445 #endif // wxUSE_LONGLONG_NATIVE
1447 if ( !(nTested
% 1000) )
1459 static void TestAddition()
1461 puts("*** Testing wxLongLong addition ***\n");
1465 for ( size_t n
= 0; n
< 100000; n
++ )
1471 #if wxUSE_LONGLONG_NATIVE
1472 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1473 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1474 "addition failure" );
1475 #else // !wxUSE_LONGLONG_NATIVE
1476 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1477 #endif // wxUSE_LONGLONG_NATIVE
1479 if ( !(nTested
% 1000) )
1491 static void TestBitOperations()
1493 puts("*** Testing wxLongLong bit operation ***\n");
1497 for ( size_t n
= 0; n
< 100000; n
++ )
1501 #if wxUSE_LONGLONG_NATIVE
1502 for ( size_t n
= 0; n
< 33; n
++ )
1505 #else // !wxUSE_LONGLONG_NATIVE
1506 puts("Can't do it without native long long type, test skipped.");
1509 #endif // wxUSE_LONGLONG_NATIVE
1511 if ( !(nTested
% 1000) )
1523 static void TestLongLongComparison()
1525 puts("*** Testing wxLongLong comparison ***\n");
1527 static const long testLongs
[] =
1538 static const long ls
[2] =
1544 wxLongLongWx lls
[2];
1548 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1552 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1554 res
= lls
[m
] > testLongs
[n
];
1555 printf("0x%lx > 0x%lx is %s (%s)\n",
1556 ls
[m
], testLongs
[n
], res
? "true" : "false",
1557 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1559 res
= lls
[m
] < testLongs
[n
];
1560 printf("0x%lx < 0x%lx is %s (%s)\n",
1561 ls
[m
], testLongs
[n
], res
? "true" : "false",
1562 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1564 res
= lls
[m
] == testLongs
[n
];
1565 printf("0x%lx == 0x%lx is %s (%s)\n",
1566 ls
[m
], testLongs
[n
], res
? "true" : "false",
1567 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1575 #endif // TEST_LONGLONG
1577 // ----------------------------------------------------------------------------
1579 // ----------------------------------------------------------------------------
1581 #ifdef TEST_PATHLIST
1583 static void TestPathList()
1585 puts("*** Testing wxPathList ***\n");
1587 wxPathList pathlist
;
1588 pathlist
.AddEnvList("PATH");
1589 wxString path
= pathlist
.FindValidPath("ls");
1592 printf("ERROR: command not found in the path.\n");
1596 printf("Command found in the path as '%s'.\n", path
.c_str());
1600 #endif // TEST_PATHLIST
1602 // ----------------------------------------------------------------------------
1603 // registry and related stuff
1604 // ----------------------------------------------------------------------------
1606 // this is for MSW only
1609 #undef TEST_REGISTRY
1614 #include <wx/confbase.h>
1615 #include <wx/msw/regconf.h>
1617 static void TestRegConfWrite()
1619 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
1620 regconf
.Write(_T("Hello"), wxString(_T("world")));
1623 #endif // TEST_REGCONF
1625 #ifdef TEST_REGISTRY
1627 #include <wx/msw/registry.h>
1629 // I chose this one because I liked its name, but it probably only exists under
1631 static const wxChar
*TESTKEY
=
1632 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1634 static void TestRegistryRead()
1636 puts("*** testing registry reading ***");
1638 wxRegKey
key(TESTKEY
);
1639 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1642 puts("ERROR: test key can't be opened, aborting test.");
1647 size_t nSubKeys
, nValues
;
1648 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1650 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1653 printf("Enumerating values:\n");
1657 bool cont
= key
.GetFirstValue(value
, dummy
);
1660 printf("Value '%s': type ", value
.c_str());
1661 switch ( key
.GetValueType(value
) )
1663 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1664 case wxRegKey::Type_String
: printf("SZ"); break;
1665 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1666 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1667 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1668 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1669 default: printf("other (unknown)"); break;
1672 printf(", value = ");
1673 if ( key
.IsNumericValue(value
) )
1676 key
.QueryValue(value
, &val
);
1682 key
.QueryValue(value
, val
);
1683 printf("'%s'", val
.c_str());
1685 key
.QueryRawValue(value
, val
);
1686 printf(" (raw value '%s')", val
.c_str());
1691 cont
= key
.GetNextValue(value
, dummy
);
1695 static void TestRegistryAssociation()
1698 The second call to deleteself genertaes an error message, with a
1699 messagebox saying .flo is crucial to system operation, while the .ddf
1700 call also fails, but with no error message
1705 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1707 key
= "ddxf_auto_file" ;
1708 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1710 key
= "ddxf_auto_file" ;
1711 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1714 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1716 key
= "program \"%1\"" ;
1718 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1720 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1722 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1724 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1728 #endif // TEST_REGISTRY
1730 // ----------------------------------------------------------------------------
1732 // ----------------------------------------------------------------------------
1736 #include <wx/socket.h>
1737 #include <wx/protocol/protocol.h>
1738 #include <wx/protocol/http.h>
1740 static void TestSocketServer()
1742 puts("*** Testing wxSocketServer ***\n");
1744 static const int PORT
= 3000;
1749 wxSocketServer
*server
= new wxSocketServer(addr
);
1750 if ( !server
->Ok() )
1752 puts("ERROR: failed to bind");
1759 printf("Server: waiting for connection on port %d...\n", PORT
);
1761 wxSocketBase
*socket
= server
->Accept();
1764 puts("ERROR: wxSocketServer::Accept() failed.");
1768 puts("Server: got a client.");
1770 server
->SetTimeout(60); // 1 min
1772 while ( socket
->IsConnected() )
1778 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1780 // don't log error if the client just close the connection
1781 if ( socket
->IsConnected() )
1783 puts("ERROR: in wxSocket::Read.");
1803 printf("Server: got '%s'.\n", s
.c_str());
1804 if ( s
== _T("bye") )
1811 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1812 socket
->Write("\r\n", 2);
1813 printf("Server: wrote '%s'.\n", s
.c_str());
1816 puts("Server: lost a client.");
1821 // same as "delete server" but is consistent with GUI programs
1825 static void TestSocketClient()
1827 puts("*** Testing wxSocketClient ***\n");
1829 static const char *hostname
= "www.wxwindows.org";
1832 addr
.Hostname(hostname
);
1835 printf("--- Attempting to connect to %s:80...\n", hostname
);
1837 wxSocketClient client
;
1838 if ( !client
.Connect(addr
) )
1840 printf("ERROR: failed to connect to %s\n", hostname
);
1844 printf("--- Connected to %s:%u...\n",
1845 addr
.Hostname().c_str(), addr
.Service());
1849 // could use simply "GET" here I suppose
1851 wxString::Format("GET http://%s/\r\n", hostname
);
1852 client
.Write(cmdGet
, cmdGet
.length());
1853 printf("--- Sent command '%s' to the server\n",
1854 MakePrintable(cmdGet
).c_str());
1855 client
.Read(buf
, WXSIZEOF(buf
));
1856 printf("--- Server replied:\n%s", buf
);
1860 #endif // TEST_SOCKETS
1862 // ----------------------------------------------------------------------------
1864 // ----------------------------------------------------------------------------
1868 #include <wx/protocol/ftp.h>
1872 #define FTP_ANONYMOUS
1874 #ifdef FTP_ANONYMOUS
1875 static const char *directory
= "/pub";
1876 static const char *filename
= "welcome.msg";
1878 static const char *directory
= "/etc";
1879 static const char *filename
= "issue";
1882 static bool TestFtpConnect()
1884 puts("*** Testing FTP connect ***");
1886 #ifdef FTP_ANONYMOUS
1887 static const char *hostname
= "ftp.wxwindows.org";
1889 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1890 #else // !FTP_ANONYMOUS
1891 static const char *hostname
= "localhost";
1894 fgets(user
, WXSIZEOF(user
), stdin
);
1895 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
1899 printf("Password for %s: ", password
);
1900 fgets(password
, WXSIZEOF(password
), stdin
);
1901 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
1902 ftp
.SetPassword(password
);
1904 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
1905 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
1907 if ( !ftp
.Connect(hostname
) )
1909 printf("ERROR: failed to connect to %s\n", hostname
);
1915 printf("--- Connected to %s, current directory is '%s'\n",
1916 hostname
, ftp
.Pwd().c_str());
1922 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
1923 static void TestFtpWuFtpd()
1926 static const char *hostname
= "ftp.eudora.com";
1927 if ( !ftp
.Connect(hostname
) )
1929 printf("ERROR: failed to connect to %s\n", hostname
);
1933 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
1934 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1937 printf("ERROR: couldn't get input stream for %s\n", filename
);
1941 size_t size
= in
->StreamSize();
1942 printf("Reading file %s (%u bytes)...", filename
, size
);
1944 char *data
= new char[size
];
1945 if ( !in
->Read(data
, size
) )
1947 puts("ERROR: read error");
1951 printf("Successfully retrieved the file.\n");
1960 static void TestFtpList()
1962 puts("*** Testing wxFTP file listing ***\n");
1965 if ( !ftp
.ChDir(directory
) )
1967 printf("ERROR: failed to cd to %s\n", directory
);
1970 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
1972 // test NLIST and LIST
1973 wxArrayString files
;
1974 if ( !ftp
.GetFilesList(files
) )
1976 puts("ERROR: failed to get NLIST of files");
1980 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
1981 size_t count
= files
.GetCount();
1982 for ( size_t n
= 0; n
< count
; n
++ )
1984 printf("\t%s\n", files
[n
].c_str());
1986 puts("End of the file list");
1989 if ( !ftp
.GetDirList(files
) )
1991 puts("ERROR: failed to get LIST of files");
1995 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
1996 size_t count
= files
.GetCount();
1997 for ( size_t n
= 0; n
< count
; n
++ )
1999 printf("\t%s\n", files
[n
].c_str());
2001 puts("End of the file list");
2004 if ( !ftp
.ChDir(_T("..")) )
2006 puts("ERROR: failed to cd to ..");
2009 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2012 static void TestFtpDownload()
2014 puts("*** Testing wxFTP download ***\n");
2017 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2020 printf("ERROR: couldn't get input stream for %s\n", filename
);
2024 size_t size
= in
->StreamSize();
2025 printf("Reading file %s (%u bytes)...", filename
, size
);
2028 char *data
= new char[size
];
2029 if ( !in
->Read(data
, size
) )
2031 puts("ERROR: read error");
2035 printf("\nContents of %s:\n%s\n", filename
, data
);
2043 static void TestFtpFileSize()
2045 puts("*** Testing FTP SIZE command ***");
2047 if ( !ftp
.ChDir(directory
) )
2049 printf("ERROR: failed to cd to %s\n", directory
);
2052 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2054 if ( ftp
.FileExists(filename
) )
2056 int size
= ftp
.GetFileSize(filename
);
2058 printf("ERROR: couldn't get size of '%s'\n", filename
);
2060 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2064 printf("ERROR: '%s' doesn't exist\n", filename
);
2068 static void TestFtpMisc()
2070 puts("*** Testing miscellaneous wxFTP functions ***");
2072 if ( ftp
.SendCommand("STAT") != '2' )
2074 puts("ERROR: STAT failed");
2078 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2081 if ( ftp
.SendCommand("HELP SITE") != '2' )
2083 puts("ERROR: HELP SITE failed");
2087 printf("The list of site-specific commands:\n\n%s\n",
2088 ftp
.GetLastResult().c_str());
2092 static void TestFtpInteractive()
2094 puts("\n*** Interactive wxFTP test ***");
2100 printf("Enter FTP command: ");
2101 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2104 // kill the last '\n'
2105 buf
[strlen(buf
) - 1] = 0;
2107 // special handling of LIST and NLST as they require data connection
2108 wxString
start(buf
, 4);
2110 if ( start
== "LIST" || start
== "NLST" )
2113 if ( strlen(buf
) > 4 )
2116 wxArrayString files
;
2117 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2119 printf("ERROR: failed to get %s of files\n", start
.c_str());
2123 printf("--- %s of '%s' under '%s':\n",
2124 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2125 size_t count
= files
.GetCount();
2126 for ( size_t n
= 0; n
< count
; n
++ )
2128 printf("\t%s\n", files
[n
].c_str());
2130 puts("--- End of the file list");
2135 char ch
= ftp
.SendCommand(buf
);
2136 printf("Command %s", ch
? "succeeded" : "failed");
2139 printf(" (return code %c)", ch
);
2142 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2146 puts("\n*** done ***");
2149 static void TestFtpUpload()
2151 puts("*** Testing wxFTP uploading ***\n");
2154 static const char *file1
= "test1";
2155 static const char *file2
= "test2";
2156 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2159 printf("--- Uploading to %s ---\n", file1
);
2160 out
->Write("First hello", 11);
2164 // send a command to check the remote file
2165 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2167 printf("ERROR: STAT %s failed\n", file1
);
2171 printf("STAT %s returned:\n\n%s\n",
2172 file1
, ftp
.GetLastResult().c_str());
2175 out
= ftp
.GetOutputStream(file2
);
2178 printf("--- Uploading to %s ---\n", file1
);
2179 out
->Write("Second hello", 12);
2186 // ----------------------------------------------------------------------------
2188 // ----------------------------------------------------------------------------
2192 #include <wx/wfstream.h>
2193 #include <wx/mstream.h>
2195 static void TestFileStream()
2197 puts("*** Testing wxFileInputStream ***");
2199 static const wxChar
*filename
= _T("testdata.fs");
2201 wxFileOutputStream
fsOut(filename
);
2202 fsOut
.Write("foo", 3);
2205 wxFileInputStream
fsIn(filename
);
2206 printf("File stream size: %u\n", fsIn
.GetSize());
2207 while ( !fsIn
.Eof() )
2209 putchar(fsIn
.GetC());
2212 if ( !wxRemoveFile(filename
) )
2214 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2217 puts("\n*** wxFileInputStream test done ***");
2220 static void TestMemoryStream()
2222 puts("*** Testing wxMemoryInputStream ***");
2225 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2227 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2228 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2229 while ( !memInpStream
.Eof() )
2231 putchar(memInpStream
.GetC());
2234 puts("\n*** wxMemoryInputStream test done ***");
2237 #endif // TEST_STREAMS
2239 // ----------------------------------------------------------------------------
2241 // ----------------------------------------------------------------------------
2245 #include <wx/timer.h>
2246 #include <wx/utils.h>
2248 static void TestStopWatch()
2250 puts("*** Testing wxStopWatch ***\n");
2253 printf("Sleeping 3 seconds...");
2255 printf("\telapsed time: %ldms\n", sw
.Time());
2258 printf("Sleeping 2 more seconds...");
2260 printf("\telapsed time: %ldms\n", sw
.Time());
2263 printf("And 3 more seconds...");
2265 printf("\telapsed time: %ldms\n", sw
.Time());
2268 puts("\nChecking for 'backwards clock' bug...");
2269 for ( size_t n
= 0; n
< 70; n
++ )
2273 for ( size_t m
= 0; m
< 100000; m
++ )
2275 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2277 puts("\ntime is negative - ERROR!");
2287 #endif // TEST_TIMER
2289 // ----------------------------------------------------------------------------
2291 // ----------------------------------------------------------------------------
2295 #include <wx/vcard.h>
2297 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2300 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2304 wxString(_T('\t'), level
).c_str(),
2305 vcObj
->GetName().c_str());
2308 switch ( vcObj
->GetType() )
2310 case wxVCardObject::String
:
2311 case wxVCardObject::UString
:
2314 vcObj
->GetValue(&val
);
2315 value
<< _T('"') << val
<< _T('"');
2319 case wxVCardObject::Int
:
2322 vcObj
->GetValue(&i
);
2323 value
.Printf(_T("%u"), i
);
2327 case wxVCardObject::Long
:
2330 vcObj
->GetValue(&l
);
2331 value
.Printf(_T("%lu"), l
);
2335 case wxVCardObject::None
:
2338 case wxVCardObject::Object
:
2339 value
= _T("<node>");
2343 value
= _T("<unknown value type>");
2347 printf(" = %s", value
.c_str());
2350 DumpVObject(level
+ 1, *vcObj
);
2353 vcObj
= vcard
.GetNextProp(&cookie
);
2357 static void DumpVCardAddresses(const wxVCard
& vcard
)
2359 puts("\nShowing all addresses from vCard:\n");
2363 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2367 int flags
= addr
->GetFlags();
2368 if ( flags
& wxVCardAddress::Domestic
)
2370 flagsStr
<< _T("domestic ");
2372 if ( flags
& wxVCardAddress::Intl
)
2374 flagsStr
<< _T("international ");
2376 if ( flags
& wxVCardAddress::Postal
)
2378 flagsStr
<< _T("postal ");
2380 if ( flags
& wxVCardAddress::Parcel
)
2382 flagsStr
<< _T("parcel ");
2384 if ( flags
& wxVCardAddress::Home
)
2386 flagsStr
<< _T("home ");
2388 if ( flags
& wxVCardAddress::Work
)
2390 flagsStr
<< _T("work ");
2393 printf("Address %u:\n"
2395 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2398 addr
->GetPostOffice().c_str(),
2399 addr
->GetExtAddress().c_str(),
2400 addr
->GetStreet().c_str(),
2401 addr
->GetLocality().c_str(),
2402 addr
->GetRegion().c_str(),
2403 addr
->GetPostalCode().c_str(),
2404 addr
->GetCountry().c_str()
2408 addr
= vcard
.GetNextAddress(&cookie
);
2412 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2414 puts("\nShowing all phone numbers from vCard:\n");
2418 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2422 int flags
= phone
->GetFlags();
2423 if ( flags
& wxVCardPhoneNumber::Voice
)
2425 flagsStr
<< _T("voice ");
2427 if ( flags
& wxVCardPhoneNumber::Fax
)
2429 flagsStr
<< _T("fax ");
2431 if ( flags
& wxVCardPhoneNumber::Cellular
)
2433 flagsStr
<< _T("cellular ");
2435 if ( flags
& wxVCardPhoneNumber::Modem
)
2437 flagsStr
<< _T("modem ");
2439 if ( flags
& wxVCardPhoneNumber::Home
)
2441 flagsStr
<< _T("home ");
2443 if ( flags
& wxVCardPhoneNumber::Work
)
2445 flagsStr
<< _T("work ");
2448 printf("Phone number %u:\n"
2453 phone
->GetNumber().c_str()
2457 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2461 static void TestVCardRead()
2463 puts("*** Testing wxVCard reading ***\n");
2465 wxVCard
vcard(_T("vcard.vcf"));
2466 if ( !vcard
.IsOk() )
2468 puts("ERROR: couldn't load vCard.");
2472 // read individual vCard properties
2473 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2477 vcObj
->GetValue(&value
);
2482 value
= _T("<none>");
2485 printf("Full name retrieved directly: %s\n", value
.c_str());
2488 if ( !vcard
.GetFullName(&value
) )
2490 value
= _T("<none>");
2493 printf("Full name from wxVCard API: %s\n", value
.c_str());
2495 // now show how to deal with multiply occuring properties
2496 DumpVCardAddresses(vcard
);
2497 DumpVCardPhoneNumbers(vcard
);
2499 // and finally show all
2500 puts("\nNow dumping the entire vCard:\n"
2501 "-----------------------------\n");
2503 DumpVObject(0, vcard
);
2507 static void TestVCardWrite()
2509 puts("*** Testing wxVCard writing ***\n");
2512 if ( !vcard
.IsOk() )
2514 puts("ERROR: couldn't create vCard.");
2519 vcard
.SetName("Zeitlin", "Vadim");
2520 vcard
.SetFullName("Vadim Zeitlin");
2521 vcard
.SetOrganization("wxWindows", "R&D");
2523 // just dump the vCard back
2524 puts("Entire vCard follows:\n");
2525 puts(vcard
.Write());
2529 #endif // TEST_VCARD
2531 // ----------------------------------------------------------------------------
2532 // wide char (Unicode) support
2533 // ----------------------------------------------------------------------------
2537 #include <wx/strconv.h>
2538 #include <wx/fontenc.h>
2539 #include <wx/encconv.h>
2540 #include <wx/buffer.h>
2542 static void TestUtf8()
2544 puts("*** Testing UTF8 support ***\n");
2546 static const char textInUtf8
[] =
2548 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2549 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2550 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2551 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2552 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2553 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2554 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2559 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2561 puts("ERROR: UTF-8 decoding failed.");
2565 // using wxEncodingConverter
2567 wxEncodingConverter ec
;
2568 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2569 ec
.Convert(wbuf
, buf
);
2570 #else // using wxCSConv
2571 wxCSConv
conv(_T("koi8-r"));
2572 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2574 puts("ERROR: conversion to KOI8-R failed.");
2579 printf("The resulting string (in koi8-r): %s\n", buf
);
2583 #endif // TEST_WCHAR
2585 // ----------------------------------------------------------------------------
2587 // ----------------------------------------------------------------------------
2591 #include "wx/filesys.h"
2592 #include "wx/fs_zip.h"
2593 #include "wx/zipstrm.h"
2595 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
2597 static void TestZipStreamRead()
2599 puts("*** Testing ZIP reading ***\n");
2601 static const wxChar
*filename
= _T("foo");
2602 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
2603 printf("Archive size: %u\n", istr
.GetSize());
2605 printf("Dumping the file '%s':\n", filename
);
2606 while ( !istr
.Eof() )
2608 putchar(istr
.GetC());
2612 puts("\n----- done ------");
2615 static void DumpZipDirectory(wxFileSystem
& fs
,
2616 const wxString
& dir
,
2617 const wxString
& indent
)
2619 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
2620 TESTFILE_ZIP
, dir
.c_str());
2621 wxString wildcard
= prefix
+ _T("/*");
2623 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
2624 while ( !dirname
.empty() )
2626 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
2628 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2633 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
2635 DumpZipDirectory(fs
, dirname
,
2636 indent
+ wxString(_T(' '), 4));
2638 dirname
= fs
.FindNext();
2641 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
2642 while ( !filename
.empty() )
2644 if ( !filename
.StartsWith(prefix
, &filename
) )
2646 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2651 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
2653 filename
= fs
.FindNext();
2657 static void TestZipFileSystem()
2659 puts("*** Testing ZIP file system ***\n");
2661 wxFileSystem::AddHandler(new wxZipFSHandler
);
2663 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
2665 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
2670 // ----------------------------------------------------------------------------
2672 // ----------------------------------------------------------------------------
2676 #include <wx/zstream.h>
2677 #include <wx/wfstream.h>
2679 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2680 static const char *TEST_DATA
= "hello and hello again";
2682 static void TestZlibStreamWrite()
2684 puts("*** Testing Zlib stream reading ***\n");
2686 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2687 wxZlibOutputStream
ostr(fileOutStream
, 0);
2688 printf("Compressing the test string... ");
2689 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2692 puts("(ERROR: failed)");
2699 puts("\n----- done ------");
2702 static void TestZlibStreamRead()
2704 puts("*** Testing Zlib stream reading ***\n");
2706 wxFileInputStream
fileInStream(FILENAME_GZ
);
2707 wxZlibInputStream
istr(fileInStream
);
2708 printf("Archive size: %u\n", istr
.GetSize());
2710 puts("Dumping the file:");
2711 while ( !istr
.Eof() )
2713 putchar(istr
.GetC());
2717 puts("\n----- done ------");
2722 // ----------------------------------------------------------------------------
2724 // ----------------------------------------------------------------------------
2726 #ifdef TEST_DATETIME
2728 #include <wx/date.h>
2730 #include <wx/datetime.h>
2735 wxDateTime::wxDateTime_t day
;
2736 wxDateTime::Month month
;
2738 wxDateTime::wxDateTime_t hour
, min
, sec
;
2740 wxDateTime::WeekDay wday
;
2741 time_t gmticks
, ticks
;
2743 void Init(const wxDateTime::Tm
& tm
)
2752 gmticks
= ticks
= -1;
2755 wxDateTime
DT() const
2756 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2758 bool SameDay(const wxDateTime::Tm
& tm
) const
2760 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2763 wxString
Format() const
2766 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2768 wxDateTime::GetMonthName(month
).c_str(),
2770 abs(wxDateTime::ConvertYearToBC(year
)),
2771 year
> 0 ? "AD" : "BC");
2775 wxString
FormatDate() const
2778 s
.Printf("%02d-%s-%4d%s",
2780 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2781 abs(wxDateTime::ConvertYearToBC(year
)),
2782 year
> 0 ? "AD" : "BC");
2787 static const Date testDates
[] =
2789 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2790 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2791 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2792 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2793 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2794 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2795 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2796 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2797 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2798 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2799 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2800 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2801 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2802 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2803 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2806 // this test miscellaneous static wxDateTime functions
2807 static void TestTimeStatic()
2809 puts("\n*** wxDateTime static methods test ***");
2811 // some info about the current date
2812 int year
= wxDateTime::GetCurrentYear();
2813 printf("Current year %d is %sa leap one and has %d days.\n",
2815 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2816 wxDateTime::GetNumberOfDays(year
));
2818 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2819 printf("Current month is '%s' ('%s') and it has %d days\n",
2820 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2821 wxDateTime::GetMonthName(month
).c_str(),
2822 wxDateTime::GetNumberOfDays(month
));
2825 static const size_t nYears
= 5;
2826 static const size_t years
[2][nYears
] =
2828 // first line: the years to test
2829 { 1990, 1976, 2000, 2030, 1984, },
2831 // second line: TRUE if leap, FALSE otherwise
2832 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2835 for ( size_t n
= 0; n
< nYears
; n
++ )
2837 int year
= years
[0][n
];
2838 bool should
= years
[1][n
] != 0,
2839 is
= wxDateTime::IsLeapYear(year
);
2841 printf("Year %d is %sa leap year (%s)\n",
2844 should
== is
? "ok" : "ERROR");
2846 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2850 // test constructing wxDateTime objects
2851 static void TestTimeSet()
2853 puts("\n*** wxDateTime construction test ***");
2855 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2857 const Date
& d1
= testDates
[n
];
2858 wxDateTime dt
= d1
.DT();
2861 d2
.Init(dt
.GetTm());
2863 wxString s1
= d1
.Format(),
2866 printf("Date: %s == %s (%s)\n",
2867 s1
.c_str(), s2
.c_str(),
2868 s1
== s2
? "ok" : "ERROR");
2872 // test time zones stuff
2873 static void TestTimeZones()
2875 puts("\n*** wxDateTime timezone test ***");
2877 wxDateTime now
= wxDateTime::Now();
2879 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2880 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2881 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2882 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2883 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2884 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2886 wxDateTime::Tm tm
= now
.GetTm();
2887 if ( wxDateTime(tm
) != now
)
2889 printf("ERROR: got %s instead of %s\n",
2890 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2894 // test some minimal support for the dates outside the standard range
2895 static void TestTimeRange()
2897 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2899 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
2901 printf("Unix epoch:\t%s\n",
2902 wxDateTime(2440587.5).Format(fmt
).c_str());
2903 printf("Feb 29, 0: \t%s\n",
2904 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
2905 printf("JDN 0: \t%s\n",
2906 wxDateTime(0.0).Format(fmt
).c_str());
2907 printf("Jan 1, 1AD:\t%s\n",
2908 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
2909 printf("May 29, 2099:\t%s\n",
2910 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
2913 static void TestTimeTicks()
2915 puts("\n*** wxDateTime ticks test ***");
2917 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2919 const Date
& d
= testDates
[n
];
2920 if ( d
.ticks
== -1 )
2923 wxDateTime dt
= d
.DT();
2924 long ticks
= (dt
.GetValue() / 1000).ToLong();
2925 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2926 if ( ticks
== d
.ticks
)
2932 printf(" (ERROR: should be %ld, delta = %ld)\n",
2933 d
.ticks
, ticks
- d
.ticks
);
2936 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
2937 ticks
= (dt
.GetValue() / 1000).ToLong();
2938 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2939 if ( ticks
== d
.gmticks
)
2945 printf(" (ERROR: should be %ld, delta = %ld)\n",
2946 d
.gmticks
, ticks
- d
.gmticks
);
2953 // test conversions to JDN &c
2954 static void TestTimeJDN()
2956 puts("\n*** wxDateTime to JDN test ***");
2958 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2960 const Date
& d
= testDates
[n
];
2961 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2962 double jdn
= dt
.GetJulianDayNumber();
2964 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
2971 printf(" (ERROR: should be %f, delta = %f)\n",
2972 d
.jdn
, jdn
- d
.jdn
);
2977 // test week days computation
2978 static void TestTimeWDays()
2980 puts("\n*** wxDateTime weekday test ***");
2982 // test GetWeekDay()
2984 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2986 const Date
& d
= testDates
[n
];
2987 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2989 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
2992 wxDateTime::GetWeekDayName(wday
).c_str());
2993 if ( wday
== d
.wday
)
2999 printf(" (ERROR: should be %s)\n",
3000 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3006 // test SetToWeekDay()
3007 struct WeekDateTestData
3009 Date date
; // the real date (precomputed)
3010 int nWeek
; // its week index in the month
3011 wxDateTime::WeekDay wday
; // the weekday
3012 wxDateTime::Month month
; // the month
3013 int year
; // and the year
3015 wxString
Format() const
3018 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3020 case 1: which
= "first"; break;
3021 case 2: which
= "second"; break;
3022 case 3: which
= "third"; break;
3023 case 4: which
= "fourth"; break;
3024 case 5: which
= "fifth"; break;
3026 case -1: which
= "last"; break;
3031 which
+= " from end";
3034 s
.Printf("The %s %s of %s in %d",
3036 wxDateTime::GetWeekDayName(wday
).c_str(),
3037 wxDateTime::GetMonthName(month
).c_str(),
3044 // the array data was generated by the following python program
3046 from DateTime import *
3047 from whrandom import *
3048 from string import *
3050 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3051 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3053 week = DateTimeDelta(7)
3056 year = randint(1900, 2100)
3057 month = randint(1, 12)
3058 day = randint(1, 28)
3059 dt = DateTime(year, month, day)
3060 wday = dt.day_of_week
3062 countFromEnd = choice([-1, 1])
3065 while dt.month is month:
3066 dt = dt - countFromEnd * week
3067 weekNum = weekNum + countFromEnd
3069 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3071 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3072 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3075 static const WeekDateTestData weekDatesTestData
[] =
3077 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3078 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3079 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3080 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3081 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3082 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3083 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3084 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3085 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3086 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3087 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3088 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3089 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3090 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3091 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3092 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3093 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3094 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3095 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3096 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3099 static const char *fmt
= "%d-%b-%Y";
3102 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3104 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3106 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3108 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3110 const Date
& d
= wd
.date
;
3111 if ( d
.SameDay(dt
.GetTm()) )
3117 dt
.Set(d
.day
, d
.month
, d
.year
);
3119 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3124 // test the computation of (ISO) week numbers
3125 static void TestTimeWNumber()
3127 puts("\n*** wxDateTime week number test ***");
3129 struct WeekNumberTestData
3131 Date date
; // the date
3132 wxDateTime::wxDateTime_t week
; // the week number in the year
3133 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3134 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3135 wxDateTime::wxDateTime_t dnum
; // day number in the year
3138 // data generated with the following python script:
3140 from DateTime import *
3141 from whrandom import *
3142 from string import *
3144 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3145 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3147 def GetMonthWeek(dt):
3148 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3149 if weekNumMonth < 0:
3150 weekNumMonth = weekNumMonth + 53
3153 def GetLastSundayBefore(dt):
3154 if dt.iso_week[2] == 7:
3157 return dt - DateTimeDelta(dt.iso_week[2])
3160 year = randint(1900, 2100)
3161 month = randint(1, 12)
3162 day = randint(1, 28)
3163 dt = DateTime(year, month, day)
3164 dayNum = dt.day_of_year
3165 weekNum = dt.iso_week[1]
3166 weekNumMonth = GetMonthWeek(dt)
3169 dtSunday = GetLastSundayBefore(dt)
3171 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3172 weekNumMonth2 = weekNumMonth2 + 1
3173 dtSunday = dtSunday - DateTimeDelta(7)
3175 data = { 'day': rjust(`day`, 2), \
3176 'month': monthNames[month - 1], \
3178 'weekNum': rjust(`weekNum`, 2), \
3179 'weekNumMonth': weekNumMonth, \
3180 'weekNumMonth2': weekNumMonth2, \
3181 'dayNum': rjust(`dayNum`, 3) }
3183 print " { { %(day)s, "\
3184 "wxDateTime::%(month)s, "\
3187 "%(weekNumMonth)s, "\
3188 "%(weekNumMonth2)s, "\
3189 "%(dayNum)s }," % data
3192 static const WeekNumberTestData weekNumberTestDates
[] =
3194 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3195 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3196 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3197 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3198 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3199 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3200 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3201 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3202 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3203 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3204 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3205 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3206 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3207 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3208 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3209 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3210 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3211 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3212 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3213 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3216 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3218 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3219 const Date
& d
= wn
.date
;
3221 wxDateTime dt
= d
.DT();
3223 wxDateTime::wxDateTime_t
3224 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3225 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3226 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3227 dnum
= dt
.GetDayOfYear();
3229 printf("%s: the day number is %d",
3230 d
.FormatDate().c_str(), dnum
);
3231 if ( dnum
== wn
.dnum
)
3237 printf(" (ERROR: should be %d)", wn
.dnum
);
3240 printf(", week in month is %d", wmon
);
3241 if ( wmon
== wn
.wmon
)
3247 printf(" (ERROR: should be %d)", wn
.wmon
);
3250 printf(" or %d", wmon2
);
3251 if ( wmon2
== wn
.wmon2
)
3257 printf(" (ERROR: should be %d)", wn
.wmon2
);
3260 printf(", week in year is %d", week
);
3261 if ( week
== wn
.week
)
3267 printf(" (ERROR: should be %d)\n", wn
.week
);
3272 // test DST calculations
3273 static void TestTimeDST()
3275 puts("\n*** wxDateTime DST test ***");
3277 printf("DST is%s in effect now.\n\n",
3278 wxDateTime::Now().IsDST() ? "" : " not");
3280 // taken from http://www.energy.ca.gov/daylightsaving.html
3281 static const Date datesDST
[2][2004 - 1900 + 1] =
3284 { 1, wxDateTime::Apr
, 1990 },
3285 { 7, wxDateTime::Apr
, 1991 },
3286 { 5, wxDateTime::Apr
, 1992 },
3287 { 4, wxDateTime::Apr
, 1993 },
3288 { 3, wxDateTime::Apr
, 1994 },
3289 { 2, wxDateTime::Apr
, 1995 },
3290 { 7, wxDateTime::Apr
, 1996 },
3291 { 6, wxDateTime::Apr
, 1997 },
3292 { 5, wxDateTime::Apr
, 1998 },
3293 { 4, wxDateTime::Apr
, 1999 },
3294 { 2, wxDateTime::Apr
, 2000 },
3295 { 1, wxDateTime::Apr
, 2001 },
3296 { 7, wxDateTime::Apr
, 2002 },
3297 { 6, wxDateTime::Apr
, 2003 },
3298 { 4, wxDateTime::Apr
, 2004 },
3301 { 28, wxDateTime::Oct
, 1990 },
3302 { 27, wxDateTime::Oct
, 1991 },
3303 { 25, wxDateTime::Oct
, 1992 },
3304 { 31, wxDateTime::Oct
, 1993 },
3305 { 30, wxDateTime::Oct
, 1994 },
3306 { 29, wxDateTime::Oct
, 1995 },
3307 { 27, wxDateTime::Oct
, 1996 },
3308 { 26, wxDateTime::Oct
, 1997 },
3309 { 25, wxDateTime::Oct
, 1998 },
3310 { 31, wxDateTime::Oct
, 1999 },
3311 { 29, wxDateTime::Oct
, 2000 },
3312 { 28, wxDateTime::Oct
, 2001 },
3313 { 27, wxDateTime::Oct
, 2002 },
3314 { 26, wxDateTime::Oct
, 2003 },
3315 { 31, wxDateTime::Oct
, 2004 },
3320 for ( year
= 1990; year
< 2005; year
++ )
3322 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3323 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3325 printf("DST period in the US for year %d: from %s to %s",
3326 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3328 size_t n
= year
- 1990;
3329 const Date
& dBegin
= datesDST
[0][n
];
3330 const Date
& dEnd
= datesDST
[1][n
];
3332 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3338 printf(" (ERROR: should be %s %d to %s %d)\n",
3339 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3340 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3346 for ( year
= 1990; year
< 2005; year
++ )
3348 printf("DST period in Europe for year %d: from %s to %s\n",
3350 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3351 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3355 // test wxDateTime -> text conversion
3356 static void TestTimeFormat()
3358 puts("\n*** wxDateTime formatting test ***");
3360 // some information may be lost during conversion, so store what kind
3361 // of info should we recover after a round trip
3364 CompareNone
, // don't try comparing
3365 CompareBoth
, // dates and times should be identical
3366 CompareDate
, // dates only
3367 CompareTime
// time only
3372 CompareKind compareKind
;
3374 } formatTestFormats
[] =
3376 { CompareBoth
, "---> %c" },
3377 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3378 { CompareBoth
, "Date is %x, time is %X" },
3379 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3380 { CompareNone
, "The day of year: %j, the week of year: %W" },
3381 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3384 static const Date formatTestDates
[] =
3386 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3387 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3389 // this test can't work for other centuries because it uses two digit
3390 // years in formats, so don't even try it
3391 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3392 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3393 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3397 // an extra test (as it doesn't depend on date, don't do it in the loop)
3398 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3400 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3404 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3405 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3407 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3408 printf("%s", s
.c_str());
3410 // what can we recover?
3411 int kind
= formatTestFormats
[n
].compareKind
;
3415 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3418 // converion failed - should it have?
3419 if ( kind
== CompareNone
)
3422 puts(" (ERROR: conversion back failed)");
3426 // should have parsed the entire string
3427 puts(" (ERROR: conversion back stopped too soon)");
3431 bool equal
= FALSE
; // suppress compilaer warning
3439 equal
= dt
.IsSameDate(dt2
);
3443 equal
= dt
.IsSameTime(dt2
);
3449 printf(" (ERROR: got back '%s' instead of '%s')\n",
3450 dt2
.Format().c_str(), dt
.Format().c_str());
3461 // test text -> wxDateTime conversion
3462 static void TestTimeParse()
3464 puts("\n*** wxDateTime parse test ***");
3466 struct ParseTestData
3473 static const ParseTestData parseTestDates
[] =
3475 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3476 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3479 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3481 const char *format
= parseTestDates
[n
].format
;
3483 printf("%s => ", format
);
3486 if ( dt
.ParseRfc822Date(format
) )
3488 printf("%s ", dt
.Format().c_str());
3490 if ( parseTestDates
[n
].good
)
3492 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3499 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3504 puts("(ERROR: bad format)");
3509 printf("bad format (%s)\n",
3510 parseTestDates
[n
].good
? "ERROR" : "ok");
3515 static void TestDateTimeInteractive()
3517 puts("\n*** interactive wxDateTime tests ***");
3523 printf("Enter a date: ");
3524 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3527 // kill the last '\n'
3528 buf
[strlen(buf
) - 1] = 0;
3531 const char *p
= dt
.ParseDate(buf
);
3534 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3540 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3543 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3544 dt
.Format("%b %d, %Y").c_str(),
3546 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3547 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3548 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3551 puts("\n*** done ***");
3554 static void TestTimeMS()
3556 puts("*** testing millisecond-resolution support in wxDateTime ***");
3558 wxDateTime dt1
= wxDateTime::Now(),
3559 dt2
= wxDateTime::UNow();
3561 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3562 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3563 printf("Dummy loop: ");
3564 for ( int i
= 0; i
< 6000; i
++ )
3566 //for ( int j = 0; j < 10; j++ )
3569 s
.Printf("%g", sqrt(i
));
3578 dt2
= wxDateTime::UNow();
3579 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3581 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3583 puts("\n*** done ***");
3586 static void TestTimeArithmetics()
3588 puts("\n*** testing arithmetic operations on wxDateTime ***");
3590 static const struct ArithmData
3592 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3593 : span(sp
), name(nam
) { }
3597 } testArithmData
[] =
3599 ArithmData(wxDateSpan::Day(), "day"),
3600 ArithmData(wxDateSpan::Week(), "week"),
3601 ArithmData(wxDateSpan::Month(), "month"),
3602 ArithmData(wxDateSpan::Year(), "year"),
3603 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3606 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3608 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3610 wxDateSpan span
= testArithmData
[n
].span
;
3614 const char *name
= testArithmData
[n
].name
;
3615 printf("%s + %s = %s, %s - %s = %s\n",
3616 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3617 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3619 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3620 if ( dt1
- span
== dt
)
3626 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3629 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3630 if ( dt2
+ span
== dt
)
3636 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3639 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3640 if ( dt2
+ 2*span
== dt1
)
3646 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3653 static void TestTimeHolidays()
3655 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3657 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3658 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3659 dtEnd
= dtStart
.GetLastMonthDay();
3661 wxDateTimeArray hol
;
3662 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3664 const wxChar
*format
= "%d-%b-%Y (%a)";
3666 printf("All holidays between %s and %s:\n",
3667 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3669 size_t count
= hol
.GetCount();
3670 for ( size_t n
= 0; n
< count
; n
++ )
3672 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3678 static void TestTimeZoneBug()
3680 puts("\n*** testing for DST/timezone bug ***\n");
3682 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3683 for ( int i
= 0; i
< 31; i
++ )
3685 printf("Date %s: week day %s.\n",
3686 date
.Format(_T("%d-%m-%Y")).c_str(),
3687 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3689 date
+= wxDateSpan::Day();
3695 static void TestTimeSpanFormat()
3697 puts("\n*** wxTimeSpan tests ***");
3699 static const char *formats
[] =
3701 _T("(default) %H:%M:%S"),
3702 _T("%E weeks and %D days"),
3703 _T("%l milliseconds"),
3704 _T("(with ms) %H:%M:%S:%l"),
3705 _T("100%% of minutes is %M"), // test "%%"
3706 _T("%D days and %H hours"),
3709 wxTimeSpan
ts1(1, 2, 3, 4),
3711 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3713 printf("ts1 = %s\tts2 = %s\n",
3714 ts1
.Format(formats
[n
]).c_str(),
3715 ts2
.Format(formats
[n
]).c_str());
3723 // test compatibility with the old wxDate/wxTime classes
3724 static void TestTimeCompatibility()
3726 puts("\n*** wxDateTime compatibility test ***");
3728 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3729 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3731 double jdnNow
= wxDateTime::Now().GetJDN();
3732 long jdnMidnight
= (long)(jdnNow
- 0.5);
3733 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3735 jdnMidnight
= wxDate().Set().GetJulianDate();
3736 printf("wxDateTime for today: %s\n",
3737 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3739 int flags
= wxEUROPEAN
;//wxFULL;
3742 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3743 for ( int n
= 0; n
< 7; n
++ )
3745 printf("Previous %s is %s\n",
3746 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3747 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3753 #endif // TEST_DATETIME
3755 // ----------------------------------------------------------------------------
3757 // ----------------------------------------------------------------------------
3761 #include <wx/thread.h>
3763 static size_t gs_counter
= (size_t)-1;
3764 static wxCriticalSection gs_critsect
;
3765 static wxCondition gs_cond
;
3767 class MyJoinableThread
: public wxThread
3770 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3771 { m_n
= n
; Create(); }
3773 // thread execution starts here
3774 virtual ExitCode
Entry();
3780 wxThread::ExitCode
MyJoinableThread::Entry()
3782 unsigned long res
= 1;
3783 for ( size_t n
= 1; n
< m_n
; n
++ )
3787 // it's a loooong calculation :-)
3791 return (ExitCode
)res
;
3794 class MyDetachedThread
: public wxThread
3797 MyDetachedThread(size_t n
, char ch
)
3801 m_cancelled
= FALSE
;
3806 // thread execution starts here
3807 virtual ExitCode
Entry();
3810 virtual void OnExit();
3813 size_t m_n
; // number of characters to write
3814 char m_ch
; // character to write
3816 bool m_cancelled
; // FALSE if we exit normally
3819 wxThread::ExitCode
MyDetachedThread::Entry()
3822 wxCriticalSectionLocker
lock(gs_critsect
);
3823 if ( gs_counter
== (size_t)-1 )
3829 for ( size_t n
= 0; n
< m_n
; n
++ )
3831 if ( TestDestroy() )
3841 wxThread::Sleep(100);
3847 void MyDetachedThread::OnExit()
3849 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3851 wxCriticalSectionLocker
lock(gs_critsect
);
3852 if ( !--gs_counter
&& !m_cancelled
)
3856 void TestDetachedThreads()
3858 puts("\n*** Testing detached threads ***");
3860 static const size_t nThreads
= 3;
3861 MyDetachedThread
*threads
[nThreads
];
3863 for ( n
= 0; n
< nThreads
; n
++ )
3865 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3868 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3869 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3871 for ( n
= 0; n
< nThreads
; n
++ )
3876 // wait until all threads terminate
3882 void TestJoinableThreads()
3884 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3886 // calc 10! in the background
3887 MyJoinableThread
thread(10);
3890 printf("\nThread terminated with exit code %lu.\n",
3891 (unsigned long)thread
.Wait());
3894 void TestThreadSuspend()
3896 puts("\n*** Testing thread suspend/resume functions ***");
3898 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3902 // this is for this demo only, in a real life program we'd use another
3903 // condition variable which would be signaled from wxThread::Entry() to
3904 // tell us that the thread really started running - but here just wait a
3905 // bit and hope that it will be enough (the problem is, of course, that
3906 // the thread might still not run when we call Pause() which will result
3908 wxThread::Sleep(300);
3910 for ( size_t n
= 0; n
< 3; n
++ )
3914 puts("\nThread suspended");
3917 // don't sleep but resume immediately the first time
3918 wxThread::Sleep(300);
3920 puts("Going to resume the thread");
3925 puts("Waiting until it terminates now");
3927 // wait until the thread terminates
3933 void TestThreadDelete()
3935 // As above, using Sleep() is only for testing here - we must use some
3936 // synchronisation object instead to ensure that the thread is still
3937 // running when we delete it - deleting a detached thread which already
3938 // terminated will lead to a crash!
3940 puts("\n*** Testing thread delete function ***");
3942 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3946 puts("\nDeleted a thread which didn't start to run yet.");
3948 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3952 wxThread::Sleep(300);
3956 puts("\nDeleted a running thread.");
3958 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3962 wxThread::Sleep(300);
3968 puts("\nDeleted a sleeping thread.");
3970 MyJoinableThread
thread3(20);
3975 puts("\nDeleted a joinable thread.");
3977 MyJoinableThread
thread4(2);
3980 wxThread::Sleep(300);
3984 puts("\nDeleted a joinable thread which already terminated.");
3989 #endif // TEST_THREADS
3991 // ----------------------------------------------------------------------------
3993 // ----------------------------------------------------------------------------
3997 static void PrintArray(const char* name
, const wxArrayString
& array
)
3999 printf("Dump of the array '%s'\n", name
);
4001 size_t nCount
= array
.GetCount();
4002 for ( size_t n
= 0; n
< nCount
; n
++ )
4004 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4008 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4010 printf("Dump of the array '%s'\n", name
);
4012 size_t nCount
= array
.GetCount();
4013 for ( size_t n
= 0; n
< nCount
; n
++ )
4015 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4019 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4020 const wxString
& second
)
4022 return first
.length() - second
.length();
4025 int wxCMPFUNC_CONV
IntCompare(int *first
,
4028 return *first
- *second
;
4031 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4034 return *second
- *first
;
4037 static void TestArrayOfInts()
4039 puts("*** Testing wxArrayInt ***\n");
4050 puts("After sort:");
4054 puts("After reverse sort:");
4055 a
.Sort(IntRevCompare
);
4059 #include "wx/dynarray.h"
4061 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4062 #include "wx/arrimpl.cpp"
4063 WX_DEFINE_OBJARRAY(ArrayBars
);
4065 static void TestArrayOfObjects()
4067 puts("*** Testing wxObjArray ***\n");
4071 Bar
bar("second bar");
4073 printf("Initially: %u objects in the array, %u objects total.\n",
4074 bars
.GetCount(), Bar::GetNumber());
4076 bars
.Add(new Bar("first bar"));
4079 printf("Now: %u objects in the array, %u objects total.\n",
4080 bars
.GetCount(), Bar::GetNumber());
4084 printf("After Empty(): %u objects in the array, %u objects total.\n",
4085 bars
.GetCount(), Bar::GetNumber());
4088 printf("Finally: no more objects in the array, %u objects total.\n",
4092 #endif // TEST_ARRAYS
4094 // ----------------------------------------------------------------------------
4096 // ----------------------------------------------------------------------------
4100 #include "wx/timer.h"
4101 #include "wx/tokenzr.h"
4103 static void TestStringConstruction()
4105 puts("*** Testing wxString constructores ***");
4107 #define TEST_CTOR(args, res) \
4110 printf("wxString%s = %s ", #args, s.c_str()); \
4117 printf("(ERROR: should be %s)\n", res); \
4121 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4122 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4123 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4124 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4126 static const wxChar
*s
= _T("?really!");
4127 const wxChar
*start
= wxStrchr(s
, _T('r'));
4128 const wxChar
*end
= wxStrchr(s
, _T('!'));
4129 TEST_CTOR((start
, end
), _T("really"));
4134 static void TestString()
4144 for (int i
= 0; i
< 1000000; ++i
)
4148 c
= "! How'ya doin'?";
4151 c
= "Hello world! What's up?";
4156 printf ("TestString elapsed time: %ld\n", sw
.Time());
4159 static void TestPChar()
4167 for (int i
= 0; i
< 1000000; ++i
)
4169 strcpy (a
, "Hello");
4170 strcpy (b
, " world");
4171 strcpy (c
, "! How'ya doin'?");
4174 strcpy (c
, "Hello world! What's up?");
4175 if (strcmp (c
, a
) == 0)
4179 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4182 static void TestStringSub()
4184 wxString
s("Hello, world!");
4186 puts("*** Testing wxString substring extraction ***");
4188 printf("String = '%s'\n", s
.c_str());
4189 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4190 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4191 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4192 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4193 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4194 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4196 static const wxChar
*prefixes
[] =
4200 _T("Hello, world!"),
4201 _T("Hello, world!!!"),
4207 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4209 wxString prefix
= prefixes
[n
], rest
;
4210 bool rc
= s
.StartsWith(prefix
, &rest
);
4211 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4214 printf(" (the rest is '%s')\n", rest
.c_str());
4225 static void TestStringFormat()
4227 puts("*** Testing wxString formatting ***");
4230 s
.Printf("%03d", 18);
4232 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4233 printf("Number 18: %s\n", s
.c_str());
4238 // returns "not found" for npos, value for all others
4239 static wxString
PosToString(size_t res
)
4241 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4242 : wxString::Format(_T("%u"), res
);
4246 static void TestStringFind()
4248 puts("*** Testing wxString find() functions ***");
4250 static const wxChar
*strToFind
= _T("ell");
4251 static const struct StringFindTest
4255 result
; // of searching "ell" in str
4258 { _T("Well, hello world"), 0, 1 },
4259 { _T("Well, hello world"), 6, 7 },
4260 { _T("Well, hello world"), 9, wxString::npos
},
4263 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4265 const StringFindTest
& ft
= findTestData
[n
];
4266 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4268 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4269 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4271 size_t resTrue
= ft
.result
;
4272 if ( res
== resTrue
)
4278 printf(_T("(ERROR: should be %s)\n"),
4279 PosToString(resTrue
).c_str());
4286 static void TestStringTokenizer()
4288 puts("*** Testing wxStringTokenizer ***");
4290 static const wxChar
*modeNames
[] =
4294 _T("return all empty"),
4299 static const struct StringTokenizerTest
4301 const wxChar
*str
; // string to tokenize
4302 const wxChar
*delims
; // delimiters to use
4303 size_t count
; // count of token
4304 wxStringTokenizerMode mode
; // how should we tokenize it
4305 } tokenizerTestData
[] =
4307 { _T(""), _T(" "), 0 },
4308 { _T("Hello, world"), _T(" "), 2 },
4309 { _T("Hello, world "), _T(" "), 2 },
4310 { _T("Hello, world"), _T(","), 2 },
4311 { _T("Hello, world!"), _T(",!"), 2 },
4312 { _T("Hello,, world!"), _T(",!"), 3 },
4313 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4314 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4315 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4316 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4317 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4318 { _T("01/02/99"), _T("/-"), 3 },
4319 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4322 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4324 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4325 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4327 size_t count
= tkz
.CountTokens();
4328 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4329 MakePrintable(tt
.str
).c_str(),
4331 MakePrintable(tt
.delims
).c_str(),
4332 modeNames
[tkz
.GetMode()]);
4333 if ( count
== tt
.count
)
4339 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4344 // if we emulate strtok(), check that we do it correctly
4345 wxChar
*buf
, *s
= NULL
, *last
;
4347 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4349 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4350 wxStrcpy(buf
, tt
.str
);
4352 s
= wxStrtok(buf
, tt
.delims
, &last
);
4359 // now show the tokens themselves
4361 while ( tkz
.HasMoreTokens() )
4363 wxString token
= tkz
.GetNextToken();
4365 printf(_T("\ttoken %u: '%s'"),
4367 MakePrintable(token
).c_str());
4377 printf(" (ERROR: should be %s)\n", s
);
4380 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4384 // nothing to compare with
4389 if ( count2
!= count
)
4391 puts(_T("\tERROR: token count mismatch"));
4400 static void TestStringReplace()
4402 puts("*** Testing wxString::replace ***");
4404 static const struct StringReplaceTestData
4406 const wxChar
*original
; // original test string
4407 size_t start
, len
; // the part to replace
4408 const wxChar
*replacement
; // the replacement string
4409 const wxChar
*result
; // and the expected result
4410 } stringReplaceTestData
[] =
4412 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4413 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4414 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4415 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4416 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4419 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4421 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4423 wxString original
= data
.original
;
4424 original
.replace(data
.start
, data
.len
, data
.replacement
);
4426 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4427 data
.original
, data
.start
, data
.len
, data
.replacement
,
4430 if ( original
== data
.result
)
4436 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4443 #endif // TEST_STRINGS
4445 // ----------------------------------------------------------------------------
4447 // ----------------------------------------------------------------------------
4449 int main(int argc
, char **argv
)
4451 if ( !wxInitialize() )
4453 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4457 puts("Sleeping for 3 seconds... z-z-z-z-z...");
4459 #endif // TEST_USLEEP
4462 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4464 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4465 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4467 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4468 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4469 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
4470 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
4472 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4473 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4478 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4480 parser
.AddOption("project_name", "", "full path to project file",
4481 wxCMD_LINE_VAL_STRING
,
4482 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4484 switch ( parser
.Parse() )
4487 wxLogMessage("Help was given, terminating.");
4491 ShowCmdLine(parser
);
4495 wxLogMessage("Syntax error detected, aborting.");
4498 #endif // TEST_CMDLINE
4509 TestStringConstruction();
4512 TestStringTokenizer();
4513 TestStringReplace();
4515 #endif // TEST_STRINGS
4528 puts("*** Initially:");
4530 PrintArray("a1", a1
);
4532 wxArrayString
a2(a1
);
4533 PrintArray("a2", a2
);
4535 wxSortedArrayString
a3(a1
);
4536 PrintArray("a3", a3
);
4538 puts("*** After deleting a string from a1");
4541 PrintArray("a1", a1
);
4542 PrintArray("a2", a2
);
4543 PrintArray("a3", a3
);
4545 puts("*** After reassigning a1 to a2 and a3");
4547 PrintArray("a2", a2
);
4548 PrintArray("a3", a3
);
4550 puts("*** After sorting a1");
4552 PrintArray("a1", a1
);
4554 puts("*** After sorting a1 in reverse order");
4556 PrintArray("a1", a1
);
4558 puts("*** After sorting a1 by the string length");
4559 a1
.Sort(StringLenCompare
);
4560 PrintArray("a1", a1
);
4562 TestArrayOfObjects();
4565 #endif // TEST_ARRAYS
4571 #ifdef TEST_DLLLOADER
4573 #endif // TEST_DLLLOADER
4577 #endif // TEST_ENVIRON
4581 #endif // TEST_EXECUTE
4583 #ifdef TEST_FILECONF
4585 #endif // TEST_FILECONF
4593 #endif // TEST_LOCALE
4597 for ( size_t n
= 0; n
< 8000; n
++ )
4599 s
<< (char)('A' + (n
% 26));
4603 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4605 // this one shouldn't be truncated
4608 // but this one will because log functions use fixed size buffer
4609 // (note that it doesn't need '\n' at the end neither - will be added
4611 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4623 #ifdef TEST_FILENAME
4624 TestFileNameSplit();
4627 TestFileNameConstruction();
4629 TestFileNameComparison();
4630 TestFileNameOperations();
4632 #endif // TEST_FILENAME
4635 int nCPUs
= wxThread::GetCPUCount();
4636 printf("This system has %d CPUs\n", nCPUs
);
4638 wxThread::SetConcurrency(nCPUs
);
4640 if ( argc
> 1 && argv
[1][0] == 't' )
4641 wxLog::AddTraceMask("thread");
4644 TestDetachedThreads();
4646 TestJoinableThreads();
4648 TestThreadSuspend();
4652 #endif // TEST_THREADS
4654 #ifdef TEST_LONGLONG
4655 // seed pseudo random generator
4656 srand((unsigned)time(NULL
));
4664 TestMultiplication();
4667 TestLongLongConversion();
4668 TestBitOperations();
4670 TestLongLongComparison();
4671 #endif // TEST_LONGLONG
4678 wxLog::AddTraceMask(_T("mime"));
4686 TestMimeAssociate();
4689 #ifdef TEST_INFO_FUNCTIONS
4692 #endif // TEST_INFO_FUNCTIONS
4694 #ifdef TEST_PATHLIST
4696 #endif // TEST_PATHLIST
4700 #endif // TEST_REGCONF
4702 #ifdef TEST_REGISTRY
4705 TestRegistryAssociation();
4706 #endif // TEST_REGISTRY
4714 #endif // TEST_SOCKETS
4717 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4718 if ( TestFtpConnect() )
4729 TestFtpInteractive();
4731 //else: connecting to the FTP server failed
4741 #endif // TEST_STREAMS
4745 #endif // TEST_TIMER
4747 #ifdef TEST_DATETIME
4760 TestTimeArithmetics();
4767 TestTimeSpanFormat();
4769 TestDateTimeInteractive();
4770 #endif // TEST_DATETIME
4776 #endif // TEST_VCARD
4780 #endif // TEST_WCHAR
4784 TestZipStreamRead();
4785 TestZipFileSystem();
4790 TestZlibStreamWrite();
4791 TestZlibStreamRead();