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 // ----------------------------------------------------------------------------
27 // conditional compilation
28 // ----------------------------------------------------------------------------
33 //#define TEST_CMDLINE
36 //#define TEST_FILECONF
39 //#define TEST_LONGLONG
41 //#define TEST_SOCKETS
42 //#define TEST_STRINGS
43 //#define TEST_THREADS
46 // ============================================================================
48 // ============================================================================
52 // ----------------------------------------------------------------------------
54 // ----------------------------------------------------------------------------
56 #include <wx/cmdline.h>
57 #include <wx/datetime.h>
59 static void ShowCmdLine(const wxCmdLineParser
& parser
)
61 wxString s
= "Input files: ";
63 size_t count
= parser
.GetParamCount();
64 for ( size_t param
= 0; param
< count
; param
++ )
66 s
<< parser
.GetParam(param
) << ' ';
70 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
71 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
76 if ( parser
.Found("o", &strVal
) )
77 s
<< "Output file:\t" << strVal
<< '\n';
78 if ( parser
.Found("i", &strVal
) )
79 s
<< "Input dir:\t" << strVal
<< '\n';
80 if ( parser
.Found("s", &lVal
) )
81 s
<< "Size:\t" << lVal
<< '\n';
82 if ( parser
.Found("d", &dt
) )
83 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
88 #endif // TEST_CMDLINE
90 // ----------------------------------------------------------------------------
92 // ----------------------------------------------------------------------------
98 static void TestDirEnumHelper(wxDir
& dir
,
99 int flags
= wxDIR_DEFAULT
,
100 const wxString
& filespec
= wxEmptyString
)
104 if ( !dir
.IsOpened() )
107 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
110 printf("\t%s\n", filename
.c_str());
112 cont
= dir
.GetNext(&filename
);
118 static void TestDirEnum()
120 wxDir
dir(wxGetCwd());
122 puts("Enumerating everything in current directory:");
123 TestDirEnumHelper(dir
);
125 puts("Enumerating really everything in current directory:");
126 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
128 puts("Enumerating object files in current directory:");
129 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
131 puts("Enumerating directories in current directory:");
132 TestDirEnumHelper(dir
, wxDIR_DIRS
);
134 puts("Enumerating files in current directory:");
135 TestDirEnumHelper(dir
, wxDIR_FILES
);
137 puts("Enumerating files including hidden in current directory:");
138 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
142 #elif defined(__WXMSW__)
145 #error "don't know where the root directory is"
148 puts("Enumerating everything in root directory:");
149 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
151 puts("Enumerating directories in root directory:");
152 TestDirEnumHelper(dir
, wxDIR_DIRS
);
154 puts("Enumerating files in root directory:");
155 TestDirEnumHelper(dir
, wxDIR_FILES
);
157 puts("Enumerating files including hidden in root directory:");
158 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
160 puts("Enumerating files in non existing directory:");
161 wxDir
dirNo("nosuchdir");
162 TestDirEnumHelper(dirNo
);
167 // ----------------------------------------------------------------------------
169 // ----------------------------------------------------------------------------
173 #include <wx/utils.h>
175 static void TestExecute()
177 puts("*** testing wxExecute ***");
180 #define COMMAND "echo hi"
181 #define SHELL_COMMAND "echo hi from shell"
182 #define REDIRECT_COMMAND "date"
183 #elif defined(__WXMSW__)
184 #define COMMAND "command.com -c 'echo hi'"
185 #define SHELL_COMMAND "echo hi"
186 #define REDIRECT_COMMAND COMMAND
188 #error "no command to exec"
191 printf("Testing wxShell: ");
193 if ( wxShell(SHELL_COMMAND
) )
198 printf("Testing wxExecute: ");
200 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
205 #if 0 // no, it doesn't work (yet?)
206 printf("Testing async wxExecute: ");
208 if ( wxExecute(COMMAND
) != 0 )
209 puts("Ok (command launched).");
214 printf("Testing wxExecute with redirection:\n");
215 wxArrayString output
;
216 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
222 size_t count
= output
.GetCount();
223 for ( size_t n
= 0; n
< count
; n
++ )
225 printf("\t%s\n", output
[n
].c_str());
232 #endif // TEST_EXECUTE
234 // ----------------------------------------------------------------------------
236 // ----------------------------------------------------------------------------
240 #include <wx/confbase.h>
241 #include <wx/fileconf.h>
243 static const struct FileConfTestData
245 const wxChar
*name
; // value name
246 const wxChar
*value
; // the value from the file
249 { _T("value1"), _T("one") },
250 { _T("value2"), _T("two") },
251 { _T("novalue"), _T("default") },
254 static void TestFileConfRead()
256 puts("*** testing wxFileConfig loading/reading ***");
258 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
259 _T("testdata.fc"), wxEmptyString
,
260 wxCONFIG_USE_RELATIVE_PATH
);
262 // test simple reading
263 puts("\nReading config file:");
264 wxString
defValue(_T("default")), value
;
265 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
267 const FileConfTestData
& data
= fcTestData
[n
];
268 value
= fileconf
.Read(data
.name
, defValue
);
269 printf("\t%s = %s ", data
.name
, value
.c_str());
270 if ( value
== data
.value
)
276 printf("(ERROR: should be %s)\n", data
.value
);
280 // test enumerating the entries
281 puts("\nEnumerating all root entries:");
284 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
287 printf("\t%s = %s\n",
289 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
291 cont
= fileconf
.GetNextEntry(name
, dummy
);
295 #endif // TEST_FILECONF
297 // ----------------------------------------------------------------------------
299 // ----------------------------------------------------------------------------
307 Foo(int n_
) { n
= n_
; count
++; }
315 size_t Foo::count
= 0;
317 WX_DECLARE_LIST(Foo
, wxListFoos
);
318 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
320 #include <wx/listimpl.cpp>
322 WX_DEFINE_LIST(wxListFoos
);
324 static void TestHash()
326 puts("*** Testing wxHashTable ***\n");
330 hash
.DeleteContents(TRUE
);
332 printf("Hash created: %u foos in hash, %u foos totally\n",
333 hash
.GetCount(), Foo::count
);
335 static const int hashTestData
[] =
337 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
341 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
343 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
346 printf("Hash filled: %u foos in hash, %u foos totally\n",
347 hash
.GetCount(), Foo::count
);
349 puts("Hash access test:");
350 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
352 printf("\tGetting element with key %d, value %d: ",
354 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
357 printf("ERROR, not found.\n");
361 printf("%d (%s)\n", foo
->n
,
362 (size_t)foo
->n
== n
? "ok" : "ERROR");
366 printf("\nTrying to get an element not in hash: ");
368 if ( hash
.Get(1234) || hash
.Get(1, 0) )
370 puts("ERROR: found!");
374 puts("ok (not found)");
378 printf("Hash destroyed: %u foos left\n", Foo::count
);
383 // ----------------------------------------------------------------------------
385 // ----------------------------------------------------------------------------
389 #include <wx/mimetype.h>
391 static void TestMimeEnum()
393 wxMimeTypesManager mimeTM
;
394 wxArrayString mimetypes
;
396 size_t count
= mimeTM
.EnumAllFileTypes(mimetypes
);
398 printf("*** All %u known filetypes: ***\n", count
);
403 for ( size_t n
= 0; n
< count
; n
++ )
405 wxFileType
*filetype
= mimeTM
.GetFileTypeFromMimeType(mimetypes
[n
]);
408 printf("nothing known about the filetype '%s'!\n",
409 mimetypes
[n
].c_str());
413 filetype
->GetDescription(&desc
);
414 filetype
->GetExtensions(exts
);
416 filetype
->GetIcon(NULL
);
419 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
426 printf("\t%s: %s (%s)\n",
427 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
433 // ----------------------------------------------------------------------------
435 // ----------------------------------------------------------------------------
439 #include <wx/longlong.h>
440 #include <wx/timer.h>
442 // make a 64 bit number from 4 16 bit ones
443 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
445 // get a random 64 bit number
446 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
448 #if wxUSE_LONGLONG_WX
449 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
450 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
451 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
452 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
453 #endif // wxUSE_LONGLONG_WX
455 static void TestSpeed()
457 static const long max
= 100000000;
464 for ( n
= 0; n
< max
; n
++ )
469 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
472 #if wxUSE_LONGLONG_NATIVE
477 for ( n
= 0; n
< max
; n
++ )
482 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
484 #endif // wxUSE_LONGLONG_NATIVE
490 for ( n
= 0; n
< max
; n
++ )
495 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
499 static void TestLongLongConversion()
501 puts("*** Testing wxLongLong conversions ***\n");
505 for ( size_t n
= 0; n
< 100000; n
++ )
509 #if wxUSE_LONGLONG_NATIVE
510 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
512 wxASSERT_MSG( a
== b
, "conversions failure" );
514 puts("Can't do it without native long long type, test skipped.");
517 #endif // wxUSE_LONGLONG_NATIVE
519 if ( !(nTested
% 1000) )
531 static void TestMultiplication()
533 puts("*** Testing wxLongLong multiplication ***\n");
537 for ( size_t n
= 0; n
< 100000; n
++ )
542 #if wxUSE_LONGLONG_NATIVE
543 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
544 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
546 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
547 #else // !wxUSE_LONGLONG_NATIVE
548 puts("Can't do it without native long long type, test skipped.");
551 #endif // wxUSE_LONGLONG_NATIVE
553 if ( !(nTested
% 1000) )
565 static void TestDivision()
567 puts("*** Testing wxLongLong division ***\n");
571 for ( size_t n
= 0; n
< 100000; n
++ )
573 // get a random wxLongLong (shifting by 12 the MSB ensures that the
574 // multiplication will not overflow)
575 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
577 // get a random long (not wxLongLong for now) to divide it with
582 #if wxUSE_LONGLONG_NATIVE
583 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
585 wxLongLongNative p
= m
/ l
, s
= m
% l
;
586 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
587 #else // !wxUSE_LONGLONG_NATIVE
589 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
590 #endif // wxUSE_LONGLONG_NATIVE
592 if ( !(nTested
% 1000) )
604 static void TestAddition()
606 puts("*** Testing wxLongLong addition ***\n");
610 for ( size_t n
= 0; n
< 100000; n
++ )
616 #if wxUSE_LONGLONG_NATIVE
617 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
618 wxLongLongNative(b
.GetHi(), b
.GetLo()),
619 "addition failure" );
620 #else // !wxUSE_LONGLONG_NATIVE
621 wxASSERT_MSG( c
- b
== a
, "addition failure" );
622 #endif // wxUSE_LONGLONG_NATIVE
624 if ( !(nTested
% 1000) )
636 static void TestBitOperations()
638 puts("*** Testing wxLongLong bit operation ***\n");
642 for ( size_t n
= 0; n
< 100000; n
++ )
646 #if wxUSE_LONGLONG_NATIVE
647 for ( size_t n
= 0; n
< 33; n
++ )
649 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
654 wxASSERT_MSG( b
== c
, "bit shift failure" );
656 b
= wxLongLongNative(a
.GetHi(), a
.GetLo()) << n
;
659 wxASSERT_MSG( b
== c
, "bit shift failure" );
662 #else // !wxUSE_LONGLONG_NATIVE
663 puts("Can't do it without native long long type, test skipped.");
666 #endif // wxUSE_LONGLONG_NATIVE
668 if ( !(nTested
% 1000) )
683 #endif // TEST_LONGLONG
685 // ----------------------------------------------------------------------------
687 // ----------------------------------------------------------------------------
691 #include <wx/socket.h>
693 static void TestSocketClient()
695 puts("*** Testing wxSocketClient ***\n");
697 wxIPV4address addrDst
;
698 addrDst
.Hostname("www.wxwindows.org");
701 wxSocketClient client
;
702 if ( !client
.Connect(addrDst
) )
704 printf("ERROR: failed to connect to %s\n", addrDst
.Hostname().c_str());
710 client
.Write("get /front.htm\n", 17);
711 client
.Read(buf
, WXSIZEOF(buf
));
712 printf("Server replied:\n%s", buf
);
716 #endif // TEST_SOCKETS
718 // ----------------------------------------------------------------------------
720 // ----------------------------------------------------------------------------
726 #include <wx/datetime.h>
731 wxDateTime::wxDateTime_t day
;
732 wxDateTime::Month month
;
734 wxDateTime::wxDateTime_t hour
, min
, sec
;
736 wxDateTime::WeekDay wday
;
737 time_t gmticks
, ticks
;
739 void Init(const wxDateTime::Tm
& tm
)
748 gmticks
= ticks
= -1;
751 wxDateTime
DT() const
752 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
754 bool SameDay(const wxDateTime::Tm
& tm
) const
756 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
759 wxString
Format() const
762 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
764 wxDateTime::GetMonthName(month
).c_str(),
766 abs(wxDateTime::ConvertYearToBC(year
)),
767 year
> 0 ? "AD" : "BC");
771 wxString
FormatDate() const
774 s
.Printf("%02d-%s-%4d%s",
776 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
777 abs(wxDateTime::ConvertYearToBC(year
)),
778 year
> 0 ? "AD" : "BC");
783 static const Date testDates
[] =
785 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
786 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
787 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
788 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
789 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
790 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
791 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
792 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
793 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
794 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
795 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
796 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
797 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
798 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
799 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
802 // this test miscellaneous static wxDateTime functions
803 static void TestTimeStatic()
805 puts("\n*** wxDateTime static methods test ***");
807 // some info about the current date
808 int year
= wxDateTime::GetCurrentYear();
809 printf("Current year %d is %sa leap one and has %d days.\n",
811 wxDateTime::IsLeapYear(year
) ? "" : "not ",
812 wxDateTime::GetNumberOfDays(year
));
814 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
815 printf("Current month is '%s' ('%s') and it has %d days\n",
816 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
817 wxDateTime::GetMonthName(month
).c_str(),
818 wxDateTime::GetNumberOfDays(month
));
821 static const size_t nYears
= 5;
822 static const size_t years
[2][nYears
] =
824 // first line: the years to test
825 { 1990, 1976, 2000, 2030, 1984, },
827 // second line: TRUE if leap, FALSE otherwise
828 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
831 for ( size_t n
= 0; n
< nYears
; n
++ )
833 int year
= years
[0][n
];
834 bool should
= years
[1][n
] != 0,
835 is
= wxDateTime::IsLeapYear(year
);
837 printf("Year %d is %sa leap year (%s)\n",
840 should
== is
? "ok" : "ERROR");
842 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
846 // test constructing wxDateTime objects
847 static void TestTimeSet()
849 puts("\n*** wxDateTime construction test ***");
851 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
853 const Date
& d1
= testDates
[n
];
854 wxDateTime dt
= d1
.DT();
859 wxString s1
= d1
.Format(),
862 printf("Date: %s == %s (%s)\n",
863 s1
.c_str(), s2
.c_str(),
864 s1
== s2
? "ok" : "ERROR");
868 // test time zones stuff
869 static void TestTimeZones()
871 puts("\n*** wxDateTime timezone test ***");
873 wxDateTime now
= wxDateTime::Now();
875 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
876 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
877 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
878 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
879 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
880 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
882 wxDateTime::Tm tm
= now
.GetTm();
883 if ( wxDateTime(tm
) != now
)
885 printf("ERROR: got %s instead of %s\n",
886 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
890 // test some minimal support for the dates outside the standard range
891 static void TestTimeRange()
893 puts("\n*** wxDateTime out-of-standard-range dates test ***");
895 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
897 printf("Unix epoch:\t%s\n",
898 wxDateTime(2440587.5).Format(fmt
).c_str());
899 printf("Feb 29, 0: \t%s\n",
900 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
901 printf("JDN 0: \t%s\n",
902 wxDateTime(0.0).Format(fmt
).c_str());
903 printf("Jan 1, 1AD:\t%s\n",
904 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
905 printf("May 29, 2099:\t%s\n",
906 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
909 static void TestTimeTicks()
911 puts("\n*** wxDateTime ticks test ***");
913 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
915 const Date
& d
= testDates
[n
];
919 wxDateTime dt
= d
.DT();
920 long ticks
= (dt
.GetValue() / 1000).ToLong();
921 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
922 if ( ticks
== d
.ticks
)
928 printf(" (ERROR: should be %ld, delta = %ld)\n",
929 d
.ticks
, ticks
- d
.ticks
);
932 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
933 ticks
= (dt
.GetValue() / 1000).ToLong();
934 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
935 if ( ticks
== d
.gmticks
)
941 printf(" (ERROR: should be %ld, delta = %ld)\n",
942 d
.gmticks
, ticks
- d
.gmticks
);
949 // test conversions to JDN &c
950 static void TestTimeJDN()
952 puts("\n*** wxDateTime to JDN test ***");
954 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
956 const Date
& d
= testDates
[n
];
957 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
958 double jdn
= dt
.GetJulianDayNumber();
960 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
967 printf(" (ERROR: should be %f, delta = %f)\n",
973 // test week days computation
974 static void TestTimeWDays()
976 puts("\n*** wxDateTime weekday test ***");
980 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
982 const Date
& d
= testDates
[n
];
983 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
985 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
988 wxDateTime::GetWeekDayName(wday
).c_str());
989 if ( wday
== d
.wday
)
995 printf(" (ERROR: should be %s)\n",
996 wxDateTime::GetWeekDayName(d
.wday
).c_str());
1002 // test SetToWeekDay()
1003 struct WeekDateTestData
1005 Date date
; // the real date (precomputed)
1006 int nWeek
; // its week index in the month
1007 wxDateTime::WeekDay wday
; // the weekday
1008 wxDateTime::Month month
; // the month
1009 int year
; // and the year
1011 wxString
Format() const
1014 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
1016 case 1: which
= "first"; break;
1017 case 2: which
= "second"; break;
1018 case 3: which
= "third"; break;
1019 case 4: which
= "fourth"; break;
1020 case 5: which
= "fifth"; break;
1022 case -1: which
= "last"; break;
1027 which
+= " from end";
1030 s
.Printf("The %s %s of %s in %d",
1032 wxDateTime::GetWeekDayName(wday
).c_str(),
1033 wxDateTime::GetMonthName(month
).c_str(),
1040 // the array data was generated by the following python program
1042 from DateTime import *
1043 from whrandom import *
1044 from string import *
1046 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1047 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1049 week = DateTimeDelta(7)
1052 year = randint(1900, 2100)
1053 month = randint(1, 12)
1054 day = randint(1, 28)
1055 dt = DateTime(year, month, day)
1056 wday = dt.day_of_week
1058 countFromEnd = choice([-1, 1])
1061 while dt.month is month:
1062 dt = dt - countFromEnd * week
1063 weekNum = weekNum + countFromEnd
1065 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
1067 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
1068 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
1071 static const WeekDateTestData weekDatesTestData
[] =
1073 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
1074 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
1075 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
1076 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
1077 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
1078 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
1079 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
1080 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
1081 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
1082 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
1083 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
1084 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
1085 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
1086 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
1087 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
1088 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
1089 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
1090 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
1091 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
1092 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
1095 static const char *fmt
= "%d-%b-%Y";
1098 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
1100 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
1102 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
1104 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
1106 const Date
& d
= wd
.date
;
1107 if ( d
.SameDay(dt
.GetTm()) )
1113 dt
.Set(d
.day
, d
.month
, d
.year
);
1115 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
1120 // test the computation of (ISO) week numbers
1121 static void TestTimeWNumber()
1123 puts("\n*** wxDateTime week number test ***");
1125 struct WeekNumberTestData
1127 Date date
; // the date
1128 wxDateTime::wxDateTime_t week
; // the week number in the year
1129 wxDateTime::wxDateTime_t wmon
; // the week number in the month
1130 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
1131 wxDateTime::wxDateTime_t dnum
; // day number in the year
1134 // data generated with the following python script:
1136 from DateTime import *
1137 from whrandom import *
1138 from string import *
1140 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1141 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1143 def GetMonthWeek(dt):
1144 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
1145 if weekNumMonth < 0:
1146 weekNumMonth = weekNumMonth + 53
1149 def GetLastSundayBefore(dt):
1150 if dt.iso_week[2] == 7:
1153 return dt - DateTimeDelta(dt.iso_week[2])
1156 year = randint(1900, 2100)
1157 month = randint(1, 12)
1158 day = randint(1, 28)
1159 dt = DateTime(year, month, day)
1160 dayNum = dt.day_of_year
1161 weekNum = dt.iso_week[1]
1162 weekNumMonth = GetMonthWeek(dt)
1165 dtSunday = GetLastSundayBefore(dt)
1167 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
1168 weekNumMonth2 = weekNumMonth2 + 1
1169 dtSunday = dtSunday - DateTimeDelta(7)
1171 data = { 'day': rjust(`day`, 2), \
1172 'month': monthNames[month - 1], \
1174 'weekNum': rjust(`weekNum`, 2), \
1175 'weekNumMonth': weekNumMonth, \
1176 'weekNumMonth2': weekNumMonth2, \
1177 'dayNum': rjust(`dayNum`, 3) }
1179 print " { { %(day)s, "\
1180 "wxDateTime::%(month)s, "\
1183 "%(weekNumMonth)s, "\
1184 "%(weekNumMonth2)s, "\
1185 "%(dayNum)s }," % data
1188 static const WeekNumberTestData weekNumberTestDates
[] =
1190 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
1191 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
1192 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
1193 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
1194 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
1195 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
1196 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
1197 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
1198 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
1199 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
1200 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
1201 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
1202 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
1203 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
1204 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
1205 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
1206 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
1207 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
1208 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
1209 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
1212 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
1214 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
1215 const Date
& d
= wn
.date
;
1217 wxDateTime dt
= d
.DT();
1219 wxDateTime::wxDateTime_t
1220 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
1221 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
1222 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
1223 dnum
= dt
.GetDayOfYear();
1225 printf("%s: the day number is %d",
1226 d
.FormatDate().c_str(), dnum
);
1227 if ( dnum
== wn
.dnum
)
1233 printf(" (ERROR: should be %d)", wn
.dnum
);
1236 printf(", week in month is %d", wmon
);
1237 if ( wmon
== wn
.wmon
)
1243 printf(" (ERROR: should be %d)", wn
.wmon
);
1246 printf(" or %d", wmon2
);
1247 if ( wmon2
== wn
.wmon2
)
1253 printf(" (ERROR: should be %d)", wn
.wmon2
);
1256 printf(", week in year is %d", week
);
1257 if ( week
== wn
.week
)
1263 printf(" (ERROR: should be %d)\n", wn
.week
);
1268 // test DST calculations
1269 static void TestTimeDST()
1271 puts("\n*** wxDateTime DST test ***");
1273 printf("DST is%s in effect now.\n\n",
1274 wxDateTime::Now().IsDST() ? "" : " not");
1276 // taken from http://www.energy.ca.gov/daylightsaving.html
1277 static const Date datesDST
[2][2004 - 1900 + 1] =
1280 { 1, wxDateTime::Apr
, 1990 },
1281 { 7, wxDateTime::Apr
, 1991 },
1282 { 5, wxDateTime::Apr
, 1992 },
1283 { 4, wxDateTime::Apr
, 1993 },
1284 { 3, wxDateTime::Apr
, 1994 },
1285 { 2, wxDateTime::Apr
, 1995 },
1286 { 7, wxDateTime::Apr
, 1996 },
1287 { 6, wxDateTime::Apr
, 1997 },
1288 { 5, wxDateTime::Apr
, 1998 },
1289 { 4, wxDateTime::Apr
, 1999 },
1290 { 2, wxDateTime::Apr
, 2000 },
1291 { 1, wxDateTime::Apr
, 2001 },
1292 { 7, wxDateTime::Apr
, 2002 },
1293 { 6, wxDateTime::Apr
, 2003 },
1294 { 4, wxDateTime::Apr
, 2004 },
1297 { 28, wxDateTime::Oct
, 1990 },
1298 { 27, wxDateTime::Oct
, 1991 },
1299 { 25, wxDateTime::Oct
, 1992 },
1300 { 31, wxDateTime::Oct
, 1993 },
1301 { 30, wxDateTime::Oct
, 1994 },
1302 { 29, wxDateTime::Oct
, 1995 },
1303 { 27, wxDateTime::Oct
, 1996 },
1304 { 26, wxDateTime::Oct
, 1997 },
1305 { 25, wxDateTime::Oct
, 1998 },
1306 { 31, wxDateTime::Oct
, 1999 },
1307 { 29, wxDateTime::Oct
, 2000 },
1308 { 28, wxDateTime::Oct
, 2001 },
1309 { 27, wxDateTime::Oct
, 2002 },
1310 { 26, wxDateTime::Oct
, 2003 },
1311 { 31, wxDateTime::Oct
, 2004 },
1316 for ( year
= 1990; year
< 2005; year
++ )
1318 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
1319 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
1321 printf("DST period in the US for year %d: from %s to %s",
1322 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
1324 size_t n
= year
- 1990;
1325 const Date
& dBegin
= datesDST
[0][n
];
1326 const Date
& dEnd
= datesDST
[1][n
];
1328 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
1334 printf(" (ERROR: should be %s %d to %s %d)\n",
1335 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
1336 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
1342 for ( year
= 1990; year
< 2005; year
++ )
1344 printf("DST period in Europe for year %d: from %s to %s\n",
1346 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
1347 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
1351 // test wxDateTime -> text conversion
1352 static void TestTimeFormat()
1354 puts("\n*** wxDateTime formatting test ***");
1356 // some information may be lost during conversion, so store what kind
1357 // of info should we recover after a round trip
1360 CompareNone
, // don't try comparing
1361 CompareBoth
, // dates and times should be identical
1362 CompareDate
, // dates only
1363 CompareTime
// time only
1368 CompareKind compareKind
;
1370 } formatTestFormats
[] =
1372 { CompareBoth
, "---> %c" },
1373 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
1374 { CompareBoth
, "Date is %x, time is %X" },
1375 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
1376 { CompareNone
, "The day of year: %j, the week of year: %W" },
1379 static const Date formatTestDates
[] =
1381 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
1382 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
1384 // this test can't work for other centuries because it uses two digit
1385 // years in formats, so don't even try it
1386 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
1387 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
1388 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
1392 // an extra test (as it doesn't depend on date, don't do it in the loop)
1393 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
1395 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
1399 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
1400 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
1402 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
1403 printf("%s", s
.c_str());
1405 // what can we recover?
1406 int kind
= formatTestFormats
[n
].compareKind
;
1410 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
1413 // converion failed - should it have?
1414 if ( kind
== CompareNone
)
1417 puts(" (ERROR: conversion back failed)");
1421 // should have parsed the entire string
1422 puts(" (ERROR: conversion back stopped too soon)");
1426 bool equal
= FALSE
; // suppress compilaer warning
1434 equal
= dt
.IsSameDate(dt2
);
1438 equal
= dt
.IsSameTime(dt2
);
1444 printf(" (ERROR: got back '%s' instead of '%s')\n",
1445 dt2
.Format().c_str(), dt
.Format().c_str());
1456 // test text -> wxDateTime conversion
1457 static void TestTimeParse()
1459 puts("\n*** wxDateTime parse test ***");
1461 struct ParseTestData
1468 static const ParseTestData parseTestDates
[] =
1470 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
1471 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
1474 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
1476 const char *format
= parseTestDates
[n
].format
;
1478 printf("%s => ", format
);
1481 if ( dt
.ParseRfc822Date(format
) )
1483 printf("%s ", dt
.Format().c_str());
1485 if ( parseTestDates
[n
].good
)
1487 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
1494 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
1499 puts("(ERROR: bad format)");
1504 printf("bad format (%s)\n",
1505 parseTestDates
[n
].good
? "ERROR" : "ok");
1510 static void TestInteractive()
1512 puts("\n*** interactive wxDateTime tests ***");
1518 printf("Enter a date: ");
1519 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
1523 if ( !dt
.ParseDate(buf
) )
1525 puts("failed to parse the date");
1530 printf("%s: day %u, week of month %u/%u, week of year %u\n",
1531 dt
.FormatISODate().c_str(),
1533 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
1534 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
1535 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
1538 puts("\n*** done ***");
1541 static void TestTimeArithmetics()
1543 puts("\n*** testing arithmetic operations on wxDateTime ***");
1549 } testArithmData
[] =
1551 { wxDateSpan::Day(), "day" },
1552 { wxDateSpan::Week(), "week" },
1553 { wxDateSpan::Month(), "month" },
1554 { wxDateSpan::Year(), "year" },
1555 { wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days" },
1558 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
1560 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
1562 wxDateSpan span
= testArithmData
[n
].span
;
1566 const char *name
= testArithmData
[n
].name
;
1567 printf("%s + %s = %s, %s - %s = %s\n",
1568 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
1569 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
1571 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
1572 if ( dt1
- span
== dt
)
1578 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
1581 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
1582 if ( dt2
+ span
== dt
)
1588 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
1591 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
1592 if ( dt2
+ 2*span
== dt1
)
1598 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
1605 static void TestTimeHolidays()
1607 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
1609 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
1610 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
1611 dtEnd
= dtStart
.GetLastMonthDay();
1613 wxDateTimeArray hol
;
1614 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
1616 const wxChar
*format
= "%d-%b-%Y (%a)";
1618 printf("All holidays between %s and %s:\n",
1619 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
1621 size_t count
= hol
.GetCount();
1622 for ( size_t n
= 0; n
< count
; n
++ )
1624 printf("\t%s\n", hol
[n
].Format(format
).c_str());
1632 // test compatibility with the old wxDate/wxTime classes
1633 static void TestTimeCompatibility()
1635 puts("\n*** wxDateTime compatibility test ***");
1637 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
1638 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
1640 double jdnNow
= wxDateTime::Now().GetJDN();
1641 long jdnMidnight
= (long)(jdnNow
- 0.5);
1642 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
1644 jdnMidnight
= wxDate().Set().GetJulianDate();
1645 printf("wxDateTime for today: %s\n",
1646 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
1648 int flags
= wxEUROPEAN
;//wxFULL;
1651 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
1652 for ( int n
= 0; n
< 7; n
++ )
1654 printf("Previous %s is %s\n",
1655 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
1656 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
1664 // ----------------------------------------------------------------------------
1666 // ----------------------------------------------------------------------------
1670 #include <wx/thread.h>
1672 static size_t gs_counter
= (size_t)-1;
1673 static wxCriticalSection gs_critsect
;
1674 static wxCondition gs_cond
;
1676 class MyJoinableThread
: public wxThread
1679 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
1680 { m_n
= n
; Create(); }
1682 // thread execution starts here
1683 virtual ExitCode
Entry();
1689 wxThread::ExitCode
MyJoinableThread::Entry()
1691 unsigned long res
= 1;
1692 for ( size_t n
= 1; n
< m_n
; n
++ )
1696 // it's a loooong calculation :-)
1700 return (ExitCode
)res
;
1703 class MyDetachedThread
: public wxThread
1706 MyDetachedThread(size_t n
, char ch
)
1710 m_cancelled
= FALSE
;
1715 // thread execution starts here
1716 virtual ExitCode
Entry();
1719 virtual void OnExit();
1722 size_t m_n
; // number of characters to write
1723 char m_ch
; // character to write
1725 bool m_cancelled
; // FALSE if we exit normally
1728 wxThread::ExitCode
MyDetachedThread::Entry()
1731 wxCriticalSectionLocker
lock(gs_critsect
);
1732 if ( gs_counter
== (size_t)-1 )
1738 for ( size_t n
= 0; n
< m_n
; n
++ )
1740 if ( TestDestroy() )
1750 wxThread::Sleep(100);
1756 void MyDetachedThread::OnExit()
1758 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
1760 wxCriticalSectionLocker
lock(gs_critsect
);
1761 if ( !--gs_counter
&& !m_cancelled
)
1765 void TestDetachedThreads()
1767 puts("\n*** Testing detached threads ***");
1769 static const size_t nThreads
= 3;
1770 MyDetachedThread
*threads
[nThreads
];
1772 for ( n
= 0; n
< nThreads
; n
++ )
1774 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
1777 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
1778 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
1780 for ( n
= 0; n
< nThreads
; n
++ )
1785 // wait until all threads terminate
1791 void TestJoinableThreads()
1793 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
1795 // calc 10! in the background
1796 MyJoinableThread
thread(10);
1799 printf("\nThread terminated with exit code %lu.\n",
1800 (unsigned long)thread
.Wait());
1803 void TestThreadSuspend()
1805 puts("\n*** Testing thread suspend/resume functions ***");
1807 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
1811 // this is for this demo only, in a real life program we'd use another
1812 // condition variable which would be signaled from wxThread::Entry() to
1813 // tell us that the thread really started running - but here just wait a
1814 // bit and hope that it will be enough (the problem is, of course, that
1815 // the thread might still not run when we call Pause() which will result
1817 wxThread::Sleep(300);
1819 for ( size_t n
= 0; n
< 3; n
++ )
1823 puts("\nThread suspended");
1826 // don't sleep but resume immediately the first time
1827 wxThread::Sleep(300);
1829 puts("Going to resume the thread");
1834 puts("Waiting until it terminates now");
1836 // wait until the thread terminates
1842 void TestThreadDelete()
1844 // As above, using Sleep() is only for testing here - we must use some
1845 // synchronisation object instead to ensure that the thread is still
1846 // running when we delete it - deleting a detached thread which already
1847 // terminated will lead to a crash!
1849 puts("\n*** Testing thread delete function ***");
1851 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
1855 puts("\nDeleted a thread which didn't start to run yet.");
1857 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
1861 wxThread::Sleep(300);
1865 puts("\nDeleted a running thread.");
1867 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
1871 wxThread::Sleep(300);
1877 puts("\nDeleted a sleeping thread.");
1879 MyJoinableThread
thread3(20);
1884 puts("\nDeleted a joinable thread.");
1886 MyJoinableThread
thread4(2);
1889 wxThread::Sleep(300);
1893 puts("\nDeleted a joinable thread which already terminated.");
1898 #endif // TEST_THREADS
1900 // ----------------------------------------------------------------------------
1902 // ----------------------------------------------------------------------------
1906 void PrintArray(const char* name
, const wxArrayString
& array
)
1908 printf("Dump of the array '%s'\n", name
);
1910 size_t nCount
= array
.GetCount();
1911 for ( size_t n
= 0; n
< nCount
; n
++ )
1913 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
1917 #endif // TEST_ARRAYS
1919 // ----------------------------------------------------------------------------
1921 // ----------------------------------------------------------------------------
1925 #include "wx/timer.h"
1926 #include "wx/tokenzr.h"
1928 static void TestStringConstruction()
1930 puts("*** Testing wxString constructores ***");
1932 #define TEST_CTOR(args, res) \
1935 printf("wxString%s = %s ", #args, s.c_str()); \
1942 printf("(ERROR: should be %s)\n", res); \
1946 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
1947 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
1948 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
1949 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
1951 static const wxChar
*s
= _T("?really!");
1952 const wxChar
*start
= wxStrchr(s
, _T('r'));
1953 const wxChar
*end
= wxStrchr(s
, _T('!'));
1954 TEST_CTOR((start
, end
), _T("really"));
1959 static void TestString()
1969 for (int i
= 0; i
< 1000000; ++i
)
1973 c
= "! How'ya doin'?";
1976 c
= "Hello world! What's up?";
1981 printf ("TestString elapsed time: %ld\n", sw
.Time());
1984 static void TestPChar()
1992 for (int i
= 0; i
< 1000000; ++i
)
1994 strcpy (a
, "Hello");
1995 strcpy (b
, " world");
1996 strcpy (c
, "! How'ya doin'?");
1999 strcpy (c
, "Hello world! What's up?");
2000 if (strcmp (c
, a
) == 0)
2004 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
2007 static void TestStringSub()
2009 wxString
s("Hello, world!");
2011 puts("*** Testing wxString substring extraction ***");
2013 printf("String = '%s'\n", s
.c_str());
2014 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
2015 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
2016 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
2017 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
2018 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
2019 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
2024 static void TestStringFormat()
2026 puts("*** Testing wxString formatting ***");
2029 s
.Printf("%03d", 18);
2031 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
2032 printf("Number 18: %s\n", s
.c_str());
2037 // returns "not found" for npos, value for all others
2038 static wxString
PosToString(size_t res
)
2040 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
2041 : wxString::Format(_T("%u"), res
);
2045 static void TestStringFind()
2047 puts("*** Testing wxString find() functions ***");
2049 static const wxChar
*strToFind
= _T("ell");
2050 static const struct StringFindTest
2054 result
; // of searching "ell" in str
2057 { _T("Well, hello world"), 0, 1 },
2058 { _T("Well, hello world"), 6, 7 },
2059 { _T("Well, hello world"), 9, wxString::npos
},
2062 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
2064 const StringFindTest
& ft
= findTestData
[n
];
2065 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
2067 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
2068 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
2070 size_t resTrue
= ft
.result
;
2071 if ( res
== resTrue
)
2077 printf(_T("(ERROR: should be %s)\n"),
2078 PosToString(resTrue
).c_str());
2085 // replace TABs with \t and CRs with \n
2086 static wxString
MakePrintable(const wxChar
*s
)
2089 (void)str
.Replace(_T("\t"), _T("\\t"));
2090 (void)str
.Replace(_T("\n"), _T("\\n"));
2091 (void)str
.Replace(_T("\r"), _T("\\r"));
2096 static void TestStringTokenizer()
2098 puts("*** Testing wxStringTokenizer ***");
2100 static const wxChar
*modeNames
[] =
2104 _T("return all empty"),
2109 static const struct StringTokenizerTest
2111 const wxChar
*str
; // string to tokenize
2112 const wxChar
*delims
; // delimiters to use
2113 size_t count
; // count of token
2114 wxStringTokenizerMode mode
; // how should we tokenize it
2115 } tokenizerTestData
[] =
2117 { _T(""), _T(" "), 0 },
2118 { _T("Hello, world"), _T(" "), 2 },
2119 { _T("Hello, world "), _T(" "), 2 },
2120 { _T("Hello, world"), _T(","), 2 },
2121 { _T("Hello, world!"), _T(",!"), 2 },
2122 { _T("Hello,, world!"), _T(",!"), 3 },
2123 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
2124 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
2125 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
2126 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
2127 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
2128 { _T("01/02/99"), _T("/-"), 3 },
2129 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
2132 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
2134 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
2135 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
2137 size_t count
= tkz
.CountTokens();
2138 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
2139 MakePrintable(tt
.str
).c_str(),
2141 MakePrintable(tt
.delims
).c_str(),
2142 modeNames
[tkz
.GetMode()]);
2143 if ( count
== tt
.count
)
2149 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
2154 // if we emulate strtok(), check that we do it correctly
2155 wxChar
*buf
, *s
, *last
;
2157 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
2159 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
2160 wxStrcpy(buf
, tt
.str
);
2162 s
= wxStrtok(buf
, tt
.delims
, &last
);
2169 // now show the tokens themselves
2171 while ( tkz
.HasMoreTokens() )
2173 wxString token
= tkz
.GetNextToken();
2175 printf(_T("\ttoken %u: '%s'"),
2177 MakePrintable(token
).c_str());
2187 printf(" (ERROR: should be %s)\n", s
);
2190 s
= wxStrtok(NULL
, tt
.delims
, &last
);
2194 // nothing to compare with
2199 if ( count2
!= count
)
2201 puts(_T("\tERROR: token count mismatch"));
2210 #endif // TEST_STRINGS
2212 // ----------------------------------------------------------------------------
2214 // ----------------------------------------------------------------------------
2216 int main(int argc
, char **argv
)
2218 if ( !wxInitialize() )
2220 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
2224 puts("Sleeping for 3 seconds... z-z-z-z-z...");
2226 #endif // TEST_USLEEP
2229 static const wxCmdLineEntryDesc cmdLineDesc
[] =
2231 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
2232 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
2234 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
2235 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
2236 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
2237 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
2239 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
2240 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
2245 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
2247 switch ( parser
.Parse() )
2250 wxLogMessage("Help was given, terminating.");
2254 ShowCmdLine(parser
);
2258 wxLogMessage("Syntax error detected, aborting.");
2261 #endif // TEST_CMDLINE
2271 TestStringConstruction();
2275 TestStringTokenizer();
2277 #endif // TEST_STRINGS
2288 puts("*** Initially:");
2290 PrintArray("a1", a1
);
2292 wxArrayString
a2(a1
);
2293 PrintArray("a2", a2
);
2295 wxSortedArrayString
a3(a1
);
2296 PrintArray("a3", a3
);
2298 puts("*** After deleting a string from a1");
2301 PrintArray("a1", a1
);
2302 PrintArray("a2", a2
);
2303 PrintArray("a3", a3
);
2305 puts("*** After reassigning a1 to a2 and a3");
2307 PrintArray("a2", a2
);
2308 PrintArray("a3", a3
);
2309 #endif // TEST_ARRAYS
2317 #endif // TEST_EXECUTE
2319 #ifdef TEST_FILECONF
2321 #endif // TEST_FILECONF
2325 for ( size_t n
= 0; n
< 8000; n
++ )
2327 s
<< (char)('A' + (n
% 26));
2331 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
2333 // this one shouldn't be truncated
2336 // but this one will because log functions use fixed size buffer
2337 // (note that it doesn't need '\n' at the end neither - will be added
2339 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
2343 int nCPUs
= wxThread::GetCPUCount();
2344 printf("This system has %d CPUs\n", nCPUs
);
2346 wxThread::SetConcurrency(nCPUs
);
2348 if ( argc
> 1 && argv
[1][0] == 't' )
2349 wxLog::AddTraceMask("thread");
2352 TestDetachedThreads();
2354 TestJoinableThreads();
2356 TestThreadSuspend();
2360 #endif // TEST_THREADS
2362 #ifdef TEST_LONGLONG
2363 // seed pseudo random generator
2364 srand((unsigned)time(NULL
));
2370 TestMultiplication();
2375 TestLongLongConversion();
2376 TestBitOperations();
2378 #endif // TEST_LONGLONG
2390 #endif // TEST_SOCKETS
2406 TestTimeArithmetics();