]> git.saurik.com Git - wxWidgets.git/blob - samples/console/console.cpp
5b15489d9d61ce0075a60097fcd685c9ddfc4e53
[wxWidgets.git] / samples / console / console.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWindows
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 04.10.99
7 // RCS-ID: $Id$
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #include <stdio.h>
21
22 #include <wx/string.h>
23 #include <wx/file.h>
24 #include <wx/app.h>
25
26 // ----------------------------------------------------------------------------
27 // conditional compilation
28 // ----------------------------------------------------------------------------
29
30 // what to test?
31
32 //#define TEST_ARRAYS
33 //#define TEST_LOG
34 //#define TEST_STRINGS
35 #define TEST_THREADS
36 //#define TEST_TIME
37 //#define TEST_LONGLONG
38
39 // ============================================================================
40 // implementation
41 // ============================================================================
42
43 // ----------------------------------------------------------------------------
44 // long long
45 // ----------------------------------------------------------------------------
46
47 #ifdef TEST_LONGLONG
48
49 #include <wx/longlong.h>
50 #include <wx/timer.h>
51
52 static void TestSpeed()
53 {
54 static const long max = 100000000;
55 long n;
56
57 {
58 wxStopWatch sw;
59
60 long l = 0;
61 for ( n = 0; n < max; n++ )
62 {
63 l += n;
64 }
65
66 printf("Summing longs took %ld milliseconds.\n", sw.Time());
67 }
68
69 {
70 wxStopWatch sw;
71
72 __int64 l = 0;
73 for ( n = 0; n < max; n++ )
74 {
75 l += n;
76 }
77
78 printf("Summing __int64s took %ld milliseconds.\n", sw.Time());
79 }
80
81 {
82 wxStopWatch sw;
83
84 wxLongLong l;
85 for ( n = 0; n < max; n++ )
86 {
87 l += n;
88 }
89
90 printf("Summing wxLongLongs took %ld milliseconds.\n", sw.Time());
91 }
92 }
93
94 static void TestDivision()
95 {
96 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
97
98 // seed pseudo random generator
99 //srand((unsigned)time(NULL));
100
101 size_t nTested = 0;
102 for ( size_t n = 0; n < 10000; n++ )
103 {
104 // get a random wxLongLong (shifting by 12 the MSB ensures that the
105 // multiplication will not overflow)
106 wxLongLong ll = MAKE_LL((rand() >> 12), rand(), rand(), rand());
107
108 wxASSERT( (ll * 1000l)/1000l == ll );
109
110 nTested++;
111 }
112
113 printf("\n*** Tested %u divisions/multiplications: ok\n", nTested);
114
115 #undef MAKE_LL
116 }
117
118 #endif // TEST_LONGLONG
119
120 // ----------------------------------------------------------------------------
121 // date time
122 // ----------------------------------------------------------------------------
123
124 #ifdef TEST_TIME
125
126 #include <wx/datetime.h>
127
128 // this test miscellaneous static wxDateTime functions
129 static void TestTimeStatic()
130 {
131 puts("\n*** wxDateTime static methods test ***");
132
133 // some info about the current date
134 int year = wxDateTime::GetCurrentYear();
135 printf("Current year %d is %sa leap one and has %d days.\n",
136 year,
137 wxDateTime::IsLeapYear(year) ? "" : "not ",
138 wxDateTime::GetNumberOfDays(year));
139
140 wxDateTime::Month month = wxDateTime::GetCurrentMonth();
141 printf("Current month is '%s' ('%s') and it has %d days\n",
142 wxDateTime::GetMonthName(month, TRUE).c_str(),
143 wxDateTime::GetMonthName(month).c_str(),
144 wxDateTime::GetNumberOfDays(month));
145
146 // leap year logic
147 static const size_t nYears = 5;
148 static const size_t years[2][nYears] =
149 {
150 // first line: the years to test
151 { 1990, 1976, 2000, 2030, 1984, },
152
153 // second line: TRUE if leap, FALSE otherwise
154 { FALSE, TRUE, TRUE, FALSE, TRUE }
155 };
156
157 for ( size_t n = 0; n < nYears; n++ )
158 {
159 int year = years[0][n];
160 bool should = years[1][n] != 0;
161
162 printf("Year %d is %sa leap year (should be: %s)\n",
163 year,
164 wxDateTime::IsLeapYear(year) ? "" : "not ",
165 should ? "yes" : "no");
166
167 wxASSERT( should == wxDateTime::IsLeapYear(year) );
168 }
169 }
170
171 // test constructing wxDateTime objects
172 static void TestTimeSet()
173 {
174 puts("\n*** wxDateTime construction test ***");
175
176 printf("Current time:\t%s\n", wxDateTime::Now().Format().c_str());
177 printf("Unix epoch:\t%s\n", wxDateTime((time_t)0).Format().c_str());
178 printf("Today noon:\t%s\n", wxDateTime(12, 0).Format().c_str());
179 printf("May 29, 1976:\t%s\n", wxDateTime(29, wxDateTime::May, 1976).Format().c_str());
180 }
181
182 // test time zones stuff
183 static void TestTimeZones()
184 {
185 puts("\n*** wxDateTime timezone test ***");
186
187 wxDateTime now = wxDateTime::Now();
188
189 printf("Current GMT time:\t%s\n", now.ToGMT().Format().c_str());
190 //printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).MakeGMT().Format().c_str());
191 printf("Current time in Paris:\t%s\n", now.ToTimezone(wxDateTime::CET).Format().c_str());
192 printf(" Moscow:\t%s\n", now.ToTimezone(wxDateTime::MSK).Format().c_str());
193 printf(" New York:\t%s\n", now.ToTimezone(wxDateTime::EST).Format().c_str());
194 }
195
196 #endif // TEST_TIME
197
198 // ----------------------------------------------------------------------------
199 // threads
200 // ----------------------------------------------------------------------------
201
202 #ifdef TEST_THREADS
203
204 #include <wx/thread.h>
205
206 static size_t gs_counter = (size_t)-1;
207 static wxCriticalSection gs_critsect;
208 static wxCondition gs_cond;
209
210 class MyJoinableThread : public wxThread
211 {
212 public:
213 MyJoinableThread(size_t n) : wxThread(wxTHREAD_JOINABLE)
214 { m_n = n; Create(); }
215
216 // thread execution starts here
217 virtual ExitCode Entry();
218
219 private:
220 size_t m_n;
221 };
222
223 wxThread::ExitCode MyJoinableThread::Entry()
224 {
225 unsigned long res = 1;
226 for ( size_t n = 1; n < m_n; n++ )
227 {
228 res *= n;
229
230 // it's a loooong calculation :-)
231 Sleep(100);
232 }
233
234 return (ExitCode)res;
235 }
236
237 class MyDetachedThread : public wxThread
238 {
239 public:
240 MyDetachedThread(size_t n, char ch)
241 {
242 m_n = n;
243 m_ch = ch;
244 m_cancelled = FALSE;
245
246 Create();
247 }
248
249 // thread execution starts here
250 virtual ExitCode Entry();
251
252 // and stops here
253 virtual void OnExit();
254
255 private:
256 size_t m_n; // number of characters to write
257 char m_ch; // character to write
258
259 bool m_cancelled; // FALSE if we exit normally
260 };
261
262 wxThread::ExitCode MyDetachedThread::Entry()
263 {
264 {
265 wxCriticalSectionLocker lock(gs_critsect);
266 if ( gs_counter == (size_t)-1 )
267 gs_counter = 1;
268 else
269 gs_counter++;
270 }
271
272 for ( size_t n = 0; n < m_n; n++ )
273 {
274 if ( TestDestroy() )
275 {
276 m_cancelled = TRUE;
277
278 break;
279 }
280
281 putchar(m_ch);
282 fflush(stdout);
283
284 wxThread::Sleep(100);
285 }
286
287 return 0;
288 }
289
290 void MyDetachedThread::OnExit()
291 {
292 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
293
294 wxCriticalSectionLocker lock(gs_critsect);
295 if ( !--gs_counter && !m_cancelled )
296 gs_cond.Signal();
297 }
298
299 void TestDetachedThreads()
300 {
301 puts("\n*** Testing detached threads ***");
302
303 static const size_t nThreads = 3;
304 MyDetachedThread *threads[nThreads];
305 size_t n;
306 for ( n = 0; n < nThreads; n++ )
307 {
308 threads[n] = new MyDetachedThread(10, 'A' + n);
309 }
310
311 threads[0]->SetPriority(WXTHREAD_MIN_PRIORITY);
312 threads[1]->SetPriority(WXTHREAD_MAX_PRIORITY);
313
314 for ( n = 0; n < nThreads; n++ )
315 {
316 threads[n]->Run();
317 }
318
319 // wait until all threads terminate
320 gs_cond.Wait();
321
322 puts("");
323 }
324
325 void TestJoinableThreads()
326 {
327 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
328
329 // calc 10! in the background
330 MyJoinableThread thread(10);
331 thread.Run();
332
333 printf("\nThread terminated with exit code %lu.\n",
334 (unsigned long)thread.Wait());
335 }
336
337 void TestThreadSuspend()
338 {
339 puts("\n*** Testing thread suspend/resume functions ***");
340
341 MyDetachedThread *thread = new MyDetachedThread(15, 'X');
342
343 thread->Run();
344
345 // this is for this demo only, in a real life program we'd use another
346 // condition variable which would be signaled from wxThread::Entry() to
347 // tell us that the thread really started running - but here just wait a
348 // bit and hope that it will be enough (the problem is, of course, that
349 // the thread might still not run when we call Pause() which will result
350 // in an error)
351 wxThread::Sleep(300);
352
353 for ( size_t n = 0; n < 3; n++ )
354 {
355 thread->Pause();
356
357 puts("\nThread suspended");
358 if ( n > 0 )
359 {
360 // don't sleep but resume immediately the first time
361 wxThread::Sleep(300);
362 }
363 puts("Going to resume the thread");
364
365 thread->Resume();
366 }
367
368 // wait until the thread terminates
369 gs_cond.Wait();
370
371 puts("");
372 }
373
374 void TestThreadDelete()
375 {
376 // As above, using Sleep() is only for testing here - we must use some
377 // synchronisation object instead to ensure that the thread is still
378 // running when we delete it - deleting a detached thread which already
379 // terminated will lead to a crash!
380
381 puts("\n*** Testing thread delete function ***");
382
383 MyDetachedThread *thread1 = new MyDetachedThread(30, 'Y');
384
385 thread1->Run();
386
387 wxThread::Sleep(300);
388
389 thread1->Delete();
390
391 puts("\nDeleted a running thread.");
392
393 MyDetachedThread *thread2 = new MyDetachedThread(30, 'Z');
394
395 thread2->Run();
396
397 wxThread::Sleep(300);
398
399 thread2->Pause();
400
401 thread2->Delete();
402
403 puts("\nDeleted a sleeping thread.");
404
405 MyJoinableThread *thread3 = new MyJoinableThread(20);
406 thread3->Run();
407
408 thread3->Delete();
409
410 puts("\nDeleted a joinable thread.");
411
412 MyJoinableThread *thread4 = new MyJoinableThread(2);
413 thread4->Run();
414
415 wxThread::Sleep(300);
416
417 thread4->Delete();
418
419 puts("\nDeleted a joinable thread which already terminated.");
420
421 puts("");
422 }
423
424 #endif // TEST_THREADS
425
426 // ----------------------------------------------------------------------------
427 // arrays
428 // ----------------------------------------------------------------------------
429
430 #ifdef TEST_ARRAYS
431
432 void PrintArray(const char* name, const wxArrayString& array)
433 {
434 printf("Dump of the array '%s'\n", name);
435
436 size_t nCount = array.GetCount();
437 for ( size_t n = 0; n < nCount; n++ )
438 {
439 printf("\t%s[%u] = '%s'\n", name, n, array[n].c_str());
440 }
441 }
442
443 #endif // TEST_ARRAYS
444
445 // ----------------------------------------------------------------------------
446 // strings
447 // ----------------------------------------------------------------------------
448
449 #ifdef TEST_STRINGS
450
451 #include "wx/timer.h"
452
453 void TestString()
454 {
455 wxStopWatch sw;
456
457 wxString a, b, c;
458
459 a.reserve (128);
460 b.reserve (128);
461 c.reserve (128);
462
463 for (int i = 0; i < 1000000; ++i)
464 {
465 a = "Hello";
466 b = " world";
467 c = "! How'ya doin'?";
468 a += b;
469 a += c;
470 c = "Hello world! What's up?";
471 if (c != a)
472 c = "Doh!";
473 }
474
475 printf ("TestString elapsed time: %ld\n", sw.Time());
476 }
477
478 void TestPChar()
479 {
480 wxStopWatch sw;
481
482 char a [128];
483 char b [128];
484 char c [128];
485
486 for (int i = 0; i < 1000000; ++i)
487 {
488 strcpy (a, "Hello");
489 strcpy (b, " world");
490 strcpy (c, "! How'ya doin'?");
491 strcat (a, b);
492 strcat (a, c);
493 strcpy (c, "Hello world! What's up?");
494 if (strcmp (c, a) == 0)
495 strcpy (c, "Doh!");
496 }
497
498 printf ("TestPChar elapsed time: %ld\n", sw.Time());
499 }
500
501 #endif // TEST_STRINGS
502
503 // ----------------------------------------------------------------------------
504 // entry point
505 // ----------------------------------------------------------------------------
506
507 int main(int argc, char **argv)
508 {
509 if ( !wxInitialize() )
510 {
511 fprintf(stderr, "Failed to initialize the wxWindows library, aborting.");
512 }
513
514 #ifdef TEST_STRINGS
515 TestPChar();
516 TestString();
517 #endif // TEST_STRINGS
518
519 #ifdef TEST_ARRAYS
520 wxArrayString a1;
521 a1.Add("tiger");
522 a1.Add("cat");
523 a1.Add("lion");
524 a1.Add("dog");
525 a1.Add("human");
526 a1.Add("ape");
527
528 puts("*** Initially:");
529
530 PrintArray("a1", a1);
531
532 wxArrayString a2(a1);
533 PrintArray("a2", a2);
534
535 wxSortedArrayString a3(a1);
536 PrintArray("a3", a3);
537
538 puts("*** After deleting a string from a1");
539 a1.Remove(2);
540
541 PrintArray("a1", a1);
542 PrintArray("a2", a2);
543 PrintArray("a3", a3);
544
545 puts("*** After reassigning a1 to a2 and a3");
546 a3 = a2 = a1;
547 PrintArray("a2", a2);
548 PrintArray("a3", a3);
549 #endif // TEST_ARRAYS
550
551 #ifdef TEST_LOG
552 wxString s;
553 for ( size_t n = 0; n < 8000; n++ )
554 {
555 s << (char)('A' + (n % 26));
556 }
557
558 wxString msg;
559 msg.Printf("A very very long message: '%s', the end!\n", s.c_str());
560
561 // this one shouldn't be truncated
562 printf(msg);
563
564 // but this one will because log functions use fixed size buffer
565 // (note that it doesn't need '\n' at the end neither - will be added
566 // by wxLog anyhow)
567 wxLogMessage("A very very long message 2: '%s', the end!", s.c_str());
568 #endif // TEST_LOG
569
570 #ifdef TEST_THREADS
571 if ( argc > 1 && argv[1][0] == 't' )
572 wxLog::AddTraceMask("thread");
573
574 if ( 0 )
575 TestDetachedThreads();
576 if ( 0 )
577 TestJoinableThreads();
578 if ( 0 )
579 TestThreadSuspend();
580 if ( 1 )
581 TestThreadDelete();
582
583 #endif // TEST_THREADS
584
585 #ifdef TEST_LONGLONG
586 if ( 0 )
587 TestSpeed();
588 if ( 1 )
589 TestDivision();
590 #endif // TEST_LONGLONG
591
592 #ifdef TEST_TIME
593 TestTimeStatic();
594 TestTimeSet();
595 TestTimeZones();
596 #endif // TEST_TIME
597
598 wxUninitialize();
599
600 return 0;
601 }