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 // ----------------------------------------------------------------------------
36 //#define TEST_STRINGS
37 //#define TEST_THREADS
39 //#define TEST_LONGLONG
41 // ============================================================================
43 // ============================================================================
45 // ----------------------------------------------------------------------------
47 // ----------------------------------------------------------------------------
53 static void TestDirEnumHelper(wxDir
& dir
,
54 int flags
= wxDIR_DEFAULT
,
55 const wxString
& filespec
= wxEmptyString
)
59 if ( !dir
.IsOpened() )
62 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
65 printf("\t%s\n", filename
.c_str());
67 cont
= dir
.GetNext(&filename
);
73 static void TestDirEnum()
75 wxDir
dir(wxGetCwd());
77 puts("Enumerating everything in current directory:");
78 TestDirEnumHelper(dir
);
80 puts("Enumerating really everything in current directory:");
81 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
83 puts("Enumerating object files in current directory:");
84 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
86 puts("Enumerating directories in current directory:");
87 TestDirEnumHelper(dir
, wxDIR_DIRS
);
89 puts("Enumerating files in current directory:");
90 TestDirEnumHelper(dir
, wxDIR_FILES
);
92 puts("Enumerating files including hidden in current directory:");
93 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
97 #elif defined(__WXMSW__)
100 #error "don't know where the root directory is"
103 puts("Enumerating everything in root directory:");
104 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
106 puts("Enumerating directories in root directory:");
107 TestDirEnumHelper(dir
, wxDIR_DIRS
);
109 puts("Enumerating files in root directory:");
110 TestDirEnumHelper(dir
, wxDIR_FILES
);
112 puts("Enumerating files including hidden in root directory:");
113 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
115 puts("Enumerating files in non existing directory:");
116 wxDir
dirNo("nosuchdir");
117 TestDirEnumHelper(dirNo
);
122 // ----------------------------------------------------------------------------
124 // ----------------------------------------------------------------------------
128 #include <wx/mimetype.h>
130 static void TestMimeEnum()
132 wxMimeTypesManager mimeTM
;
133 wxArrayString mimetypes
;
135 size_t count
= mimeTM
.EnumAllFileTypes(mimetypes
);
137 printf("*** All %u known filetypes: ***\n", count
);
142 for ( size_t n
= 0; n
< count
; n
++ )
144 wxFileType
*filetype
= mimeTM
.GetFileTypeFromMimeType(mimetypes
[n
]);
147 printf("nothing known about the filetype '%s'!\n",
148 mimetypes
[n
].c_str());
152 filetype
->GetDescription(&desc
);
153 filetype
->GetExtensions(exts
);
155 filetype
->GetIcon(NULL
);
158 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
165 printf("\t%s: %s (%s)\n",
166 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
178 #include <wx/longlong.h>
179 #include <wx/timer.h>
181 static void TestSpeed()
183 static const long max
= 100000000;
190 for ( n
= 0; n
< max
; n
++ )
195 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
202 for ( n
= 0; n
< max
; n
++ )
207 printf("Summing __int64s took %ld milliseconds.\n", sw
.Time());
214 for ( n
= 0; n
< max
; n
++ )
219 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
223 static void TestDivision()
225 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
227 // seed pseudo random generator
228 //srand((unsigned)time(NULL));
231 for ( size_t n
= 0; n
< 10000; n
++ )
233 // get a random wxLongLong (shifting by 12 the MSB ensures that the
234 // multiplication will not overflow)
235 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
237 wxASSERT( (ll
* 1000l)/1000l == ll
);
242 printf("\n*** Tested %u divisions/multiplications: ok\n", nTested
);
247 #endif // TEST_LONGLONG
249 // ----------------------------------------------------------------------------
251 // ----------------------------------------------------------------------------
255 #include <wx/datetime.h>
260 wxDateTime::wxDateTime_t day
;
261 wxDateTime::Month month
;
263 wxDateTime::wxDateTime_t hour
, min
, sec
;
265 time_t gmticks
, ticks
;
267 void Init(const wxDateTime::Tm
& tm
)
276 gmticks
= ticks
= -1;
279 wxDateTime
DT() const
280 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
282 wxString
Format() const
285 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
287 wxDateTime::GetMonthName(month
).c_str(),
289 abs(wxDateTime::ConvertYearToBC(year
)),
290 year
> 0 ? "AD" : "BC");
295 static const Date testDates
[] =
297 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, 0, -3600 },
298 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, -1, -1 },
299 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, 202219200, 202212000 },
300 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, 194400000, 194396400 },
301 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, -1, -1 },
302 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, -1, -1 },
303 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, -1, -1 },
304 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, -1, -1 },
305 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, -1, -1 },
306 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, -1, -1 },
307 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, -1, -1 },
308 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, -1, -1 },
309 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, -1, -1 },
310 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, -1, -1 },
311 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, -1, -1 },
314 // this test miscellaneous static wxDateTime functions
315 static void TestTimeStatic()
317 puts("\n*** wxDateTime static methods test ***");
319 // some info about the current date
320 int year
= wxDateTime::GetCurrentYear();
321 printf("Current year %d is %sa leap one and has %d days.\n",
323 wxDateTime::IsLeapYear(year
) ? "" : "not ",
324 wxDateTime::GetNumberOfDays(year
));
326 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
327 printf("Current month is '%s' ('%s') and it has %d days\n",
328 wxDateTime::GetMonthName(month
, TRUE
).c_str(),
329 wxDateTime::GetMonthName(month
).c_str(),
330 wxDateTime::GetNumberOfDays(month
));
333 static const size_t nYears
= 5;
334 static const size_t years
[2][nYears
] =
336 // first line: the years to test
337 { 1990, 1976, 2000, 2030, 1984, },
339 // second line: TRUE if leap, FALSE otherwise
340 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
343 for ( size_t n
= 0; n
< nYears
; n
++ )
345 int year
= years
[0][n
];
346 bool should
= years
[1][n
] != 0;
348 printf("Year %d is %sa leap year (should be: %s)\n",
350 wxDateTime::IsLeapYear(year
) ? "" : "not ",
351 should
? "yes" : "no");
353 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
357 // test constructing wxDateTime objects
358 static void TestTimeSet()
360 puts("\n*** wxDateTime construction test ***");
362 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
364 const Date
& d1
= testDates
[n
];
365 wxDateTime dt
= d1
.DT();
370 wxString s1
= d1
.Format(),
373 printf("Date: %s == %s (%s)\n",
374 s1
.c_str(), s2
.c_str(),
375 s1
== s2
? "ok" : "ERROR");
379 // test time zones stuff
380 static void TestTimeZones()
382 puts("\n*** wxDateTime timezone test ***");
384 wxDateTime now
= wxDateTime::Now();
386 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
387 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
388 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
389 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
390 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
391 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
394 // test some minimal support for the dates outside the standard range
395 static void TestTimeRange()
397 puts("\n*** wxDateTime out-of-standard-range dates test ***");
399 printf("Unix epoch:\t%s\n",
400 wxDateTime(2440587.5).Format().c_str());
401 printf("Feb 29, 0: \t%s\n",
402 wxDateTime(29, wxDateTime::Feb
, 0).Format().c_str());
403 printf("JDN 0: \t%s\n",
404 wxDateTime(0.0).Format().c_str());
405 printf("Jan 1, 1AD:\t%s\n",
406 wxDateTime(1, wxDateTime::Jan
, 1).Format().c_str());
407 printf("May 29, 2099:\t%s\n",
408 wxDateTime(29, wxDateTime::May
, 2099).Format().c_str());
411 static void TestTimeTicks()
413 puts("\n*** wxDateTime ticks test ***");
415 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
417 const Date
& d
= testDates
[n
];
421 wxDateTime dt
= d
.DT();
422 long ticks
= (dt
.GetValue() / 1000).ToLong();
423 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
424 if ( ticks
== d
.ticks
)
430 printf(" (ERROR: should be %ld, delta = %ld)\n",
431 d
.ticks
, ticks
- d
.ticks
);
434 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
435 ticks
= (dt
.GetValue() / 1000).ToLong();
436 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
437 if ( ticks
== d
.gmticks
)
443 printf(" (ERROR: should be %ld, delta = %ld)\n",
444 d
.gmticks
, ticks
- d
.gmticks
);
451 // test conversions to JDN &c
452 static void TestTimeJDN()
454 puts("\n*** wxDateTime to JDN test ***");
456 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
458 const Date
& d
= testDates
[n
];
459 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
460 double jdn
= dt
.GetJulianDayNumber();
462 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
469 printf(" (ERROR: should be %f, delta = %f)\n",
477 // ----------------------------------------------------------------------------
479 // ----------------------------------------------------------------------------
483 #include <wx/thread.h>
485 static size_t gs_counter
= (size_t)-1;
486 static wxCriticalSection gs_critsect
;
487 static wxCondition gs_cond
;
489 class MyJoinableThread
: public wxThread
492 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
493 { m_n
= n
; Create(); }
495 // thread execution starts here
496 virtual ExitCode
Entry();
502 wxThread::ExitCode
MyJoinableThread::Entry()
504 unsigned long res
= 1;
505 for ( size_t n
= 1; n
< m_n
; n
++ )
509 // it's a loooong calculation :-)
513 return (ExitCode
)res
;
516 class MyDetachedThread
: public wxThread
519 MyDetachedThread(size_t n
, char ch
)
528 // thread execution starts here
529 virtual ExitCode
Entry();
532 virtual void OnExit();
535 size_t m_n
; // number of characters to write
536 char m_ch
; // character to write
538 bool m_cancelled
; // FALSE if we exit normally
541 wxThread::ExitCode
MyDetachedThread::Entry()
544 wxCriticalSectionLocker
lock(gs_critsect
);
545 if ( gs_counter
== (size_t)-1 )
551 for ( size_t n
= 0; n
< m_n
; n
++ )
563 wxThread::Sleep(100);
569 void MyDetachedThread::OnExit()
571 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
573 wxCriticalSectionLocker
lock(gs_critsect
);
574 if ( !--gs_counter
&& !m_cancelled
)
578 void TestDetachedThreads()
580 puts("\n*** Testing detached threads ***");
582 static const size_t nThreads
= 3;
583 MyDetachedThread
*threads
[nThreads
];
585 for ( n
= 0; n
< nThreads
; n
++ )
587 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
590 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
591 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
593 for ( n
= 0; n
< nThreads
; n
++ )
598 // wait until all threads terminate
604 void TestJoinableThreads()
606 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
608 // calc 10! in the background
609 MyJoinableThread
thread(10);
612 printf("\nThread terminated with exit code %lu.\n",
613 (unsigned long)thread
.Wait());
616 void TestThreadSuspend()
618 puts("\n*** Testing thread suspend/resume functions ***");
620 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
624 // this is for this demo only, in a real life program we'd use another
625 // condition variable which would be signaled from wxThread::Entry() to
626 // tell us that the thread really started running - but here just wait a
627 // bit and hope that it will be enough (the problem is, of course, that
628 // the thread might still not run when we call Pause() which will result
630 wxThread::Sleep(300);
632 for ( size_t n
= 0; n
< 3; n
++ )
636 puts("\nThread suspended");
639 // don't sleep but resume immediately the first time
640 wxThread::Sleep(300);
642 puts("Going to resume the thread");
647 puts("Waiting until it terminates now");
649 // wait until the thread terminates
655 void TestThreadDelete()
657 // As above, using Sleep() is only for testing here - we must use some
658 // synchronisation object instead to ensure that the thread is still
659 // running when we delete it - deleting a detached thread which already
660 // terminated will lead to a crash!
662 puts("\n*** Testing thread delete function ***");
664 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
668 puts("\nDeleted a thread which didn't start to run yet.");
670 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
674 wxThread::Sleep(300);
678 puts("\nDeleted a running thread.");
680 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
684 wxThread::Sleep(300);
690 puts("\nDeleted a sleeping thread.");
692 MyJoinableThread
thread3(20);
697 puts("\nDeleted a joinable thread.");
699 MyJoinableThread
thread4(2);
702 wxThread::Sleep(300);
706 puts("\nDeleted a joinable thread which already terminated.");
711 #endif // TEST_THREADS
713 // ----------------------------------------------------------------------------
715 // ----------------------------------------------------------------------------
719 void PrintArray(const char* name
, const wxArrayString
& array
)
721 printf("Dump of the array '%s'\n", name
);
723 size_t nCount
= array
.GetCount();
724 for ( size_t n
= 0; n
< nCount
; n
++ )
726 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
730 #endif // TEST_ARRAYS
732 // ----------------------------------------------------------------------------
734 // ----------------------------------------------------------------------------
738 #include "wx/timer.h"
740 static void TestString()
750 for (int i
= 0; i
< 1000000; ++i
)
754 c
= "! How'ya doin'?";
757 c
= "Hello world! What's up?";
762 printf ("TestString elapsed time: %ld\n", sw
.Time());
765 static void TestPChar()
773 for (int i
= 0; i
< 1000000; ++i
)
776 strcpy (b
, " world");
777 strcpy (c
, "! How'ya doin'?");
780 strcpy (c
, "Hello world! What's up?");
781 if (strcmp (c
, a
) == 0)
785 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
788 static void TestStringSub()
790 wxString
s("Hello, world!");
792 puts("*** Testing wxString substring extraction ***");
794 printf("String = '%s'\n", s
.c_str());
795 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
796 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
797 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
798 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
799 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
800 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
805 #endif // TEST_STRINGS
807 // ----------------------------------------------------------------------------
809 // ----------------------------------------------------------------------------
811 int main(int argc
, char **argv
)
813 if ( !wxInitialize() )
815 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
825 #endif // TEST_STRINGS
836 puts("*** Initially:");
838 PrintArray("a1", a1
);
840 wxArrayString
a2(a1
);
841 PrintArray("a2", a2
);
843 wxSortedArrayString
a3(a1
);
844 PrintArray("a3", a3
);
846 puts("*** After deleting a string from a1");
849 PrintArray("a1", a1
);
850 PrintArray("a2", a2
);
851 PrintArray("a3", a3
);
853 puts("*** After reassigning a1 to a2 and a3");
855 PrintArray("a2", a2
);
856 PrintArray("a3", a3
);
857 #endif // TEST_ARRAYS
865 for ( size_t n
= 0; n
< 8000; n
++ )
867 s
<< (char)('A' + (n
% 26));
871 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
873 // this one shouldn't be truncated
876 // but this one will because log functions use fixed size buffer
877 // (note that it doesn't need '\n' at the end neither - will be added
879 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
883 int nCPUs
= wxThread::GetCPUCount();
884 printf("This system has %d CPUs\n", nCPUs
);
886 wxThread::SetConcurrency(nCPUs
);
888 if ( argc
> 1 && argv
[1][0] == 't' )
889 wxLog::AddTraceMask("thread");
892 TestDetachedThreads();
894 TestJoinableThreads();
900 #endif // TEST_THREADS
907 #endif // TEST_LONGLONG