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
35 //#define TEST_EXECUTE
38 //#define TEST_LONGLONG
40 //#define TEST_STRINGS
41 //#define TEST_THREADS
44 // ============================================================================
46 // ============================================================================
50 // ----------------------------------------------------------------------------
52 // ----------------------------------------------------------------------------
54 #include <wx/cmdline.h>
55 #include <wx/datetime.h>
57 static void ShowCmdLine(const wxCmdLineParser
& parser
)
59 wxString s
= "Input files: ";
61 size_t count
= parser
.GetParamCount();
62 for ( size_t param
= 0; param
< count
; param
++ )
64 s
<< parser
.GetParam(param
) << ' ';
68 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
69 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
74 if ( parser
.Found("o", &strVal
) )
75 s
<< "Output file:\t" << strVal
<< '\n';
76 if ( parser
.Found("i", &strVal
) )
77 s
<< "Input dir:\t" << strVal
<< '\n';
78 if ( parser
.Found("s", &lVal
) )
79 s
<< "Size:\t" << lVal
<< '\n';
80 if ( parser
.Found("d", &dt
) )
81 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
86 #endif // TEST_CMDLINE
88 // ----------------------------------------------------------------------------
90 // ----------------------------------------------------------------------------
96 static void TestDirEnumHelper(wxDir
& dir
,
97 int flags
= wxDIR_DEFAULT
,
98 const wxString
& filespec
= wxEmptyString
)
102 if ( !dir
.IsOpened() )
105 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
108 printf("\t%s\n", filename
.c_str());
110 cont
= dir
.GetNext(&filename
);
116 static void TestDirEnum()
118 wxDir
dir(wxGetCwd());
120 puts("Enumerating everything in current directory:");
121 TestDirEnumHelper(dir
);
123 puts("Enumerating really everything in current directory:");
124 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
126 puts("Enumerating object files in current directory:");
127 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
129 puts("Enumerating directories in current directory:");
130 TestDirEnumHelper(dir
, wxDIR_DIRS
);
132 puts("Enumerating files in current directory:");
133 TestDirEnumHelper(dir
, wxDIR_FILES
);
135 puts("Enumerating files including hidden in current directory:");
136 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
140 #elif defined(__WXMSW__)
143 #error "don't know where the root directory is"
146 puts("Enumerating everything in root directory:");
147 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
149 puts("Enumerating directories in root directory:");
150 TestDirEnumHelper(dir
, wxDIR_DIRS
);
152 puts("Enumerating files in root directory:");
153 TestDirEnumHelper(dir
, wxDIR_FILES
);
155 puts("Enumerating files including hidden in root directory:");
156 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
158 puts("Enumerating files in non existing directory:");
159 wxDir
dirNo("nosuchdir");
160 TestDirEnumHelper(dirNo
);
165 // ----------------------------------------------------------------------------
167 // ----------------------------------------------------------------------------
171 #include <wx/utils.h>
173 static void TestExecute()
175 puts("*** testing wxExecute ***");
178 #define COMMAND "echo hi"
179 #elif defined(__WXMSW__)
180 #define COMMAND "command.com -c 'echo hi'"
182 #error "no command to exec"
185 if ( wxExecute(COMMAND
) == 0 )
191 #endif // TEST_EXECUTE
193 // ----------------------------------------------------------------------------
195 // ----------------------------------------------------------------------------
199 #include <wx/confbase.h>
200 #include <wx/fileconf.h>
202 static const struct FileConfTestData
204 const wxChar
*name
; // value name
205 const wxChar
*value
; // the value from the file
208 { _T("value1"), _T("one") },
209 { _T("value2"), _T("two") },
210 { _T("novalue"), _T("default") },
213 static void TestFileConfRead()
215 puts("*** testing wxFileConfig loading/reading ***");
217 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
218 _T("testdata.fc"), wxEmptyString
,
219 wxCONFIG_USE_RELATIVE_PATH
);
221 // test simple reading
222 puts("\nReading config file:");
223 wxString
defValue(_T("default")), value
;
224 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
226 const FileConfTestData
& data
= fcTestData
[n
];
227 value
= fileconf
.Read(data
.name
, defValue
);
228 printf("\t%s = %s ", data
.name
, value
.c_str());
229 if ( value
== data
.value
)
235 printf("(ERROR: should be %s)\n", data
.value
);
239 // test enumerating the entries
240 puts("\nEnumerating all root entries:");
243 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
246 printf("\t%s = %s\n",
248 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
250 cont
= fileconf
.GetNextEntry(name
, dummy
);
254 #endif // TEST_FILECONF
256 // ----------------------------------------------------------------------------
258 // ----------------------------------------------------------------------------
262 #include <wx/mimetype.h>
264 static void TestMimeEnum()
266 wxMimeTypesManager mimeTM
;
267 wxArrayString mimetypes
;
269 size_t count
= mimeTM
.EnumAllFileTypes(mimetypes
);
271 printf("*** All %u known filetypes: ***\n", count
);
276 for ( size_t n
= 0; n
< count
; n
++ )
278 wxFileType
*filetype
= mimeTM
.GetFileTypeFromMimeType(mimetypes
[n
]);
281 printf("nothing known about the filetype '%s'!\n",
282 mimetypes
[n
].c_str());
286 filetype
->GetDescription(&desc
);
287 filetype
->GetExtensions(exts
);
289 filetype
->GetIcon(NULL
);
292 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
299 printf("\t%s: %s (%s)\n",
300 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
306 // ----------------------------------------------------------------------------
308 // ----------------------------------------------------------------------------
312 #include <wx/longlong.h>
313 #include <wx/timer.h>
315 // make a 64 bit number from 4 16 bit ones
316 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
318 // get a random 64 bit number
319 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
321 #if wxUSE_LONGLONG_WX
322 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
323 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
324 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
325 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
326 #endif // wxUSE_LONGLONG_WX
328 static void TestSpeed()
330 static const long max
= 100000000;
337 for ( n
= 0; n
< max
; n
++ )
342 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
345 #if wxUSE_LONGLONG_NATIVE
350 for ( n
= 0; n
< max
; n
++ )
355 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
357 #endif // wxUSE_LONGLONG_NATIVE
363 for ( n
= 0; n
< max
; n
++ )
368 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
372 static void TestLongLongConversion()
374 puts("*** Testing wxLongLong conversions ***\n");
378 for ( size_t n
= 0; n
< 100000; n
++ )
382 #if wxUSE_LONGLONG_NATIVE
383 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
385 wxASSERT_MSG( a
== b
, "conversions failure" );
387 puts("Can't do it without native long long type, test skipped.");
390 #endif // wxUSE_LONGLONG_NATIVE
392 if ( !(nTested
% 1000) )
404 static void TestMultiplication()
406 puts("*** Testing wxLongLong multiplication ***\n");
410 for ( size_t n
= 0; n
< 100000; n
++ )
415 #if wxUSE_LONGLONG_NATIVE
416 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
417 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
419 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
420 #else // !wxUSE_LONGLONG_NATIVE
421 puts("Can't do it without native long long type, test skipped.");
424 #endif // wxUSE_LONGLONG_NATIVE
426 if ( !(nTested
% 1000) )
438 static void TestDivision()
440 puts("*** Testing wxLongLong division ***\n");
444 for ( size_t n
= 0; n
< 100000; n
++ )
446 // get a random wxLongLong (shifting by 12 the MSB ensures that the
447 // multiplication will not overflow)
448 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
450 // get a random long (not wxLongLong for now) to divide it with
455 #if wxUSE_LONGLONG_NATIVE
456 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
458 wxLongLongNative p
= m
/ l
, s
= m
% l
;
459 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
460 #else // !wxUSE_LONGLONG_NATIVE
462 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
463 #endif // wxUSE_LONGLONG_NATIVE
465 if ( !(nTested
% 1000) )
477 static void TestAddition()
479 puts("*** Testing wxLongLong addition ***\n");
483 for ( size_t n
= 0; n
< 100000; n
++ )
489 #if wxUSE_LONGLONG_NATIVE
490 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
491 wxLongLongNative(b
.GetHi(), b
.GetLo()),
492 "addition failure" );
493 #else // !wxUSE_LONGLONG_NATIVE
494 wxASSERT_MSG( c
- b
== a
, "addition failure" );
495 #endif // wxUSE_LONGLONG_NATIVE
497 if ( !(nTested
% 1000) )
509 static void TestBitOperations()
511 puts("*** Testing wxLongLong bit operation ***\n");
515 for ( size_t n
= 0; n
< 100000; n
++ )
519 #if wxUSE_LONGLONG_NATIVE
520 for ( size_t n
= 0; n
< 33; n
++ )
522 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
527 wxASSERT_MSG( b
== c
, "bit shift failure" );
529 b
= wxLongLongNative(a
.GetHi(), a
.GetLo()) << n
;
532 wxASSERT_MSG( b
== c
, "bit shift failure" );
535 #else // !wxUSE_LONGLONG_NATIVE
536 puts("Can't do it without native long long type, test skipped.");
539 #endif // wxUSE_LONGLONG_NATIVE
541 if ( !(nTested
% 1000) )
556 #endif // TEST_LONGLONG
558 // ----------------------------------------------------------------------------
560 // ----------------------------------------------------------------------------
566 #include <wx/datetime.h>
571 wxDateTime::wxDateTime_t day
;
572 wxDateTime::Month month
;
574 wxDateTime::wxDateTime_t hour
, min
, sec
;
576 wxDateTime::WeekDay wday
;
577 time_t gmticks
, ticks
;
579 void Init(const wxDateTime::Tm
& tm
)
588 gmticks
= ticks
= -1;
591 wxDateTime
DT() const
592 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
594 bool SameDay(const wxDateTime::Tm
& tm
) const
596 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
599 wxString
Format() const
602 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
604 wxDateTime::GetMonthName(month
).c_str(),
606 abs(wxDateTime::ConvertYearToBC(year
)),
607 year
> 0 ? "AD" : "BC");
611 wxString
FormatDate() const
614 s
.Printf("%02d-%s-%4d%s",
616 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
617 abs(wxDateTime::ConvertYearToBC(year
)),
618 year
> 0 ? "AD" : "BC");
623 static const Date testDates
[] =
625 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
626 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
627 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
628 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
629 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
630 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
631 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
632 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
633 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
634 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
635 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
636 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
637 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
638 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
639 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
642 // this test miscellaneous static wxDateTime functions
643 static void TestTimeStatic()
645 puts("\n*** wxDateTime static methods test ***");
647 // some info about the current date
648 int year
= wxDateTime::GetCurrentYear();
649 printf("Current year %d is %sa leap one and has %d days.\n",
651 wxDateTime::IsLeapYear(year
) ? "" : "not ",
652 wxDateTime::GetNumberOfDays(year
));
654 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
655 printf("Current month is '%s' ('%s') and it has %d days\n",
656 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
657 wxDateTime::GetMonthName(month
).c_str(),
658 wxDateTime::GetNumberOfDays(month
));
661 static const size_t nYears
= 5;
662 static const size_t years
[2][nYears
] =
664 // first line: the years to test
665 { 1990, 1976, 2000, 2030, 1984, },
667 // second line: TRUE if leap, FALSE otherwise
668 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
671 for ( size_t n
= 0; n
< nYears
; n
++ )
673 int year
= years
[0][n
];
674 bool should
= years
[1][n
] != 0,
675 is
= wxDateTime::IsLeapYear(year
);
677 printf("Year %d is %sa leap year (%s)\n",
680 should
== is
? "ok" : "ERROR");
682 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
686 // test constructing wxDateTime objects
687 static void TestTimeSet()
689 puts("\n*** wxDateTime construction test ***");
691 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
693 const Date
& d1
= testDates
[n
];
694 wxDateTime dt
= d1
.DT();
699 wxString s1
= d1
.Format(),
702 printf("Date: %s == %s (%s)\n",
703 s1
.c_str(), s2
.c_str(),
704 s1
== s2
? "ok" : "ERROR");
708 // test time zones stuff
709 static void TestTimeZones()
711 puts("\n*** wxDateTime timezone test ***");
713 wxDateTime now
= wxDateTime::Now();
715 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
716 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
717 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
718 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
719 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
720 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
722 wxDateTime::Tm tm
= now
.GetTm();
723 if ( wxDateTime(tm
) != now
)
725 printf("ERROR: got %s instead of %s\n",
726 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
730 // test some minimal support for the dates outside the standard range
731 static void TestTimeRange()
733 puts("\n*** wxDateTime out-of-standard-range dates test ***");
735 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
737 printf("Unix epoch:\t%s\n",
738 wxDateTime(2440587.5).Format(fmt
).c_str());
739 printf("Feb 29, 0: \t%s\n",
740 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
741 printf("JDN 0: \t%s\n",
742 wxDateTime(0.0).Format(fmt
).c_str());
743 printf("Jan 1, 1AD:\t%s\n",
744 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
745 printf("May 29, 2099:\t%s\n",
746 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
749 static void TestTimeTicks()
751 puts("\n*** wxDateTime ticks test ***");
753 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
755 const Date
& d
= testDates
[n
];
759 wxDateTime dt
= d
.DT();
760 long ticks
= (dt
.GetValue() / 1000).ToLong();
761 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
762 if ( ticks
== d
.ticks
)
768 printf(" (ERROR: should be %ld, delta = %ld)\n",
769 d
.ticks
, ticks
- d
.ticks
);
772 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
773 ticks
= (dt
.GetValue() / 1000).ToLong();
774 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
775 if ( ticks
== d
.gmticks
)
781 printf(" (ERROR: should be %ld, delta = %ld)\n",
782 d
.gmticks
, ticks
- d
.gmticks
);
789 // test conversions to JDN &c
790 static void TestTimeJDN()
792 puts("\n*** wxDateTime to JDN test ***");
794 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
796 const Date
& d
= testDates
[n
];
797 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
798 double jdn
= dt
.GetJulianDayNumber();
800 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
807 printf(" (ERROR: should be %f, delta = %f)\n",
813 // test week days computation
814 static void TestTimeWDays()
816 puts("\n*** wxDateTime weekday test ***");
820 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
822 const Date
& d
= testDates
[n
];
823 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
825 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
828 wxDateTime::GetWeekDayName(wday
).c_str());
829 if ( wday
== d
.wday
)
835 printf(" (ERROR: should be %s)\n",
836 wxDateTime::GetWeekDayName(d
.wday
).c_str());
842 // test SetToWeekDay()
843 struct WeekDateTestData
845 Date date
; // the real date (precomputed)
846 int nWeek
; // its week index in the month
847 wxDateTime::WeekDay wday
; // the weekday
848 wxDateTime::Month month
; // the month
849 int year
; // and the year
851 wxString
Format() const
854 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
856 case 1: which
= "first"; break;
857 case 2: which
= "second"; break;
858 case 3: which
= "third"; break;
859 case 4: which
= "fourth"; break;
860 case 5: which
= "fifth"; break;
862 case -1: which
= "last"; break;
867 which
+= " from end";
870 s
.Printf("The %s %s of %s in %d",
872 wxDateTime::GetWeekDayName(wday
).c_str(),
873 wxDateTime::GetMonthName(month
).c_str(),
880 // the array data was generated by the following python program
882 from DateTime import *
883 from whrandom import *
886 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
887 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
889 week = DateTimeDelta(7)
892 year = randint(1900, 2100)
893 month = randint(1, 12)
895 dt = DateTime(year, month, day)
896 wday = dt.day_of_week
898 countFromEnd = choice([-1, 1])
901 while dt.month is month:
902 dt = dt - countFromEnd * week
903 weekNum = weekNum + countFromEnd
905 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
907 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
908 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
911 static const WeekDateTestData weekDatesTestData
[] =
913 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
914 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
915 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
916 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
917 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
918 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
919 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
920 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
921 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
922 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
923 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
924 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
925 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
926 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
927 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
928 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
929 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
930 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
931 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
932 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
935 static const char *fmt
= "%d-%b-%Y";
938 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
940 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
942 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
944 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
946 const Date
& d
= wd
.date
;
947 if ( d
.SameDay(dt
.GetTm()) )
953 dt
.Set(d
.day
, d
.month
, d
.year
);
955 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
960 // test the computation of (ISO) week numbers
961 static void TestTimeWNumber()
963 puts("\n*** wxDateTime week number test ***");
965 struct WeekNumberTestData
967 Date date
; // the date
968 wxDateTime::wxDateTime_t week
; // the week number in the year
969 wxDateTime::wxDateTime_t wmon
; // the week number in the month
970 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
971 wxDateTime::wxDateTime_t dnum
; // day number in the year
974 // data generated with the following python script:
976 from DateTime import *
977 from whrandom import *
980 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
981 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
983 def GetMonthWeek(dt):
984 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
986 weekNumMonth = weekNumMonth + 53
989 def GetLastSundayBefore(dt):
990 if dt.iso_week[2] == 7:
993 return dt - DateTimeDelta(dt.iso_week[2])
996 year = randint(1900, 2100)
997 month = randint(1, 12)
999 dt = DateTime(year, month, day)
1000 dayNum = dt.day_of_year
1001 weekNum = dt.iso_week[1]
1002 weekNumMonth = GetMonthWeek(dt)
1005 dtSunday = GetLastSundayBefore(dt)
1007 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
1008 weekNumMonth2 = weekNumMonth2 + 1
1009 dtSunday = dtSunday - DateTimeDelta(7)
1011 data = { 'day': rjust(`day`, 2), \
1012 'month': monthNames[month - 1], \
1014 'weekNum': rjust(`weekNum`, 2), \
1015 'weekNumMonth': weekNumMonth, \
1016 'weekNumMonth2': weekNumMonth2, \
1017 'dayNum': rjust(`dayNum`, 3) }
1019 print " { { %(day)s, "\
1020 "wxDateTime::%(month)s, "\
1023 "%(weekNumMonth)s, "\
1024 "%(weekNumMonth2)s, "\
1025 "%(dayNum)s }," % data
1028 static const WeekNumberTestData weekNumberTestDates
[] =
1030 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
1031 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
1032 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
1033 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
1034 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
1035 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
1036 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
1037 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
1038 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
1039 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
1040 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
1041 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
1042 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
1043 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
1044 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
1045 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
1046 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
1047 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
1048 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
1049 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
1052 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
1054 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
1055 const Date
& d
= wn
.date
;
1057 wxDateTime dt
= d
.DT();
1059 wxDateTime::wxDateTime_t
1060 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
1061 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
1062 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
1063 dnum
= dt
.GetDayOfYear();
1065 printf("%s: the day number is %d",
1066 d
.FormatDate().c_str(), dnum
);
1067 if ( dnum
== wn
.dnum
)
1073 printf(" (ERROR: should be %d)", wn
.dnum
);
1076 printf(", week in month is %d", wmon
);
1077 if ( wmon
== wn
.wmon
)
1083 printf(" (ERROR: should be %d)", wn
.wmon
);
1086 printf(" or %d", wmon2
);
1087 if ( wmon2
== wn
.wmon2
)
1093 printf(" (ERROR: should be %d)", wn
.wmon2
);
1096 printf(", week in year is %d", week
);
1097 if ( week
== wn
.week
)
1103 printf(" (ERROR: should be %d)\n", wn
.week
);
1108 // test DST calculations
1109 static void TestTimeDST()
1111 puts("\n*** wxDateTime DST test ***");
1113 printf("DST is%s in effect now.\n\n",
1114 wxDateTime::Now().IsDST() ? "" : " not");
1116 // taken from http://www.energy.ca.gov/daylightsaving.html
1117 static const Date datesDST
[2][2004 - 1900 + 1] =
1120 { 1, wxDateTime::Apr
, 1990 },
1121 { 7, wxDateTime::Apr
, 1991 },
1122 { 5, wxDateTime::Apr
, 1992 },
1123 { 4, wxDateTime::Apr
, 1993 },
1124 { 3, wxDateTime::Apr
, 1994 },
1125 { 2, wxDateTime::Apr
, 1995 },
1126 { 7, wxDateTime::Apr
, 1996 },
1127 { 6, wxDateTime::Apr
, 1997 },
1128 { 5, wxDateTime::Apr
, 1998 },
1129 { 4, wxDateTime::Apr
, 1999 },
1130 { 2, wxDateTime::Apr
, 2000 },
1131 { 1, wxDateTime::Apr
, 2001 },
1132 { 7, wxDateTime::Apr
, 2002 },
1133 { 6, wxDateTime::Apr
, 2003 },
1134 { 4, wxDateTime::Apr
, 2004 },
1137 { 28, wxDateTime::Oct
, 1990 },
1138 { 27, wxDateTime::Oct
, 1991 },
1139 { 25, wxDateTime::Oct
, 1992 },
1140 { 31, wxDateTime::Oct
, 1993 },
1141 { 30, wxDateTime::Oct
, 1994 },
1142 { 29, wxDateTime::Oct
, 1995 },
1143 { 27, wxDateTime::Oct
, 1996 },
1144 { 26, wxDateTime::Oct
, 1997 },
1145 { 25, wxDateTime::Oct
, 1998 },
1146 { 31, wxDateTime::Oct
, 1999 },
1147 { 29, wxDateTime::Oct
, 2000 },
1148 { 28, wxDateTime::Oct
, 2001 },
1149 { 27, wxDateTime::Oct
, 2002 },
1150 { 26, wxDateTime::Oct
, 2003 },
1151 { 31, wxDateTime::Oct
, 2004 },
1156 for ( year
= 1990; year
< 2005; year
++ )
1158 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
1159 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
1161 printf("DST period in the US for year %d: from %s to %s",
1162 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
1164 size_t n
= year
- 1990;
1165 const Date
& dBegin
= datesDST
[0][n
];
1166 const Date
& dEnd
= datesDST
[1][n
];
1168 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
1174 printf(" (ERROR: should be %s %d to %s %d)\n",
1175 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
1176 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
1182 for ( year
= 1990; year
< 2005; year
++ )
1184 printf("DST period in Europe for year %d: from %s to %s\n",
1186 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
1187 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
1191 // test wxDateTime -> text conversion
1192 static void TestTimeFormat()
1194 puts("\n*** wxDateTime formatting test ***");
1196 // some information may be lost during conversion, so store what kind
1197 // of info should we recover after a round trip
1200 CompareNone
, // don't try comparing
1201 CompareBoth
, // dates and times should be identical
1202 CompareDate
, // dates only
1203 CompareTime
// time only
1208 CompareKind compareKind
;
1210 } formatTestFormats
[] =
1212 { CompareBoth
, "---> %c" },
1213 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
1214 { CompareBoth
, "Date is %x, time is %X" },
1215 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
1216 { CompareNone
, "The day of year: %j, the week of year: %W" },
1219 static const Date formatTestDates
[] =
1221 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
1222 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
1224 // this test can't work for other centuries because it uses two digit
1225 // years in formats, so don't even try it
1226 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
1227 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
1228 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
1232 // an extra test (as it doesn't depend on date, don't do it in the loop)
1233 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
1235 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
1239 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
1240 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
1242 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
1243 printf("%s", s
.c_str());
1245 // what can we recover?
1246 int kind
= formatTestFormats
[n
].compareKind
;
1250 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
1253 // converion failed - should it have?
1254 if ( kind
== CompareNone
)
1257 puts(" (ERROR: conversion back failed)");
1261 // should have parsed the entire string
1262 puts(" (ERROR: conversion back stopped too soon)");
1266 bool equal
= FALSE
; // suppress compilaer warning
1274 equal
= dt
.IsSameDate(dt2
);
1278 equal
= dt
.IsSameTime(dt2
);
1284 printf(" (ERROR: got back '%s' instead of '%s')\n",
1285 dt2
.Format().c_str(), dt
.Format().c_str());
1296 // test text -> wxDateTime conversion
1297 static void TestTimeParse()
1299 puts("\n*** wxDateTime parse test ***");
1301 struct ParseTestData
1308 static const ParseTestData parseTestDates
[] =
1310 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
1311 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
1314 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
1316 const char *format
= parseTestDates
[n
].format
;
1318 printf("%s => ", format
);
1321 if ( dt
.ParseRfc822Date(format
) )
1323 printf("%s ", dt
.Format().c_str());
1325 if ( parseTestDates
[n
].good
)
1327 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
1334 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
1339 puts("(ERROR: bad format)");
1344 printf("bad format (%s)\n",
1345 parseTestDates
[n
].good
? "ERROR" : "ok");
1350 static void TestInteractive()
1352 puts("\n*** interactive wxDateTime tests ***");
1358 printf("Enter a date: ");
1359 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
1363 if ( !dt
.ParseDate(buf
) )
1365 puts("failed to parse the date");
1370 printf("%s: day %u, week of month %u/%u, week of year %u\n",
1371 dt
.FormatISODate().c_str(),
1373 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
1374 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
1375 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
1378 puts("\n*** done ***");
1381 static void TestTimeArithmetics()
1383 puts("\n*** testing arithmetic operations on wxDateTime ***");
1389 } testArithmData
[] =
1391 { wxDateSpan::Day(), "day" },
1392 { wxDateSpan::Week(), "week" },
1393 { wxDateSpan::Month(), "month" },
1394 { wxDateSpan::Year(), "year" },
1395 { wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days" },
1398 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
1400 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
1402 wxDateSpan span
= testArithmData
[n
].span
;
1406 const char *name
= testArithmData
[n
].name
;
1407 printf("%s + %s = %s, %s - %s = %s\n",
1408 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
1409 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
1411 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
1412 if ( dt1
- span
== dt
)
1418 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
1421 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
1422 if ( dt2
+ span
== dt
)
1428 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
1431 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
1432 if ( dt2
+ 2*span
== dt1
)
1438 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
1445 static void TestTimeHolidays()
1447 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
1449 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
1450 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
1451 dtEnd
= dtStart
.GetLastMonthDay();
1453 wxDateTimeArray hol
;
1454 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
1456 const wxChar
*format
= "%d-%b-%Y (%a)";
1458 printf("All holidays between %s and %s:\n",
1459 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
1461 size_t count
= hol
.GetCount();
1462 for ( size_t n
= 0; n
< count
; n
++ )
1464 printf("\t%s\n", hol
[n
].Format(format
).c_str());
1472 // test compatibility with the old wxDate/wxTime classes
1473 static void TestTimeCompatibility()
1475 puts("\n*** wxDateTime compatibility test ***");
1477 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
1478 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
1480 double jdnNow
= wxDateTime::Now().GetJDN();
1481 long jdnMidnight
= (long)(jdnNow
- 0.5);
1482 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
1484 jdnMidnight
= wxDate().Set().GetJulianDate();
1485 printf("wxDateTime for today: %s\n",
1486 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
1488 int flags
= wxEUROPEAN
;//wxFULL;
1491 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
1492 for ( int n
= 0; n
< 7; n
++ )
1494 printf("Previous %s is %s\n",
1495 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
1496 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
1504 // ----------------------------------------------------------------------------
1506 // ----------------------------------------------------------------------------
1510 #include <wx/thread.h>
1512 static size_t gs_counter
= (size_t)-1;
1513 static wxCriticalSection gs_critsect
;
1514 static wxCondition gs_cond
;
1516 class MyJoinableThread
: public wxThread
1519 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
1520 { m_n
= n
; Create(); }
1522 // thread execution starts here
1523 virtual ExitCode
Entry();
1529 wxThread::ExitCode
MyJoinableThread::Entry()
1531 unsigned long res
= 1;
1532 for ( size_t n
= 1; n
< m_n
; n
++ )
1536 // it's a loooong calculation :-)
1540 return (ExitCode
)res
;
1543 class MyDetachedThread
: public wxThread
1546 MyDetachedThread(size_t n
, char ch
)
1550 m_cancelled
= FALSE
;
1555 // thread execution starts here
1556 virtual ExitCode
Entry();
1559 virtual void OnExit();
1562 size_t m_n
; // number of characters to write
1563 char m_ch
; // character to write
1565 bool m_cancelled
; // FALSE if we exit normally
1568 wxThread::ExitCode
MyDetachedThread::Entry()
1571 wxCriticalSectionLocker
lock(gs_critsect
);
1572 if ( gs_counter
== (size_t)-1 )
1578 for ( size_t n
= 0; n
< m_n
; n
++ )
1580 if ( TestDestroy() )
1590 wxThread::Sleep(100);
1596 void MyDetachedThread::OnExit()
1598 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
1600 wxCriticalSectionLocker
lock(gs_critsect
);
1601 if ( !--gs_counter
&& !m_cancelled
)
1605 void TestDetachedThreads()
1607 puts("\n*** Testing detached threads ***");
1609 static const size_t nThreads
= 3;
1610 MyDetachedThread
*threads
[nThreads
];
1612 for ( n
= 0; n
< nThreads
; n
++ )
1614 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
1617 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
1618 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
1620 for ( n
= 0; n
< nThreads
; n
++ )
1625 // wait until all threads terminate
1631 void TestJoinableThreads()
1633 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
1635 // calc 10! in the background
1636 MyJoinableThread
thread(10);
1639 printf("\nThread terminated with exit code %lu.\n",
1640 (unsigned long)thread
.Wait());
1643 void TestThreadSuspend()
1645 puts("\n*** Testing thread suspend/resume functions ***");
1647 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
1651 // this is for this demo only, in a real life program we'd use another
1652 // condition variable which would be signaled from wxThread::Entry() to
1653 // tell us that the thread really started running - but here just wait a
1654 // bit and hope that it will be enough (the problem is, of course, that
1655 // the thread might still not run when we call Pause() which will result
1657 wxThread::Sleep(300);
1659 for ( size_t n
= 0; n
< 3; n
++ )
1663 puts("\nThread suspended");
1666 // don't sleep but resume immediately the first time
1667 wxThread::Sleep(300);
1669 puts("Going to resume the thread");
1674 puts("Waiting until it terminates now");
1676 // wait until the thread terminates
1682 void TestThreadDelete()
1684 // As above, using Sleep() is only for testing here - we must use some
1685 // synchronisation object instead to ensure that the thread is still
1686 // running when we delete it - deleting a detached thread which already
1687 // terminated will lead to a crash!
1689 puts("\n*** Testing thread delete function ***");
1691 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
1695 puts("\nDeleted a thread which didn't start to run yet.");
1697 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
1701 wxThread::Sleep(300);
1705 puts("\nDeleted a running thread.");
1707 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
1711 wxThread::Sleep(300);
1717 puts("\nDeleted a sleeping thread.");
1719 MyJoinableThread
thread3(20);
1724 puts("\nDeleted a joinable thread.");
1726 MyJoinableThread
thread4(2);
1729 wxThread::Sleep(300);
1733 puts("\nDeleted a joinable thread which already terminated.");
1738 #endif // TEST_THREADS
1740 // ----------------------------------------------------------------------------
1742 // ----------------------------------------------------------------------------
1746 void PrintArray(const char* name
, const wxArrayString
& array
)
1748 printf("Dump of the array '%s'\n", name
);
1750 size_t nCount
= array
.GetCount();
1751 for ( size_t n
= 0; n
< nCount
; n
++ )
1753 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
1757 #endif // TEST_ARRAYS
1759 // ----------------------------------------------------------------------------
1761 // ----------------------------------------------------------------------------
1765 #include "wx/timer.h"
1766 #include "wx/tokenzr.h"
1768 static void TestStringConstruction()
1770 puts("*** Testing wxString constructores ***");
1772 #define TEST_CTOR(args, res) \
1775 printf("wxString%s = %s ", #args, s.c_str()); \
1782 printf("(ERROR: should be %s)\n", res); \
1786 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
1787 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
1788 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
1789 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
1791 static const wxChar
*s
= _T("?really!");
1792 const wxChar
*start
= wxStrchr(s
, _T('r'));
1793 const wxChar
*end
= wxStrchr(s
, _T('!'));
1794 TEST_CTOR((start
, end
), _T("really"));
1799 static void TestString()
1809 for (int i
= 0; i
< 1000000; ++i
)
1813 c
= "! How'ya doin'?";
1816 c
= "Hello world! What's up?";
1821 printf ("TestString elapsed time: %ld\n", sw
.Time());
1824 static void TestPChar()
1832 for (int i
= 0; i
< 1000000; ++i
)
1834 strcpy (a
, "Hello");
1835 strcpy (b
, " world");
1836 strcpy (c
, "! How'ya doin'?");
1839 strcpy (c
, "Hello world! What's up?");
1840 if (strcmp (c
, a
) == 0)
1844 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
1847 static void TestStringSub()
1849 wxString
s("Hello, world!");
1851 puts("*** Testing wxString substring extraction ***");
1853 printf("String = '%s'\n", s
.c_str());
1854 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
1855 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
1856 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
1857 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
1858 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
1859 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
1864 static void TestStringFormat()
1866 puts("*** Testing wxString formatting ***");
1869 s
.Printf("%03d", 18);
1871 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
1872 printf("Number 18: %s\n", s
.c_str());
1877 // returns "not found" for npos, value for all others
1878 static wxString
PosToString(size_t res
)
1880 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
1881 : wxString::Format(_T("%u"), res
);
1885 static void TestStringFind()
1887 puts("*** Testing wxString find() functions ***");
1889 static const wxChar
*strToFind
= _T("ell");
1890 static const struct StringFindTest
1894 result
; // of searching "ell" in str
1897 { _T("Well, hello world"), 0, 1 },
1898 { _T("Well, hello world"), 6, 7 },
1899 { _T("Well, hello world"), 9, wxString::npos
},
1902 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
1904 const StringFindTest
& ft
= findTestData
[n
];
1905 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
1907 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
1908 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
1910 size_t resTrue
= ft
.result
;
1911 if ( res
== resTrue
)
1917 printf(_T("(ERROR: should be %s)\n"),
1918 PosToString(resTrue
).c_str());
1925 // replace TABs with \t and CRs with \n
1926 static wxString
MakePrintable(const wxChar
*s
)
1929 (void)str
.Replace(_T("\t"), _T("\\t"));
1930 (void)str
.Replace(_T("\n"), _T("\\n"));
1931 (void)str
.Replace(_T("\r"), _T("\\r"));
1936 static void TestStringTokenizer()
1938 puts("*** Testing wxStringTokenizer ***");
1940 static const wxChar
*modeNames
[] =
1944 _T("return all empty"),
1949 static const struct StringTokenizerTest
1951 const wxChar
*str
; // string to tokenize
1952 const wxChar
*delims
; // delimiters to use
1953 size_t count
; // count of token
1954 wxStringTokenizerMode mode
; // how should we tokenize it
1955 } tokenizerTestData
[] =
1957 { _T(""), _T(" "), 0 },
1958 { _T("Hello, world"), _T(" "), 2 },
1959 { _T("Hello, world "), _T(" "), 2 },
1960 { _T("Hello, world"), _T(","), 2 },
1961 { _T("Hello, world!"), _T(",!"), 2 },
1962 { _T("Hello,, world!"), _T(",!"), 3 },
1963 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
1964 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
1965 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
1966 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
1967 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
1968 { _T("01/02/99"), _T("/-"), 3 },
1969 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
1972 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
1974 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
1975 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
1977 size_t count
= tkz
.CountTokens();
1978 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
1979 MakePrintable(tt
.str
).c_str(),
1981 MakePrintable(tt
.delims
).c_str(),
1982 modeNames
[tkz
.GetMode()]);
1983 if ( count
== tt
.count
)
1989 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
1994 // if we emulate strtok(), check that we do it correctly
1995 wxChar
*buf
, *s
, *last
;
1997 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
1999 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
2000 wxStrcpy(buf
, tt
.str
);
2002 s
= wxStrtok(buf
, tt
.delims
, &last
);
2009 // now show the tokens themselves
2011 while ( tkz
.HasMoreTokens() )
2013 wxString token
= tkz
.GetNextToken();
2015 printf(_T("\ttoken %u: '%s'"),
2017 MakePrintable(token
).c_str());
2027 printf(" (ERROR: should be %s)\n", s
);
2030 s
= wxStrtok(NULL
, tt
.delims
, &last
);
2034 // nothing to compare with
2039 if ( count2
!= count
)
2041 puts(_T("\tERROR: token count mismatch"));
2050 #endif // TEST_STRINGS
2052 // ----------------------------------------------------------------------------
2054 // ----------------------------------------------------------------------------
2056 int main(int argc
, char **argv
)
2058 if ( !wxInitialize() )
2060 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
2064 puts("Sleeping for 3 seconds... z-z-z-z-z...");
2066 #endif // TEST_USLEEP
2069 static const wxCmdLineEntryDesc cmdLineDesc
[] =
2071 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
2072 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
2074 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
2075 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
2076 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
2077 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
2079 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
2080 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
2085 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
2087 switch ( parser
.Parse() )
2090 wxLogMessage("Help was given, terminating.");
2094 ShowCmdLine(parser
);
2098 wxLogMessage("Syntax error detected, aborting.");
2101 #endif // TEST_CMDLINE
2111 TestStringConstruction();
2115 TestStringTokenizer();
2117 #endif // TEST_STRINGS
2128 puts("*** Initially:");
2130 PrintArray("a1", a1
);
2132 wxArrayString
a2(a1
);
2133 PrintArray("a2", a2
);
2135 wxSortedArrayString
a3(a1
);
2136 PrintArray("a3", a3
);
2138 puts("*** After deleting a string from a1");
2141 PrintArray("a1", a1
);
2142 PrintArray("a2", a2
);
2143 PrintArray("a3", a3
);
2145 puts("*** After reassigning a1 to a2 and a3");
2147 PrintArray("a2", a2
);
2148 PrintArray("a3", a3
);
2149 #endif // TEST_ARRAYS
2157 #endif // TEST_EXECUTE
2159 #ifdef TEST_FILECONF
2161 #endif // TEST_FILECONF
2165 for ( size_t n
= 0; n
< 8000; n
++ )
2167 s
<< (char)('A' + (n
% 26));
2171 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
2173 // this one shouldn't be truncated
2176 // but this one will because log functions use fixed size buffer
2177 // (note that it doesn't need '\n' at the end neither - will be added
2179 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
2183 int nCPUs
= wxThread::GetCPUCount();
2184 printf("This system has %d CPUs\n", nCPUs
);
2186 wxThread::SetConcurrency(nCPUs
);
2188 if ( argc
> 1 && argv
[1][0] == 't' )
2189 wxLog::AddTraceMask("thread");
2192 TestDetachedThreads();
2194 TestJoinableThreads();
2196 TestThreadSuspend();
2200 #endif // TEST_THREADS
2202 #ifdef TEST_LONGLONG
2203 // seed pseudo random generator
2204 srand((unsigned)time(NULL
));
2210 TestMultiplication();
2215 TestLongLongConversion();
2216 TestBitOperations();
2218 #endif // TEST_LONGLONG
2238 TestTimeArithmetics();