fix couple of warnings; remove wxUsleep dummy test
[wxWidgets.git] / samples / console / console.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: A sample console (as opposed to GUI) program using wxWidgets
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 // IMPORTANT NOTE FOR WXWIDGETS USERS:
13 // If you're a wxWidgets user and you're looking at this file to learn how to
14 // structure a wxWidgets console application, then you don't have much to learn.
15 // This application is used more for testing rather than as sample but
16 // basically the following simple block is enough for you to start your
17 // own console application:
18
19 /*
20 int main(int argc, char **argv)
21 {
22 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "program");
23
24 wxInitializer initializer;
25 if ( !initializer )
26 {
27 fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.");
28 return -1;
29 }
30
31 static const wxCmdLineEntryDesc cmdLineDesc[] =
32 {
33 { wxCMD_LINE_SWITCH, "h", "help", "show this help message",
34 wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
35 // ... your other command line options here...
36
37 { wxCMD_LINE_NONE }
38 };
39
40 wxCmdLineParser parser(cmdLineDesc, argc, wxArgv);
41 switch ( parser.Parse() )
42 {
43 case -1:
44 wxLogMessage(wxT("Help was given, terminating."));
45 break;
46
47 case 0:
48 // everything is ok; proceed
49 break;
50
51 default:
52 wxLogMessage(wxT("Syntax error detected, aborting."));
53 break;
54 }
55
56 // do something useful here
57
58 return 0;
59 }
60 */
61
62
63 // ============================================================================
64 // declarations
65 // ============================================================================
66
67 // ----------------------------------------------------------------------------
68 // headers
69 // ----------------------------------------------------------------------------
70
71 #include "wx/defs.h"
72
73 #include <stdio.h>
74
75 #include "wx/string.h"
76 #include "wx/file.h"
77 #include "wx/filename.h"
78 #include "wx/app.h"
79 #include "wx/log.h"
80 #include "wx/apptrait.h"
81 #include "wx/platinfo.h"
82 #include "wx/wxchar.h"
83
84 // without this pragma, the stupid compiler precompiles #defines below so that
85 // changing them doesn't "take place" later!
86 #ifdef __VISUALC__
87 #pragma hdrstop
88 #endif
89
90 // ----------------------------------------------------------------------------
91 // conditional compilation
92 // ----------------------------------------------------------------------------
93
94 /*
95 A note about all these conditional compilation macros: this file is used
96 both as a test suite for various non-GUI wxWidgets classes and as a
97 scratchpad for quick tests. So there are two compilation modes: if you
98 define TEST_ALL all tests are run, otherwise you may enable the individual
99 tests individually in the "#else" branch below.
100 */
101
102 // what to test (in alphabetic order)? Define TEST_ALL to 0 to do a single
103 // test, define it to 1 to do all tests.
104 #define TEST_ALL 0
105
106
107 #if TEST_ALL
108 #define TEST_DIR
109 #define TEST_DYNLIB
110 #define TEST_ENVIRON
111 #define TEST_FILE
112 #else // #if TEST_ALL
113 #define TEST_DATETIME
114 #define TEST_VOLUME
115 #define TEST_STDPATHS
116 #define TEST_STACKWALKER
117 #define TEST_FTP
118 #define TEST_SNGLINST
119 #define TEST_REGEX
120 #define TEST_INFO_FUNCTIONS
121 #define TEST_MIME
122 #endif
123
124 // some tests are interactive, define this to run them
125 #ifdef TEST_INTERACTIVE
126 #undef TEST_INTERACTIVE
127
128 #define TEST_INTERACTIVE 1
129 #else
130 #define TEST_INTERACTIVE 1
131 #endif
132
133 // ============================================================================
134 // implementation
135 // ============================================================================
136
137 // ----------------------------------------------------------------------------
138 // wxDir
139 // ----------------------------------------------------------------------------
140
141 #ifdef TEST_DIR
142
143 #include "wx/dir.h"
144
145 #ifdef __UNIX__
146 static const wxChar *ROOTDIR = wxT("/");
147 static const wxChar *TESTDIR = wxT("/usr/local/share");
148 #elif defined(__WXMSW__) || defined(__DOS__) || defined(__OS2__)
149 static const wxChar *ROOTDIR = wxT("c:\\");
150 static const wxChar *TESTDIR = wxT("d:\\");
151 #else
152 #error "don't know where the root directory is"
153 #endif
154
155 static void TestDirEnumHelper(wxDir& dir,
156 int flags = wxDIR_DEFAULT,
157 const wxString& filespec = wxEmptyString)
158 {
159 wxString filename;
160
161 if ( !dir.IsOpened() )
162 return;
163
164 bool cont = dir.GetFirst(&filename, filespec, flags);
165 while ( cont )
166 {
167 wxPrintf(wxT("\t%s\n"), filename.c_str());
168
169 cont = dir.GetNext(&filename);
170 }
171
172 wxPuts(wxEmptyString);
173 }
174
175 #if TEST_ALL
176
177 static void TestDirEnum()
178 {
179 wxPuts(wxT("*** Testing wxDir::GetFirst/GetNext ***"));
180
181 wxString cwd = wxGetCwd();
182 if ( !wxDir::Exists(cwd) )
183 {
184 wxPrintf(wxT("ERROR: current directory '%s' doesn't exist?\n"), cwd.c_str());
185 return;
186 }
187
188 wxDir dir(cwd);
189 if ( !dir.IsOpened() )
190 {
191 wxPrintf(wxT("ERROR: failed to open current directory '%s'.\n"), cwd.c_str());
192 return;
193 }
194
195 wxPuts(wxT("Enumerating everything in current directory:"));
196 TestDirEnumHelper(dir);
197
198 wxPuts(wxT("Enumerating really everything in current directory:"));
199 TestDirEnumHelper(dir, wxDIR_DEFAULT | wxDIR_DOTDOT);
200
201 wxPuts(wxT("Enumerating object files in current directory:"));
202 TestDirEnumHelper(dir, wxDIR_DEFAULT, wxT("*.o*"));
203
204 wxPuts(wxT("Enumerating directories in current directory:"));
205 TestDirEnumHelper(dir, wxDIR_DIRS);
206
207 wxPuts(wxT("Enumerating files in current directory:"));
208 TestDirEnumHelper(dir, wxDIR_FILES);
209
210 wxPuts(wxT("Enumerating files including hidden in current directory:"));
211 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
212
213 dir.Open(ROOTDIR);
214
215 wxPuts(wxT("Enumerating everything in root directory:"));
216 TestDirEnumHelper(dir, wxDIR_DEFAULT);
217
218 wxPuts(wxT("Enumerating directories in root directory:"));
219 TestDirEnumHelper(dir, wxDIR_DIRS);
220
221 wxPuts(wxT("Enumerating files in root directory:"));
222 TestDirEnumHelper(dir, wxDIR_FILES);
223
224 wxPuts(wxT("Enumerating files including hidden in root directory:"));
225 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
226
227 wxPuts(wxT("Enumerating files in non existing directory:"));
228 wxDir dirNo(wxT("nosuchdir"));
229 TestDirEnumHelper(dirNo);
230 }
231
232 #endif // TEST_ALL
233
234 class DirPrintTraverser : public wxDirTraverser
235 {
236 public:
237 virtual wxDirTraverseResult OnFile(const wxString& WXUNUSED(filename))
238 {
239 return wxDIR_CONTINUE;
240 }
241
242 virtual wxDirTraverseResult OnDir(const wxString& dirname)
243 {
244 wxString path, name, ext;
245 wxFileName::SplitPath(dirname, &path, &name, &ext);
246
247 if ( !ext.empty() )
248 name << wxT('.') << ext;
249
250 wxString indent;
251 for ( const wxChar *p = path.c_str(); *p; p++ )
252 {
253 if ( wxIsPathSeparator(*p) )
254 indent += wxT(" ");
255 }
256
257 wxPrintf(wxT("%s%s\n"), indent.c_str(), name.c_str());
258
259 return wxDIR_CONTINUE;
260 }
261 };
262
263 static void TestDirTraverse()
264 {
265 wxPuts(wxT("*** Testing wxDir::Traverse() ***"));
266
267 // enum all files
268 wxArrayString files;
269 size_t n = wxDir::GetAllFiles(TESTDIR, &files);
270 wxPrintf(wxT("There are %u files under '%s'\n"), n, TESTDIR);
271 if ( n > 1 )
272 {
273 wxPrintf(wxT("First one is '%s'\n"), files[0u].c_str());
274 wxPrintf(wxT(" last one is '%s'\n"), files[n - 1].c_str());
275 }
276
277 // enum again with custom traverser
278 wxPuts(wxT("Now enumerating directories:"));
279 wxDir dir(TESTDIR);
280 DirPrintTraverser traverser;
281 dir.Traverse(traverser, wxEmptyString, wxDIR_DIRS | wxDIR_HIDDEN);
282 }
283
284 #if TEST_ALL
285
286 static void TestDirExists()
287 {
288 wxPuts(wxT("*** Testing wxDir::Exists() ***"));
289
290 static const wxChar *dirnames[] =
291 {
292 wxT("."),
293 #if defined(__WXMSW__)
294 wxT("c:"),
295 wxT("c:\\"),
296 wxT("\\\\share\\file"),
297 wxT("c:\\dos"),
298 wxT("c:\\dos\\"),
299 wxT("c:\\dos\\\\"),
300 wxT("c:\\autoexec.bat"),
301 #elif defined(__UNIX__)
302 wxT("/"),
303 wxT("//"),
304 wxT("/usr/bin"),
305 wxT("/usr//bin"),
306 wxT("/usr///bin"),
307 #endif
308 };
309
310 for ( size_t n = 0; n < WXSIZEOF(dirnames); n++ )
311 {
312 wxPrintf(wxT("%-40s: %s\n"),
313 dirnames[n],
314 wxDir::Exists(dirnames[n]) ? wxT("exists")
315 : wxT("doesn't exist"));
316 }
317 }
318
319 #endif // TEST_ALL
320
321 #endif // TEST_DIR
322
323 // ----------------------------------------------------------------------------
324 // wxDllLoader
325 // ----------------------------------------------------------------------------
326
327 #ifdef TEST_DYNLIB
328
329 #include "wx/dynlib.h"
330
331 static void TestDllLoad()
332 {
333 #if defined(__WXMSW__)
334 static const wxChar *LIB_NAME = wxT("kernel32.dll");
335 static const wxChar *FUNC_NAME = wxT("lstrlenA");
336 #elif defined(__UNIX__)
337 // weird: using just libc.so does *not* work!
338 static const wxChar *LIB_NAME = wxT("/lib/libc.so.6");
339 static const wxChar *FUNC_NAME = wxT("strlen");
340 #else
341 #error "don't know how to test wxDllLoader on this platform"
342 #endif
343
344 wxPuts(wxT("*** testing basic wxDynamicLibrary functions ***\n"));
345
346 wxDynamicLibrary lib(LIB_NAME);
347 if ( !lib.IsLoaded() )
348 {
349 wxPrintf(wxT("ERROR: failed to load '%s'.\n"), LIB_NAME);
350 }
351 else
352 {
353 typedef int (wxSTDCALL *wxStrlenType)(const char *);
354 wxStrlenType pfnStrlen = (wxStrlenType)lib.GetSymbol(FUNC_NAME);
355 if ( !pfnStrlen )
356 {
357 wxPrintf(wxT("ERROR: function '%s' wasn't found in '%s'.\n"),
358 FUNC_NAME, LIB_NAME);
359 }
360 else
361 {
362 wxPrintf(wxT("Calling %s dynamically loaded from %s "),
363 FUNC_NAME, LIB_NAME);
364
365 if ( pfnStrlen("foo") != 3 )
366 {
367 wxPrintf(wxT("ERROR: loaded function is not wxStrlen()!\n"));
368 }
369 else
370 {
371 wxPuts(wxT("... ok"));
372 }
373 }
374
375 #ifdef __WXMSW__
376 static const wxChar *FUNC_NAME_AW = wxT("lstrlen");
377
378 typedef int (wxSTDCALL *wxStrlenTypeAorW)(const wxChar *);
379 wxStrlenTypeAorW
380 pfnStrlenAorW = (wxStrlenTypeAorW)lib.GetSymbolAorW(FUNC_NAME_AW);
381 if ( !pfnStrlenAorW )
382 {
383 wxPrintf(wxT("ERROR: function '%s' wasn't found in '%s'.\n"),
384 FUNC_NAME_AW, LIB_NAME);
385 }
386 else
387 {
388 if ( pfnStrlenAorW(wxT("foobar")) != 6 )
389 {
390 wxPrintf(wxT("ERROR: loaded function is not wxStrlen()!\n"));
391 }
392 }
393 #endif // __WXMSW__
394 }
395 }
396
397 #if defined(__WXMSW__) || defined(__UNIX__)
398
399 static void TestDllListLoaded()
400 {
401 wxPuts(wxT("*** testing wxDynamicLibrary::ListLoaded() ***\n"));
402
403 puts("\nLoaded modules:");
404 wxDynamicLibraryDetailsArray dlls = wxDynamicLibrary::ListLoaded();
405 const size_t count = dlls.GetCount();
406 for ( size_t n = 0; n < count; ++n )
407 {
408 const wxDynamicLibraryDetails& details = dlls[n];
409 printf("%-45s", (const char *)details.GetPath().mb_str());
410
411 void *addr wxDUMMY_INITIALIZE(NULL);
412 size_t len wxDUMMY_INITIALIZE(0);
413 if ( details.GetAddress(&addr, &len) )
414 {
415 printf(" %08lx:%08lx",
416 (unsigned long)addr, (unsigned long)((char *)addr + len));
417 }
418
419 printf(" %s\n", (const char *)details.GetVersion().mb_str());
420 }
421 }
422
423 #endif
424
425 #endif // TEST_DYNLIB
426
427 // ----------------------------------------------------------------------------
428 // wxGet/SetEnv
429 // ----------------------------------------------------------------------------
430
431 #ifdef TEST_ENVIRON
432
433 #include "wx/utils.h"
434
435 static wxString MyGetEnv(const wxString& var)
436 {
437 wxString val;
438 if ( !wxGetEnv(var, &val) )
439 val = wxT("<empty>");
440 else
441 val = wxString(wxT('\'')) + val + wxT('\'');
442
443 return val;
444 }
445
446 static void TestEnvironment()
447 {
448 const wxChar *var = wxT("wxTestVar");
449
450 wxPuts(wxT("*** testing environment access functions ***"));
451
452 wxPrintf(wxT("Initially getenv(%s) = %s\n"), var, MyGetEnv(var).c_str());
453 wxSetEnv(var, wxT("value for wxTestVar"));
454 wxPrintf(wxT("After wxSetEnv: getenv(%s) = %s\n"), var, MyGetEnv(var).c_str());
455 wxSetEnv(var, wxT("another value"));
456 wxPrintf(wxT("After 2nd wxSetEnv: getenv(%s) = %s\n"), var, MyGetEnv(var).c_str());
457 wxUnsetEnv(var);
458 wxPrintf(wxT("After wxUnsetEnv: getenv(%s) = %s\n"), var, MyGetEnv(var).c_str());
459 wxPrintf(wxT("PATH = %s\n"), MyGetEnv(wxT("PATH")).c_str());
460 }
461
462 #endif // TEST_ENVIRON
463
464 // ----------------------------------------------------------------------------
465 // file
466 // ----------------------------------------------------------------------------
467
468 #ifdef TEST_FILE
469
470 #include "wx/file.h"
471 #include "wx/ffile.h"
472 #include "wx/textfile.h"
473
474 static void TestFileRead()
475 {
476 wxPuts(wxT("*** wxFile read test ***"));
477
478 wxFile file(wxT("makefile.vc"));
479 if ( file.IsOpened() )
480 {
481 wxPrintf(wxT("File length: %lu\n"), file.Length());
482
483 wxPuts(wxT("File dump:\n----------"));
484
485 static const size_t len = 1024;
486 wxChar buf[len];
487 for ( ;; )
488 {
489 size_t nRead = file.Read(buf, len);
490 if ( nRead == (size_t)wxInvalidOffset )
491 {
492 wxPrintf(wxT("Failed to read the file."));
493 break;
494 }
495
496 fwrite(buf, nRead, 1, stdout);
497
498 if ( nRead < len )
499 break;
500 }
501
502 wxPuts(wxT("----------"));
503 }
504 else
505 {
506 wxPrintf(wxT("ERROR: can't open test file.\n"));
507 }
508
509 wxPuts(wxEmptyString);
510 }
511
512 static void TestTextFileRead()
513 {
514 wxPuts(wxT("*** wxTextFile read test ***"));
515
516 wxTextFile file(wxT("makefile.vc"));
517 if ( file.Open() )
518 {
519 wxPrintf(wxT("Number of lines: %u\n"), file.GetLineCount());
520 wxPrintf(wxT("Last line: '%s'\n"), file.GetLastLine().c_str());
521
522 wxString s;
523
524 wxPuts(wxT("\nDumping the entire file:"));
525 for ( s = file.GetFirstLine(); !file.Eof(); s = file.GetNextLine() )
526 {
527 wxPrintf(wxT("%6u: %s\n"), file.GetCurrentLine() + 1, s.c_str());
528 }
529 wxPrintf(wxT("%6u: %s\n"), file.GetCurrentLine() + 1, s.c_str());
530
531 wxPuts(wxT("\nAnd now backwards:"));
532 for ( s = file.GetLastLine();
533 file.GetCurrentLine() != 0;
534 s = file.GetPrevLine() )
535 {
536 wxPrintf(wxT("%6u: %s\n"), file.GetCurrentLine() + 1, s.c_str());
537 }
538 wxPrintf(wxT("%6u: %s\n"), file.GetCurrentLine() + 1, s.c_str());
539 }
540 else
541 {
542 wxPrintf(wxT("ERROR: can't open '%s'\n"), file.GetName());
543 }
544
545 wxPuts(wxEmptyString);
546 }
547
548 static void TestFileCopy()
549 {
550 wxPuts(wxT("*** Testing wxCopyFile ***"));
551
552 static const wxChar *filename1 = wxT("makefile.vc");
553 static const wxChar *filename2 = wxT("test2");
554 if ( !wxCopyFile(filename1, filename2) )
555 {
556 wxPuts(wxT("ERROR: failed to copy file"));
557 }
558 else
559 {
560 wxFFile f1(filename1, wxT("rb")),
561 f2(filename2, wxT("rb"));
562
563 if ( !f1.IsOpened() || !f2.IsOpened() )
564 {
565 wxPuts(wxT("ERROR: failed to open file(s)"));
566 }
567 else
568 {
569 wxString s1, s2;
570 if ( !f1.ReadAll(&s1) || !f2.ReadAll(&s2) )
571 {
572 wxPuts(wxT("ERROR: failed to read file(s)"));
573 }
574 else
575 {
576 if ( (s1.length() != s2.length()) ||
577 (memcmp(s1.c_str(), s2.c_str(), s1.length()) != 0) )
578 {
579 wxPuts(wxT("ERROR: copy error!"));
580 }
581 else
582 {
583 wxPuts(wxT("File was copied ok."));
584 }
585 }
586 }
587 }
588
589 if ( !wxRemoveFile(filename2) )
590 {
591 wxPuts(wxT("ERROR: failed to remove the file"));
592 }
593
594 wxPuts(wxEmptyString);
595 }
596
597 static void TestTempFile()
598 {
599 wxPuts(wxT("*** wxTempFile test ***"));
600
601 wxTempFile tmpFile;
602 if ( tmpFile.Open(wxT("test2")) && tmpFile.Write(wxT("the answer is 42")) )
603 {
604 if ( tmpFile.Commit() )
605 wxPuts(wxT("File committed."));
606 else
607 wxPuts(wxT("ERROR: could't commit temp file."));
608
609 wxRemoveFile(wxT("test2"));
610 }
611
612 wxPuts(wxEmptyString);
613 }
614
615 #endif // TEST_FILE
616
617 // ----------------------------------------------------------------------------
618 // MIME types
619 // ----------------------------------------------------------------------------
620
621 #ifdef TEST_MIME
622
623 #include "wx/mimetype.h"
624
625 static void TestMimeEnum()
626 {
627 wxPuts(wxT("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
628
629 wxArrayString mimetypes;
630
631 size_t count = wxTheMimeTypesManager->EnumAllFileTypes(mimetypes);
632
633 wxPrintf(wxT("*** All %u known filetypes: ***\n"), count);
634
635 wxArrayString exts;
636 wxString desc;
637
638 for ( size_t n = 0; n < count; n++ )
639 {
640 wxFileType *filetype =
641 wxTheMimeTypesManager->GetFileTypeFromMimeType(mimetypes[n]);
642 if ( !filetype )
643 {
644 wxPrintf(wxT(" nothing known about the filetype '%s'!\n"),
645 mimetypes[n].c_str());
646 continue;
647 }
648
649 filetype->GetDescription(&desc);
650 filetype->GetExtensions(exts);
651
652 filetype->GetIcon(NULL);
653
654 wxString extsAll;
655 for ( size_t e = 0; e < exts.GetCount(); e++ )
656 {
657 if ( e > 0 )
658 extsAll << wxT(", ");
659 extsAll += exts[e];
660 }
661
662 wxPrintf(wxT(" %s: %s (%s)\n"),
663 mimetypes[n].c_str(), desc.c_str(), extsAll.c_str());
664 }
665
666 wxPuts(wxEmptyString);
667 }
668
669 static void TestMimeFilename()
670 {
671 wxPuts(wxT("*** Testing MIME type from filename query ***\n"));
672
673 static const wxChar *filenames[] =
674 {
675 wxT("readme.txt"),
676 wxT("document.pdf"),
677 wxT("image.gif"),
678 wxT("picture.jpeg"),
679 };
680
681 for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
682 {
683 const wxString fname = filenames[n];
684 wxString ext = fname.AfterLast(wxT('.'));
685 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
686 if ( !ft )
687 {
688 wxPrintf(wxT("WARNING: extension '%s' is unknown.\n"), ext.c_str());
689 }
690 else
691 {
692 wxString desc;
693 if ( !ft->GetDescription(&desc) )
694 desc = wxT("<no description>");
695
696 wxString cmd;
697 if ( !ft->GetOpenCommand(&cmd,
698 wxFileType::MessageParameters(fname, wxEmptyString)) )
699 cmd = wxT("<no command available>");
700 else
701 cmd = wxString(wxT('"')) + cmd + wxT('"');
702
703 wxPrintf(wxT("To open %s (%s) run:\n %s\n"),
704 fname.c_str(), desc.c_str(), cmd.c_str());
705
706 delete ft;
707 }
708 }
709
710 wxPuts(wxEmptyString);
711 }
712
713 static void TestMimeAssociate()
714 {
715 wxPuts(wxT("*** Testing creation of filetype association ***\n"));
716
717 wxFileTypeInfo ftInfo(
718 wxT("application/x-xyz"),
719 wxT("xyzview '%s'"), // open cmd
720 wxT(""), // print cmd
721 wxT("XYZ File"), // description
722 wxT(".xyz"), // extensions
723 wxNullPtr // end of extensions
724 );
725 ftInfo.SetShortDesc(wxT("XYZFile")); // used under Win32 only
726
727 wxFileType *ft = wxTheMimeTypesManager->Associate(ftInfo);
728 if ( !ft )
729 {
730 wxPuts(wxT("ERROR: failed to create association!"));
731 }
732 else
733 {
734 // TODO: read it back
735 delete ft;
736 }
737
738 wxPuts(wxEmptyString);
739 }
740
741 #endif // TEST_MIME
742
743
744 // ----------------------------------------------------------------------------
745 // misc information functions
746 // ----------------------------------------------------------------------------
747
748 #ifdef TEST_INFO_FUNCTIONS
749
750 #include "wx/utils.h"
751
752 #if TEST_INTERACTIVE
753 static void TestDiskInfo()
754 {
755 wxPuts(wxT("*** Testing wxGetDiskSpace() ***"));
756
757 for ( ;; )
758 {
759 wxChar pathname[128];
760 wxPrintf(wxT("\nEnter a directory name (or 'quit' to escape): "));
761 if ( !wxFgets(pathname, WXSIZEOF(pathname), stdin) )
762 break;
763
764 // kill the last '\n'
765 pathname[wxStrlen(pathname) - 1] = 0;
766
767 if (wxStrcmp(pathname, "quit") == 0)
768 break;
769
770 wxLongLong total, free;
771 if ( !wxGetDiskSpace(pathname, &total, &free) )
772 {
773 wxPuts(wxT("ERROR: wxGetDiskSpace failed."));
774 }
775 else
776 {
777 wxPrintf(wxT("%sKb total, %sKb free on '%s'.\n"),
778 (total / 1024).ToString().c_str(),
779 (free / 1024).ToString().c_str(),
780 pathname);
781 }
782 }
783 }
784 #endif // TEST_INTERACTIVE
785
786 static void TestOsInfo()
787 {
788 wxPuts(wxT("*** Testing OS info functions ***\n"));
789
790 int major, minor;
791 wxGetOsVersion(&major, &minor);
792 wxPrintf(wxT("Running under: %s, version %d.%d\n"),
793 wxGetOsDescription().c_str(), major, minor);
794
795 wxPrintf(wxT("%ld free bytes of memory left.\n"), wxGetFreeMemory().ToLong());
796
797 wxPrintf(wxT("Host name is %s (%s).\n"),
798 wxGetHostName().c_str(), wxGetFullHostName().c_str());
799
800 wxPuts(wxEmptyString);
801 }
802
803 static void TestPlatformInfo()
804 {
805 wxPuts(wxT("*** Testing wxPlatformInfo functions ***\n"));
806
807 // get this platform
808 wxPlatformInfo plat;
809
810 wxPrintf(wxT("Operating system family name is: %s\n"), plat.GetOperatingSystemFamilyName().c_str());
811 wxPrintf(wxT("Operating system name is: %s\n"), plat.GetOperatingSystemIdName().c_str());
812 wxPrintf(wxT("Port ID name is: %s\n"), plat.GetPortIdName().c_str());
813 wxPrintf(wxT("Port ID short name is: %s\n"), plat.GetPortIdShortName().c_str());
814 wxPrintf(wxT("Architecture is: %s\n"), plat.GetArchName().c_str());
815 wxPrintf(wxT("Endianness is: %s\n"), plat.GetEndiannessName().c_str());
816
817 wxPuts(wxEmptyString);
818 }
819
820 static void TestUserInfo()
821 {
822 wxPuts(wxT("*** Testing user info functions ***\n"));
823
824 wxPrintf(wxT("User id is:\t%s\n"), wxGetUserId().c_str());
825 wxPrintf(wxT("User name is:\t%s\n"), wxGetUserName().c_str());
826 wxPrintf(wxT("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
827 wxPrintf(wxT("Email address:\t%s\n"), wxGetEmailAddress().c_str());
828
829 wxPuts(wxEmptyString);
830 }
831
832 #endif // TEST_INFO_FUNCTIONS
833
834 // ----------------------------------------------------------------------------
835 // regular expressions
836 // ----------------------------------------------------------------------------
837
838 #if defined TEST_REGEX && TEST_INTERACTIVE
839
840 #include "wx/regex.h"
841
842 static void TestRegExInteractive()
843 {
844 wxPuts(wxT("*** Testing RE interactively ***"));
845
846 for ( ;; )
847 {
848 wxChar pattern[128];
849 wxPrintf(wxT("\nEnter a pattern (or 'quit' to escape): "));
850 if ( !wxFgets(pattern, WXSIZEOF(pattern), stdin) )
851 break;
852
853 // kill the last '\n'
854 pattern[wxStrlen(pattern) - 1] = 0;
855
856 if (wxStrcmp(pattern, "quit") == 0)
857 break;
858
859 wxRegEx re;
860 if ( !re.Compile(pattern) )
861 {
862 continue;
863 }
864
865 wxChar text[128];
866 for ( ;; )
867 {
868 wxPrintf(wxT("Enter text to match: "));
869 if ( !wxFgets(text, WXSIZEOF(text), stdin) )
870 break;
871
872 // kill the last '\n'
873 text[wxStrlen(text) - 1] = 0;
874
875 if ( !re.Matches(text) )
876 {
877 wxPrintf(wxT("No match.\n"));
878 }
879 else
880 {
881 wxPrintf(wxT("Pattern matches at '%s'\n"), re.GetMatch(text).c_str());
882
883 size_t start, len;
884 for ( size_t n = 1; ; n++ )
885 {
886 if ( !re.GetMatch(&start, &len, n) )
887 {
888 break;
889 }
890
891 wxPrintf(wxT("Subexpr %u matched '%s'\n"),
892 n, wxString(text + start, len).c_str());
893 }
894 }
895 }
896 }
897 }
898
899 #endif // TEST_REGEX
900
901 // ----------------------------------------------------------------------------
902 // FTP
903 // ----------------------------------------------------------------------------
904
905 #ifdef TEST_FTP
906
907 #include "wx/protocol/ftp.h"
908 #include "wx/protocol/log.h"
909
910 #define FTP_ANONYMOUS
911
912 static wxFTP *ftp;
913
914 #ifdef FTP_ANONYMOUS
915 static const wxChar *hostname = wxT("ftp.wxwidgets.org");
916 #else
917 static const wxChar *hostname = "localhost";
918 #endif
919
920 static bool TestFtpConnect()
921 {
922 wxPuts(wxT("*** Testing FTP connect ***"));
923
924 #ifdef FTP_ANONYMOUS
925 wxPrintf(wxT("--- Attempting to connect to %s:21 anonymously...\n"), hostname);
926 #else // !FTP_ANONYMOUS
927 wxChar user[256];
928 wxFgets(user, WXSIZEOF(user), stdin);
929 user[wxStrlen(user) - 1] = '\0'; // chop off '\n'
930 ftp->SetUser(user);
931
932 wxChar password[256];
933 wxPrintf(wxT("Password for %s: "), password);
934 wxFgets(password, WXSIZEOF(password), stdin);
935 password[wxStrlen(password) - 1] = '\0'; // chop off '\n'
936 ftp->SetPassword(password);
937
938 wxPrintf(wxT("--- Attempting to connect to %s:21 as %s...\n"), hostname, user);
939 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
940
941 if ( !ftp->Connect(hostname) )
942 {
943 wxPrintf(wxT("ERROR: failed to connect to %s\n"), hostname);
944
945 return false;
946 }
947 else
948 {
949 wxPrintf(wxT("--- Connected to %s, current directory is '%s'\n"),
950 hostname, ftp->Pwd().c_str());
951 ftp->Close();
952 }
953
954 return true;
955 }
956
957 #if TEST_INTERACTIVE
958 static void TestFtpInteractive()
959 {
960 wxPuts(wxT("\n*** Interactive wxFTP test ***"));
961
962 wxChar buf[128];
963
964 for ( ;; )
965 {
966 wxPrintf(wxT("Enter FTP command (or 'quit' to escape): "));
967 if ( !wxFgets(buf, WXSIZEOF(buf), stdin) )
968 break;
969
970 // kill the last '\n'
971 buf[wxStrlen(buf) - 1] = 0;
972
973 // special handling of LIST and NLST as they require data connection
974 wxString start(buf, 4);
975 start.MakeUpper();
976 if ( start == wxT("LIST") || start == wxT("NLST") )
977 {
978 wxString wildcard;
979 if ( wxStrlen(buf) > 4 )
980 wildcard = buf + 5;
981
982 wxArrayString files;
983 if ( !ftp->GetList(files, wildcard, start == wxT("LIST")) )
984 {
985 wxPrintf(wxT("ERROR: failed to get %s of files\n"), start.c_str());
986 }
987 else
988 {
989 wxPrintf(wxT("--- %s of '%s' under '%s':\n"),
990 start.c_str(), wildcard.c_str(), ftp->Pwd().c_str());
991 size_t count = files.GetCount();
992 for ( size_t n = 0; n < count; n++ )
993 {
994 wxPrintf(wxT("\t%s\n"), files[n].c_str());
995 }
996 wxPuts(wxT("--- End of the file list"));
997 }
998 }
999 else if ( start == wxT("QUIT") )
1000 {
1001 break; // get out of here!
1002 }
1003 else // !list
1004 {
1005 wxChar ch = ftp->SendCommand(buf);
1006 wxPrintf(wxT("Command %s"), ch ? wxT("succeeded") : wxT("failed"));
1007 if ( ch )
1008 {
1009 wxPrintf(wxT(" (return code %c)"), ch);
1010 }
1011
1012 wxPrintf(wxT(", server reply:\n%s\n\n"), ftp->GetLastResult().c_str());
1013 }
1014 }
1015
1016 wxPuts(wxT("\n"));
1017 }
1018 #endif // TEST_INTERACTIVE
1019 #endif // TEST_FTP
1020
1021 // ----------------------------------------------------------------------------
1022 // stack backtrace
1023 // ----------------------------------------------------------------------------
1024
1025 #ifdef TEST_STACKWALKER
1026
1027 #if wxUSE_STACKWALKER
1028
1029 #include "wx/stackwalk.h"
1030
1031 class StackDump : public wxStackWalker
1032 {
1033 public:
1034 StackDump(const char *argv0)
1035 : wxStackWalker(argv0)
1036 {
1037 }
1038
1039 virtual void Walk(size_t skip = 1, size_t maxdepth = wxSTACKWALKER_MAX_DEPTH)
1040 {
1041 wxPuts(wxT("Stack dump:"));
1042
1043 wxStackWalker::Walk(skip, maxdepth);
1044 }
1045
1046 protected:
1047 virtual void OnStackFrame(const wxStackFrame& frame)
1048 {
1049 printf("[%2d] ", (int) frame.GetLevel());
1050
1051 wxString name = frame.GetName();
1052 if ( !name.empty() )
1053 {
1054 printf("%-20.40s", (const char*)name.mb_str());
1055 }
1056 else
1057 {
1058 printf("0x%08lx", (unsigned long)frame.GetAddress());
1059 }
1060
1061 if ( frame.HasSourceLocation() )
1062 {
1063 printf("\t%s:%d",
1064 (const char*)frame.GetFileName().mb_str(),
1065 (int)frame.GetLine());
1066 }
1067
1068 puts("");
1069
1070 wxString type, val;
1071 for ( size_t n = 0; frame.GetParam(n, &type, &name, &val); n++ )
1072 {
1073 printf("\t%s %s = %s\n", (const char*)type.mb_str(),
1074 (const char*)name.mb_str(),
1075 (const char*)val.mb_str());
1076 }
1077 }
1078 };
1079
1080 static void TestStackWalk(const char *argv0)
1081 {
1082 wxPuts(wxT("*** Testing wxStackWalker ***"));
1083
1084 StackDump dump(argv0);
1085 dump.Walk();
1086
1087 wxPuts("\n");
1088 }
1089
1090 #endif // wxUSE_STACKWALKER
1091
1092 #endif // TEST_STACKWALKER
1093
1094 // ----------------------------------------------------------------------------
1095 // standard paths
1096 // ----------------------------------------------------------------------------
1097
1098 #ifdef TEST_STDPATHS
1099
1100 #include "wx/stdpaths.h"
1101 #include "wx/wxchar.h" // wxPrintf
1102
1103 static void TestStandardPaths()
1104 {
1105 wxPuts(wxT("*** Testing wxStandardPaths ***"));
1106
1107 wxTheApp->SetAppName(wxT("console"));
1108
1109 wxStandardPathsBase& stdp = wxStandardPaths::Get();
1110 wxPrintf(wxT("Config dir (sys):\t%s\n"), stdp.GetConfigDir().c_str());
1111 wxPrintf(wxT("Config dir (user):\t%s\n"), stdp.GetUserConfigDir().c_str());
1112 wxPrintf(wxT("Data dir (sys):\t\t%s\n"), stdp.GetDataDir().c_str());
1113 wxPrintf(wxT("Data dir (sys local):\t%s\n"), stdp.GetLocalDataDir().c_str());
1114 wxPrintf(wxT("Data dir (user):\t%s\n"), stdp.GetUserDataDir().c_str());
1115 wxPrintf(wxT("Data dir (user local):\t%s\n"), stdp.GetUserLocalDataDir().c_str());
1116 wxPrintf(wxT("Documents dir:\t\t%s\n"), stdp.GetDocumentsDir().c_str());
1117 wxPrintf(wxT("Executable path:\t%s\n"), stdp.GetExecutablePath().c_str());
1118 wxPrintf(wxT("Plugins dir:\t\t%s\n"), stdp.GetPluginsDir().c_str());
1119 wxPrintf(wxT("Resources dir:\t\t%s\n"), stdp.GetResourcesDir().c_str());
1120 wxPrintf(wxT("Localized res. dir:\t%s\n"),
1121 stdp.GetLocalizedResourcesDir(wxT("fr")).c_str());
1122 wxPrintf(wxT("Message catalogs dir:\t%s\n"),
1123 stdp.GetLocalizedResourcesDir
1124 (
1125 wxT("fr"),
1126 wxStandardPaths::ResourceCat_Messages
1127 ).c_str());
1128
1129 wxPuts("\n");
1130 }
1131
1132 #endif // TEST_STDPATHS
1133
1134 // ----------------------------------------------------------------------------
1135 // wxVolume tests
1136 // ----------------------------------------------------------------------------
1137
1138 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
1139 #undef TEST_VOLUME
1140 #endif
1141
1142 #ifdef TEST_VOLUME
1143
1144 #include "wx/volume.h"
1145
1146 static const wxChar *volumeKinds[] =
1147 {
1148 wxT("floppy"),
1149 wxT("hard disk"),
1150 wxT("CD-ROM"),
1151 wxT("DVD-ROM"),
1152 wxT("network volume"),
1153 wxT("other volume"),
1154 };
1155
1156 static void TestFSVolume()
1157 {
1158 wxPuts(wxT("*** Testing wxFSVolume class ***"));
1159
1160 wxArrayString volumes = wxFSVolume::GetVolumes();
1161 size_t count = volumes.GetCount();
1162
1163 if ( !count )
1164 {
1165 wxPuts(wxT("ERROR: no mounted volumes?"));
1166 return;
1167 }
1168
1169 wxPrintf(wxT("%u mounted volumes found:\n"), count);
1170
1171 for ( size_t n = 0; n < count; n++ )
1172 {
1173 wxFSVolume vol(volumes[n]);
1174 if ( !vol.IsOk() )
1175 {
1176 wxPuts(wxT("ERROR: couldn't create volume"));
1177 continue;
1178 }
1179
1180 wxPrintf(wxT("%u: %s (%s), %s, %s, %s\n"),
1181 n + 1,
1182 vol.GetDisplayName().c_str(),
1183 vol.GetName().c_str(),
1184 volumeKinds[vol.GetKind()],
1185 vol.IsWritable() ? wxT("rw") : wxT("ro"),
1186 vol.GetFlags() & wxFS_VOL_REMOVABLE ? wxT("removable")
1187 : wxT("fixed"));
1188 }
1189
1190 wxPuts("\n");
1191 }
1192
1193 #endif // TEST_VOLUME
1194
1195 // ----------------------------------------------------------------------------
1196 // date time
1197 // ----------------------------------------------------------------------------
1198
1199 #ifdef TEST_DATETIME
1200
1201 #include "wx/math.h"
1202 #include "wx/datetime.h"
1203
1204 #if TEST_INTERACTIVE
1205
1206 static void TestDateTimeInteractive()
1207 {
1208 wxPuts(wxT("\n*** interactive wxDateTime tests ***"));
1209
1210 wxChar buf[128];
1211
1212 for ( ;; )
1213 {
1214 wxPrintf(wxT("Enter a date (or 'quit' to escape): "));
1215 if ( !wxFgets(buf, WXSIZEOF(buf), stdin) )
1216 break;
1217
1218 // kill the last '\n'
1219 buf[wxStrlen(buf) - 1] = 0;
1220
1221 if ( wxString(buf).CmpNoCase("quit") == 0 )
1222 break;
1223
1224 wxDateTime dt;
1225 const wxChar *p = dt.ParseDate(buf);
1226 if ( !p )
1227 {
1228 wxPrintf(wxT("ERROR: failed to parse the date '%s'.\n"), buf);
1229
1230 continue;
1231 }
1232 else if ( *p )
1233 {
1234 wxPrintf(wxT("WARNING: parsed only first %u characters.\n"), p - buf);
1235 }
1236
1237 wxPrintf(wxT("%s: day %u, week of month %u/%u, week of year %u\n"),
1238 dt.Format(wxT("%b %d, %Y")).c_str(),
1239 dt.GetDayOfYear(),
1240 dt.GetWeekOfMonth(wxDateTime::Monday_First),
1241 dt.GetWeekOfMonth(wxDateTime::Sunday_First),
1242 dt.GetWeekOfYear(wxDateTime::Monday_First));
1243 }
1244
1245 wxPuts("\n");
1246 }
1247
1248 #endif // TEST_INTERACTIVE
1249 #endif // TEST_DATETIME
1250
1251 // ----------------------------------------------------------------------------
1252 // single instance
1253 // ----------------------------------------------------------------------------
1254
1255 #ifdef TEST_SNGLINST
1256
1257 #include "wx/snglinst.h"
1258
1259 static bool TestSingleIstance()
1260 {
1261 wxPuts(wxT("\n*** Testing wxSingleInstanceChecker ***"));
1262
1263 wxSingleInstanceChecker checker;
1264 if ( checker.Create(wxT(".wxconsole.lock")) )
1265 {
1266 if ( checker.IsAnotherRunning() )
1267 {
1268 wxPrintf(wxT("Another instance of the program is running, exiting.\n"));
1269
1270 return false;
1271 }
1272
1273 // wait some time to give time to launch another instance
1274 wxPuts(wxT("If you try to run another instance of this program now, it won't start."));
1275 wxPrintf(wxT("Press \"Enter\" to exit wxSingleInstanceChecker test and proceed..."));
1276 wxFgetc(stdin);
1277 }
1278 else // failed to create
1279 {
1280 wxPrintf(wxT("Failed to init wxSingleInstanceChecker.\n"));
1281 }
1282
1283 wxPuts("\n");
1284
1285 return true;
1286 }
1287 #endif // TEST_SNGLINST
1288
1289
1290 // ----------------------------------------------------------------------------
1291 // entry point
1292 // ----------------------------------------------------------------------------
1293
1294 int main(int argc, char **argv)
1295 {
1296 #if wxUSE_UNICODE
1297 wxChar **wxArgv = new wxChar *[argc + 1];
1298
1299 {
1300 int n;
1301
1302 for (n = 0; n < argc; n++ )
1303 {
1304 wxMB2WXbuf warg = wxConvertMB2WX(argv[n]);
1305 wxArgv[n] = wxStrdup(warg);
1306 }
1307
1308 wxArgv[n] = NULL;
1309 }
1310 #else // !wxUSE_UNICODE
1311 #define wxArgv argv
1312 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
1313
1314 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "program");
1315
1316 wxInitializer initializer;
1317 if ( !initializer )
1318 {
1319 fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.");
1320
1321 return -1;
1322 }
1323
1324 #ifdef TEST_SNGLINST
1325 if (!TestSingleIstance())
1326 return 1;
1327 #endif // TEST_SNGLINST
1328
1329 #ifdef TEST_DIR
1330 #if TEST_ALL
1331 TestDirExists();
1332 TestDirEnum();
1333 #endif
1334 TestDirTraverse();
1335 #endif // TEST_DIR
1336
1337 #ifdef TEST_DYNLIB
1338 TestDllLoad();
1339 TestDllListLoaded();
1340 #endif // TEST_DYNLIB
1341
1342 #ifdef TEST_ENVIRON
1343 TestEnvironment();
1344 #endif // TEST_ENVIRON
1345
1346 #ifdef TEST_FILE
1347 TestFileRead();
1348 TestTextFileRead();
1349 TestFileCopy();
1350 TestTempFile();
1351 #endif // TEST_FILE
1352
1353 #ifdef TEST_FTP
1354 wxLog::AddTraceMask(FTP_TRACE_MASK);
1355
1356 // wxFTP cannot be a static variable as its ctor needs to access
1357 // wxWidgets internals after it has been initialized
1358 ftp = new wxFTP;
1359 ftp->SetLog(new wxProtocolLog(FTP_TRACE_MASK));
1360 if ( TestFtpConnect() )
1361 TestFtpInteractive();
1362 //else: connecting to the FTP server failed
1363
1364 delete ftp;
1365 #endif // TEST_FTP
1366
1367 #ifdef TEST_MIME
1368 TestMimeEnum();
1369 TestMimeAssociate();
1370 TestMimeFilename();
1371 #endif // TEST_MIME
1372
1373 #ifdef TEST_INFO_FUNCTIONS
1374 TestOsInfo();
1375 TestPlatformInfo();
1376 TestUserInfo();
1377
1378 #if TEST_INTERACTIVE
1379 TestDiskInfo();
1380 #endif
1381 #endif // TEST_INFO_FUNCTIONS
1382
1383 #ifdef TEST_PRINTF
1384 TestPrintf();
1385 #endif // TEST_PRINTF
1386
1387 #if defined TEST_REGEX && TEST_INTERACTIVE
1388 TestRegExInteractive();
1389 #endif // defined TEST_REGEX && TEST_INTERACTIVE
1390
1391 #ifdef TEST_DATETIME
1392 #if TEST_INTERACTIVE
1393 TestDateTimeInteractive();
1394 #endif
1395 #endif // TEST_DATETIME
1396
1397 #ifdef TEST_STACKWALKER
1398 #if wxUSE_STACKWALKER
1399 TestStackWalk(argv[0]);
1400 #endif
1401 #endif // TEST_STACKWALKER
1402
1403 #ifdef TEST_STDPATHS
1404 TestStandardPaths();
1405 #endif
1406
1407 #ifdef TEST_VOLUME
1408 TestFSVolume();
1409 #endif // TEST_VOLUME
1410
1411 #if wxUSE_UNICODE
1412 {
1413 for ( int n = 0; n < argc; n++ )
1414 free(wxArgv[n]);
1415
1416 delete [] wxArgv;
1417 }
1418 #endif // wxUSE_UNICODE
1419
1420 wxUnusedVar(argc);
1421 wxUnusedVar(argv);
1422 return 0;
1423 }