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 ***");
363 printf("Current time:\t%s\n", wxDateTime::Now().Format().c_str());
364 printf("Unix epoch:\t%s\n", wxDateTime((time_t)0).Format().c_str());
365 printf("Today noon:\t%s\n", wxDateTime(12, 0).Format().c_str());
366 printf("May 29, 1976:\t%s\n", wxDateTime(29, wxDateTime::May
, 1976).Format().c_str());
367 printf("Jan 1, 1900:\t%s\n", wxDateTime(1, wxDateTime::Jan
, 1900).Format().c_str());
369 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
371 const Date
& d1
= testDates
[n
];
372 wxDateTime dt
= d1
.DT();
377 wxString s1
= d1
.Format(),
380 printf("Date: %s == %s (%s)\n",
381 s1
.c_str(), s2
.c_str(),
382 s1
== s2
? "ok" : "ERROR");
387 // test time zones stuff
388 static void TestTimeZones()
390 puts("\n*** wxDateTime timezone test ***");
392 wxDateTime now
= wxDateTime::Now();
394 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
395 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
396 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
397 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
398 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
399 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
402 // test some minimal support for the dates outside the standard range
403 static void TestTimeRange()
405 puts("\n*** wxDateTime out-of-standard-range dates test ***");
407 printf("Unix epoch:\t%s\n",
408 wxDateTime(2440587.5).Format().c_str());
409 printf("Feb 29, 0: \t%s\n",
410 wxDateTime(29, wxDateTime::Feb
, 0).Format().c_str());
411 printf("JDN 0: \t%s\n",
412 wxDateTime(0.0).Format().c_str());
413 printf("Jan 1, 1AD:\t%s\n",
414 wxDateTime(1, wxDateTime::Jan
, 1).Format().c_str());
415 printf("May 29, 2099:\t%s\n",
416 wxDateTime(29, wxDateTime::May
, 2099).Format().c_str());
419 static void TestTimeTicks()
421 puts("\n*** wxDateTime ticks test ***");
423 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
425 const Date
& d
= testDates
[n
];
429 wxDateTime dt
= d
.DT();
430 long ticks
= (dt
.GetValue() / 1000).ToLong();
431 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
432 if ( ticks
== d
.ticks
)
438 printf(" (ERROR: should be %ld, delta = %ld)\n",
439 d
.ticks
, ticks
- d
.ticks
);
442 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
443 ticks
= (dt
.GetValue() / 1000).ToLong();
444 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
445 if ( ticks
== d
.gmticks
)
451 printf(" (ERROR: should be %ld, delta = %ld)\n",
452 d
.gmticks
, ticks
- d
.gmticks
);
459 // test conversions to JDN &c
460 static void TestTimeJDN()
462 puts("\n*** wxDateTime to JDN test ***");
464 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
466 const Date
& d
= testDates
[n
];
467 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
468 double jdn
= dt
.GetJulianDayNumber();
470 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
477 printf(" (ERROR: should be %f, delta = %f)\n",
485 // ----------------------------------------------------------------------------
487 // ----------------------------------------------------------------------------
491 #include <wx/thread.h>
493 static size_t gs_counter
= (size_t)-1;
494 static wxCriticalSection gs_critsect
;
495 static wxCondition gs_cond
;
497 class MyJoinableThread
: public wxThread
500 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
501 { m_n
= n
; Create(); }
503 // thread execution starts here
504 virtual ExitCode
Entry();
510 wxThread::ExitCode
MyJoinableThread::Entry()
512 unsigned long res
= 1;
513 for ( size_t n
= 1; n
< m_n
; n
++ )
517 // it's a loooong calculation :-)
521 return (ExitCode
)res
;
524 class MyDetachedThread
: public wxThread
527 MyDetachedThread(size_t n
, char ch
)
536 // thread execution starts here
537 virtual ExitCode
Entry();
540 virtual void OnExit();
543 size_t m_n
; // number of characters to write
544 char m_ch
; // character to write
546 bool m_cancelled
; // FALSE if we exit normally
549 wxThread::ExitCode
MyDetachedThread::Entry()
552 wxCriticalSectionLocker
lock(gs_critsect
);
553 if ( gs_counter
== (size_t)-1 )
559 for ( size_t n
= 0; n
< m_n
; n
++ )
571 wxThread::Sleep(100);
577 void MyDetachedThread::OnExit()
579 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
581 wxCriticalSectionLocker
lock(gs_critsect
);
582 if ( !--gs_counter
&& !m_cancelled
)
586 void TestDetachedThreads()
588 puts("\n*** Testing detached threads ***");
590 static const size_t nThreads
= 3;
591 MyDetachedThread
*threads
[nThreads
];
593 for ( n
= 0; n
< nThreads
; n
++ )
595 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
598 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
599 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
601 for ( n
= 0; n
< nThreads
; n
++ )
606 // wait until all threads terminate
612 void TestJoinableThreads()
614 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
616 // calc 10! in the background
617 MyJoinableThread
thread(10);
620 printf("\nThread terminated with exit code %lu.\n",
621 (unsigned long)thread
.Wait());
624 void TestThreadSuspend()
626 puts("\n*** Testing thread suspend/resume functions ***");
628 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
632 // this is for this demo only, in a real life program we'd use another
633 // condition variable which would be signaled from wxThread::Entry() to
634 // tell us that the thread really started running - but here just wait a
635 // bit and hope that it will be enough (the problem is, of course, that
636 // the thread might still not run when we call Pause() which will result
638 wxThread::Sleep(300);
640 for ( size_t n
= 0; n
< 3; n
++ )
644 puts("\nThread suspended");
647 // don't sleep but resume immediately the first time
648 wxThread::Sleep(300);
650 puts("Going to resume the thread");
655 puts("Waiting until it terminates now");
657 // wait until the thread terminates
663 void TestThreadDelete()
665 // As above, using Sleep() is only for testing here - we must use some
666 // synchronisation object instead to ensure that the thread is still
667 // running when we delete it - deleting a detached thread which already
668 // terminated will lead to a crash!
670 puts("\n*** Testing thread delete function ***");
672 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
676 puts("\nDeleted a thread which didn't start to run yet.");
678 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
682 wxThread::Sleep(300);
686 puts("\nDeleted a running thread.");
688 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
692 wxThread::Sleep(300);
698 puts("\nDeleted a sleeping thread.");
700 MyJoinableThread
thread3(20);
705 puts("\nDeleted a joinable thread.");
707 MyJoinableThread
thread4(2);
710 wxThread::Sleep(300);
714 puts("\nDeleted a joinable thread which already terminated.");
719 #endif // TEST_THREADS
721 // ----------------------------------------------------------------------------
723 // ----------------------------------------------------------------------------
727 void PrintArray(const char* name
, const wxArrayString
& array
)
729 printf("Dump of the array '%s'\n", name
);
731 size_t nCount
= array
.GetCount();
732 for ( size_t n
= 0; n
< nCount
; n
++ )
734 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
738 #endif // TEST_ARRAYS
740 // ----------------------------------------------------------------------------
742 // ----------------------------------------------------------------------------
746 #include "wx/timer.h"
748 static void TestString()
758 for (int i
= 0; i
< 1000000; ++i
)
762 c
= "! How'ya doin'?";
765 c
= "Hello world! What's up?";
770 printf ("TestString elapsed time: %ld\n", sw
.Time());
773 static void TestPChar()
781 for (int i
= 0; i
< 1000000; ++i
)
784 strcpy (b
, " world");
785 strcpy (c
, "! How'ya doin'?");
788 strcpy (c
, "Hello world! What's up?");
789 if (strcmp (c
, a
) == 0)
793 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
796 static void TestStringSub()
798 wxString
s("Hello, world!");
800 puts("*** Testing wxString substring extraction ***");
802 printf("String = '%s'\n", s
.c_str());
803 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
804 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
805 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
806 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
807 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
808 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
813 #endif // TEST_STRINGS
815 // ----------------------------------------------------------------------------
817 // ----------------------------------------------------------------------------
819 int main(int argc
, char **argv
)
821 if ( !wxInitialize() )
823 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
833 #endif // TEST_STRINGS
844 puts("*** Initially:");
846 PrintArray("a1", a1
);
848 wxArrayString
a2(a1
);
849 PrintArray("a2", a2
);
851 wxSortedArrayString
a3(a1
);
852 PrintArray("a3", a3
);
854 puts("*** After deleting a string from a1");
857 PrintArray("a1", a1
);
858 PrintArray("a2", a2
);
859 PrintArray("a3", a3
);
861 puts("*** After reassigning a1 to a2 and a3");
863 PrintArray("a2", a2
);
864 PrintArray("a3", a3
);
865 #endif // TEST_ARRAYS
873 for ( size_t n
= 0; n
< 8000; n
++ )
875 s
<< (char)('A' + (n
% 26));
879 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
881 // this one shouldn't be truncated
884 // but this one will because log functions use fixed size buffer
885 // (note that it doesn't need '\n' at the end neither - will be added
887 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
891 int nCPUs
= wxThread::GetCPUCount();
892 printf("This system has %d CPUs\n", nCPUs
);
894 wxThread::SetConcurrency(nCPUs
);
896 if ( argc
> 1 && argv
[1][0] == 't' )
897 wxLog::AddTraceMask("thread");
900 TestDetachedThreads();
902 TestJoinableThreads();
908 #endif // TEST_THREADS
915 #endif // TEST_LONGLONG