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
);
156 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
163 printf("\t%s: %s (%s)\n",
164 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
170 // ----------------------------------------------------------------------------
172 // ----------------------------------------------------------------------------
176 #include <wx/longlong.h>
177 #include <wx/timer.h>
179 static void TestSpeed()
181 static const long max
= 100000000;
188 for ( n
= 0; n
< max
; n
++ )
193 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
200 for ( n
= 0; n
< max
; n
++ )
205 printf("Summing __int64s took %ld milliseconds.\n", sw
.Time());
212 for ( n
= 0; n
< max
; n
++ )
217 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
221 static void TestDivision()
223 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
225 // seed pseudo random generator
226 //srand((unsigned)time(NULL));
229 for ( size_t n
= 0; n
< 10000; n
++ )
231 // get a random wxLongLong (shifting by 12 the MSB ensures that the
232 // multiplication will not overflow)
233 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
235 wxASSERT( (ll
* 1000l)/1000l == ll
);
240 printf("\n*** Tested %u divisions/multiplications: ok\n", nTested
);
245 #endif // TEST_LONGLONG
247 // ----------------------------------------------------------------------------
249 // ----------------------------------------------------------------------------
253 #include <wx/datetime.h>
255 // this test miscellaneous static wxDateTime functions
256 static void TestTimeStatic()
258 puts("\n*** wxDateTime static methods test ***");
260 // some info about the current date
261 int year
= wxDateTime::GetCurrentYear();
262 printf("Current year %d is %sa leap one and has %d days.\n",
264 wxDateTime::IsLeapYear(year
) ? "" : "not ",
265 wxDateTime::GetNumberOfDays(year
));
267 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
268 printf("Current month is '%s' ('%s') and it has %d days\n",
269 wxDateTime::GetMonthName(month
, TRUE
).c_str(),
270 wxDateTime::GetMonthName(month
).c_str(),
271 wxDateTime::GetNumberOfDays(month
));
274 static const size_t nYears
= 5;
275 static const size_t years
[2][nYears
] =
277 // first line: the years to test
278 { 1990, 1976, 2000, 2030, 1984, },
280 // second line: TRUE if leap, FALSE otherwise
281 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
284 for ( size_t n
= 0; n
< nYears
; n
++ )
286 int year
= years
[0][n
];
287 bool should
= years
[1][n
] != 0;
289 printf("Year %d is %sa leap year (should be: %s)\n",
291 wxDateTime::IsLeapYear(year
) ? "" : "not ",
292 should
? "yes" : "no");
294 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
298 // test constructing wxDateTime objects
299 static void TestTimeSet()
301 puts("\n*** wxDateTime construction test ***");
303 printf("Current time:\t%s\n", wxDateTime::Now().Format().c_str());
304 printf("Unix epoch:\t%s\n", wxDateTime((time_t)0).Format().c_str());
305 printf("Today noon:\t%s\n", wxDateTime(12, 0).Format().c_str());
306 printf("May 29, 1976:\t%s\n", wxDateTime(29, wxDateTime::May
, 1976).Format().c_str());
309 // test time zones stuff
310 static void TestTimeZones()
312 puts("\n*** wxDateTime timezone test ***");
314 wxDateTime now
= wxDateTime::Now();
316 printf("Current GMT time:\t%s\n", now
.ToGMT().Format().c_str());
317 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).MakeGMT().Format().c_str());
318 printf("Current time in Paris:\t%s\n", now
.ToTimezone(wxDateTime::CET
).Format().c_str());
319 printf(" Moscow:\t%s\n", now
.ToTimezone(wxDateTime::MSK
).Format().c_str());
320 printf(" New York:\t%s\n", now
.ToTimezone(wxDateTime::EST
).Format().c_str());
323 // test some minimal support for the dates outside the standard range
324 static void TestTimeRange()
326 puts("\n*** wxDateTime out-of-standard-range dates test ***");
328 printf("Unix epoch:\t%s\n",
329 wxDateTime(2440587.5).Format().c_str());
330 printf("Feb 29, 0: \t%s\n",
331 wxDateTime(29, wxDateTime::Feb
, 0).Format().c_str());
332 printf("JDN 0: \t%s\n",
333 wxDateTime(0.0).Format().c_str());
334 printf("Jan 1, 1AD:\t%s\n",
335 wxDateTime(1, wxDateTime::Jan
, 1).Format().c_str());
336 printf("May 29, 2099:\t%s\n",
337 wxDateTime(29, wxDateTime::May
, 2099).Format().c_str());
340 // test conversions to JDN &c
341 static void TestTimeJDN()
343 puts("\n*** wxDateTime to JDN test ***");
347 wxDateTime::wxDateTime_t day
;
348 wxDateTime::Month month
;
353 static const Date testDates
[] =
355 { 21, wxDateTime::Jan
, 2222, 2532648.5 },
356 { 29, wxDateTime::May
, 1976, 2442927.5 },
357 { 1, wxDateTime::Jan
, 1970, 2440587.5 },
358 { 1, wxDateTime::Jan
, 1900, 2415020.5 },
359 { 15, wxDateTime::Oct
, 1582, 2299160.5 },
360 { 4, wxDateTime::Oct
, 1582, 2299149.5 },
361 { 1, wxDateTime::Mar
, 1, 1721484.5 },
362 { 1, wxDateTime::Jan
, 1, 1721425.5 },
363 { 31, wxDateTime::Dec
, 0, 1721424.5 },
364 { 1, wxDateTime::Jan
, 0, 1721059.5 },
365 { 12, wxDateTime::Aug
, -1234, 1270573.5 },
366 { 12, wxDateTime::Aug
, -4000, 260313.5 },
367 { 24, wxDateTime::Nov
, -4713, -0.5 },
370 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
372 const Date
& d
= testDates
[n
];
373 wxDateTime
dt(d
.day
, d
.month
, d
.year
);
374 double jdn
= dt
.GetJulianDayNumber();
376 printf("JDN of %s %02d, %4d%s is:\t%f",
377 wxDateTime::GetMonthName(d
.month
).c_str(),
379 wxDateTime::ConvertYearToBC(d
.year
),
380 d
.year
> 0 ? "AD" : "BC",
388 printf(" (ERROR: should be %f, delta = %f)\n",
396 // ----------------------------------------------------------------------------
398 // ----------------------------------------------------------------------------
402 #include <wx/thread.h>
404 static size_t gs_counter
= (size_t)-1;
405 static wxCriticalSection gs_critsect
;
406 static wxCondition gs_cond
;
408 class MyJoinableThread
: public wxThread
411 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
412 { m_n
= n
; Create(); }
414 // thread execution starts here
415 virtual ExitCode
Entry();
421 wxThread::ExitCode
MyJoinableThread::Entry()
423 unsigned long res
= 1;
424 for ( size_t n
= 1; n
< m_n
; n
++ )
428 // it's a loooong calculation :-)
432 return (ExitCode
)res
;
435 class MyDetachedThread
: public wxThread
438 MyDetachedThread(size_t n
, char ch
)
447 // thread execution starts here
448 virtual ExitCode
Entry();
451 virtual void OnExit();
454 size_t m_n
; // number of characters to write
455 char m_ch
; // character to write
457 bool m_cancelled
; // FALSE if we exit normally
460 wxThread::ExitCode
MyDetachedThread::Entry()
463 wxCriticalSectionLocker
lock(gs_critsect
);
464 if ( gs_counter
== (size_t)-1 )
470 for ( size_t n
= 0; n
< m_n
; n
++ )
482 wxThread::Sleep(100);
488 void MyDetachedThread::OnExit()
490 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
492 wxCriticalSectionLocker
lock(gs_critsect
);
493 if ( !--gs_counter
&& !m_cancelled
)
497 void TestDetachedThreads()
499 puts("\n*** Testing detached threads ***");
501 static const size_t nThreads
= 3;
502 MyDetachedThread
*threads
[nThreads
];
504 for ( n
= 0; n
< nThreads
; n
++ )
506 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
509 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
510 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
512 for ( n
= 0; n
< nThreads
; n
++ )
517 // wait until all threads terminate
523 void TestJoinableThreads()
525 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
527 // calc 10! in the background
528 MyJoinableThread
thread(10);
531 printf("\nThread terminated with exit code %lu.\n",
532 (unsigned long)thread
.Wait());
535 void TestThreadSuspend()
537 puts("\n*** Testing thread suspend/resume functions ***");
539 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
543 // this is for this demo only, in a real life program we'd use another
544 // condition variable which would be signaled from wxThread::Entry() to
545 // tell us that the thread really started running - but here just wait a
546 // bit and hope that it will be enough (the problem is, of course, that
547 // the thread might still not run when we call Pause() which will result
549 wxThread::Sleep(300);
551 for ( size_t n
= 0; n
< 3; n
++ )
555 puts("\nThread suspended");
558 // don't sleep but resume immediately the first time
559 wxThread::Sleep(300);
561 puts("Going to resume the thread");
566 puts("Waiting until it terminates now");
568 // wait until the thread terminates
574 void TestThreadDelete()
576 // As above, using Sleep() is only for testing here - we must use some
577 // synchronisation object instead to ensure that the thread is still
578 // running when we delete it - deleting a detached thread which already
579 // terminated will lead to a crash!
581 puts("\n*** Testing thread delete function ***");
583 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
587 puts("\nDeleted a thread which didn't start to run yet.");
589 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
593 wxThread::Sleep(300);
597 puts("\nDeleted a running thread.");
599 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
603 wxThread::Sleep(300);
609 puts("\nDeleted a sleeping thread.");
611 MyJoinableThread
thread3(20);
616 puts("\nDeleted a joinable thread.");
618 MyJoinableThread
thread4(2);
621 wxThread::Sleep(300);
625 puts("\nDeleted a joinable thread which already terminated.");
630 #endif // TEST_THREADS
632 // ----------------------------------------------------------------------------
634 // ----------------------------------------------------------------------------
638 void PrintArray(const char* name
, const wxArrayString
& array
)
640 printf("Dump of the array '%s'\n", name
);
642 size_t nCount
= array
.GetCount();
643 for ( size_t n
= 0; n
< nCount
; n
++ )
645 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
649 #endif // TEST_ARRAYS
651 // ----------------------------------------------------------------------------
653 // ----------------------------------------------------------------------------
657 #include "wx/timer.h"
669 for (int i
= 0; i
< 1000000; ++i
)
673 c
= "! How'ya doin'?";
676 c
= "Hello world! What's up?";
681 printf ("TestString elapsed time: %ld\n", sw
.Time());
692 for (int i
= 0; i
< 1000000; ++i
)
695 strcpy (b
, " world");
696 strcpy (c
, "! How'ya doin'?");
699 strcpy (c
, "Hello world! What's up?");
700 if (strcmp (c
, a
) == 0)
704 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
707 #endif // TEST_STRINGS
709 // ----------------------------------------------------------------------------
711 // ----------------------------------------------------------------------------
713 int main(int argc
, char **argv
)
715 if ( !wxInitialize() )
717 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
723 #endif // TEST_STRINGS
734 puts("*** Initially:");
736 PrintArray("a1", a1
);
738 wxArrayString
a2(a1
);
739 PrintArray("a2", a2
);
741 wxSortedArrayString
a3(a1
);
742 PrintArray("a3", a3
);
744 puts("*** After deleting a string from a1");
747 PrintArray("a1", a1
);
748 PrintArray("a2", a2
);
749 PrintArray("a3", a3
);
751 puts("*** After reassigning a1 to a2 and a3");
753 PrintArray("a2", a2
);
754 PrintArray("a3", a3
);
755 #endif // TEST_ARRAYS
763 for ( size_t n
= 0; n
< 8000; n
++ )
765 s
<< (char)('A' + (n
% 26));
769 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
771 // this one shouldn't be truncated
774 // but this one will because log functions use fixed size buffer
775 // (note that it doesn't need '\n' at the end neither - will be added
777 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
781 int nCPUs
= wxThread::GetCPUCount();
782 printf("This system has %d CPUs\n", nCPUs
);
784 wxThread::SetConcurrency(nCPUs
);
786 if ( argc
> 1 && argv
[1][0] == 't' )
787 wxLog::AddTraceMask("thread");
790 TestDetachedThreads();
792 TestJoinableThreads();
798 #endif // TEST_THREADS
805 #endif // TEST_LONGLONG