Move a couple of wxFileName tests from the console sample to the existing FileNameTes...
[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 static const wxChar *directory = wxT("/pub");
917 static const wxChar *filename = wxT("welcome.msg");
918 #else
919 static const wxChar *hostname = "localhost";
920 static const wxChar *directory = wxT("/etc");
921 static const wxChar *filename = wxT("issue");
922 #endif
923
924 static bool TestFtpConnect()
925 {
926 wxPuts(wxT("*** Testing FTP connect ***"));
927
928 #ifdef FTP_ANONYMOUS
929 wxPrintf(wxT("--- Attempting to connect to %s:21 anonymously...\n"), hostname);
930 #else // !FTP_ANONYMOUS
931 wxChar user[256];
932 wxFgets(user, WXSIZEOF(user), stdin);
933 user[wxStrlen(user) - 1] = '\0'; // chop off '\n'
934 ftp->SetUser(user);
935
936 wxChar password[256];
937 wxPrintf(wxT("Password for %s: "), password);
938 wxFgets(password, WXSIZEOF(password), stdin);
939 password[wxStrlen(password) - 1] = '\0'; // chop off '\n'
940 ftp->SetPassword(password);
941
942 wxPrintf(wxT("--- Attempting to connect to %s:21 as %s...\n"), hostname, user);
943 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
944
945 if ( !ftp->Connect(hostname) )
946 {
947 wxPrintf(wxT("ERROR: failed to connect to %s\n"), hostname);
948
949 return false;
950 }
951 else
952 {
953 wxPrintf(wxT("--- Connected to %s, current directory is '%s'\n"),
954 hostname, ftp->Pwd().c_str());
955 ftp->Close();
956 }
957
958 return true;
959 }
960
961 #if TEST_INTERACTIVE
962 static void TestFtpInteractive()
963 {
964 wxPuts(wxT("\n*** Interactive wxFTP test ***"));
965
966 wxChar buf[128];
967
968 for ( ;; )
969 {
970 wxPrintf(wxT("Enter FTP command (or 'quit' to escape): "));
971 if ( !wxFgets(buf, WXSIZEOF(buf), stdin) )
972 break;
973
974 // kill the last '\n'
975 buf[wxStrlen(buf) - 1] = 0;
976
977 // special handling of LIST and NLST as they require data connection
978 wxString start(buf, 4);
979 start.MakeUpper();
980 if ( start == wxT("LIST") || start == wxT("NLST") )
981 {
982 wxString wildcard;
983 if ( wxStrlen(buf) > 4 )
984 wildcard = buf + 5;
985
986 wxArrayString files;
987 if ( !ftp->GetList(files, wildcard, start == wxT("LIST")) )
988 {
989 wxPrintf(wxT("ERROR: failed to get %s of files\n"), start.c_str());
990 }
991 else
992 {
993 wxPrintf(wxT("--- %s of '%s' under '%s':\n"),
994 start.c_str(), wildcard.c_str(), ftp->Pwd().c_str());
995 size_t count = files.GetCount();
996 for ( size_t n = 0; n < count; n++ )
997 {
998 wxPrintf(wxT("\t%s\n"), files[n].c_str());
999 }
1000 wxPuts(wxT("--- End of the file list"));
1001 }
1002 }
1003 else if ( start == wxT("QUIT") )
1004 {
1005 break; // get out of here!
1006 }
1007 else // !list
1008 {
1009 wxChar ch = ftp->SendCommand(buf);
1010 wxPrintf(wxT("Command %s"), ch ? wxT("succeeded") : wxT("failed"));
1011 if ( ch )
1012 {
1013 wxPrintf(wxT(" (return code %c)"), ch);
1014 }
1015
1016 wxPrintf(wxT(", server reply:\n%s\n\n"), ftp->GetLastResult().c_str());
1017 }
1018 }
1019
1020 wxPuts(wxT("\n"));
1021 }
1022 #endif // TEST_INTERACTIVE
1023 #endif // TEST_FTP
1024
1025 // ----------------------------------------------------------------------------
1026 // stack backtrace
1027 // ----------------------------------------------------------------------------
1028
1029 #ifdef TEST_STACKWALKER
1030
1031 #if wxUSE_STACKWALKER
1032
1033 #include "wx/stackwalk.h"
1034
1035 class StackDump : public wxStackWalker
1036 {
1037 public:
1038 StackDump(const char *argv0)
1039 : wxStackWalker(argv0)
1040 {
1041 }
1042
1043 virtual void Walk(size_t skip = 1, size_t maxdepth = wxSTACKWALKER_MAX_DEPTH)
1044 {
1045 wxPuts(wxT("Stack dump:"));
1046
1047 wxStackWalker::Walk(skip, maxdepth);
1048 }
1049
1050 protected:
1051 virtual void OnStackFrame(const wxStackFrame& frame)
1052 {
1053 printf("[%2d] ", (int) frame.GetLevel());
1054
1055 wxString name = frame.GetName();
1056 if ( !name.empty() )
1057 {
1058 printf("%-20.40s", (const char*)name.mb_str());
1059 }
1060 else
1061 {
1062 printf("0x%08lx", (unsigned long)frame.GetAddress());
1063 }
1064
1065 if ( frame.HasSourceLocation() )
1066 {
1067 printf("\t%s:%d",
1068 (const char*)frame.GetFileName().mb_str(),
1069 (int)frame.GetLine());
1070 }
1071
1072 puts("");
1073
1074 wxString type, val;
1075 for ( size_t n = 0; frame.GetParam(n, &type, &name, &val); n++ )
1076 {
1077 printf("\t%s %s = %s\n", (const char*)type.mb_str(),
1078 (const char*)name.mb_str(),
1079 (const char*)val.mb_str());
1080 }
1081 }
1082 };
1083
1084 static void TestStackWalk(const char *argv0)
1085 {
1086 wxPuts(wxT("*** Testing wxStackWalker ***"));
1087
1088 StackDump dump(argv0);
1089 dump.Walk();
1090
1091 wxPuts("\n");
1092 }
1093
1094 #endif // wxUSE_STACKWALKER
1095
1096 #endif // TEST_STACKWALKER
1097
1098 // ----------------------------------------------------------------------------
1099 // standard paths
1100 // ----------------------------------------------------------------------------
1101
1102 #ifdef TEST_STDPATHS
1103
1104 #include "wx/stdpaths.h"
1105 #include "wx/wxchar.h" // wxPrintf
1106
1107 static void TestStandardPaths()
1108 {
1109 wxPuts(wxT("*** Testing wxStandardPaths ***"));
1110
1111 wxTheApp->SetAppName(wxT("console"));
1112
1113 wxStandardPathsBase& stdp = wxStandardPaths::Get();
1114 wxPrintf(wxT("Config dir (sys):\t%s\n"), stdp.GetConfigDir().c_str());
1115 wxPrintf(wxT("Config dir (user):\t%s\n"), stdp.GetUserConfigDir().c_str());
1116 wxPrintf(wxT("Data dir (sys):\t\t%s\n"), stdp.GetDataDir().c_str());
1117 wxPrintf(wxT("Data dir (sys local):\t%s\n"), stdp.GetLocalDataDir().c_str());
1118 wxPrintf(wxT("Data dir (user):\t%s\n"), stdp.GetUserDataDir().c_str());
1119 wxPrintf(wxT("Data dir (user local):\t%s\n"), stdp.GetUserLocalDataDir().c_str());
1120 wxPrintf(wxT("Documents dir:\t\t%s\n"), stdp.GetDocumentsDir().c_str());
1121 wxPrintf(wxT("Executable path:\t%s\n"), stdp.GetExecutablePath().c_str());
1122 wxPrintf(wxT("Plugins dir:\t\t%s\n"), stdp.GetPluginsDir().c_str());
1123 wxPrintf(wxT("Resources dir:\t\t%s\n"), stdp.GetResourcesDir().c_str());
1124 wxPrintf(wxT("Localized res. dir:\t%s\n"),
1125 stdp.GetLocalizedResourcesDir(wxT("fr")).c_str());
1126 wxPrintf(wxT("Message catalogs dir:\t%s\n"),
1127 stdp.GetLocalizedResourcesDir
1128 (
1129 wxT("fr"),
1130 wxStandardPaths::ResourceCat_Messages
1131 ).c_str());
1132
1133 wxPuts("\n");
1134 }
1135
1136 #endif // TEST_STDPATHS
1137
1138 // ----------------------------------------------------------------------------
1139 // wxVolume tests
1140 // ----------------------------------------------------------------------------
1141
1142 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
1143 #undef TEST_VOLUME
1144 #endif
1145
1146 #ifdef TEST_VOLUME
1147
1148 #include "wx/volume.h"
1149
1150 static const wxChar *volumeKinds[] =
1151 {
1152 wxT("floppy"),
1153 wxT("hard disk"),
1154 wxT("CD-ROM"),
1155 wxT("DVD-ROM"),
1156 wxT("network volume"),
1157 wxT("other volume"),
1158 };
1159
1160 static void TestFSVolume()
1161 {
1162 wxPuts(wxT("*** Testing wxFSVolume class ***"));
1163
1164 wxArrayString volumes = wxFSVolume::GetVolumes();
1165 size_t count = volumes.GetCount();
1166
1167 if ( !count )
1168 {
1169 wxPuts(wxT("ERROR: no mounted volumes?"));
1170 return;
1171 }
1172
1173 wxPrintf(wxT("%u mounted volumes found:\n"), count);
1174
1175 for ( size_t n = 0; n < count; n++ )
1176 {
1177 wxFSVolume vol(volumes[n]);
1178 if ( !vol.IsOk() )
1179 {
1180 wxPuts(wxT("ERROR: couldn't create volume"));
1181 continue;
1182 }
1183
1184 wxPrintf(wxT("%u: %s (%s), %s, %s, %s\n"),
1185 n + 1,
1186 vol.GetDisplayName().c_str(),
1187 vol.GetName().c_str(),
1188 volumeKinds[vol.GetKind()],
1189 vol.IsWritable() ? wxT("rw") : wxT("ro"),
1190 vol.GetFlags() & wxFS_VOL_REMOVABLE ? wxT("removable")
1191 : wxT("fixed"));
1192 }
1193
1194 wxPuts("\n");
1195 }
1196
1197 #endif // TEST_VOLUME
1198
1199 // ----------------------------------------------------------------------------
1200 // date time
1201 // ----------------------------------------------------------------------------
1202
1203 #ifdef TEST_DATETIME
1204
1205 #include "wx/math.h"
1206 #include "wx/datetime.h"
1207
1208 #if TEST_INTERACTIVE
1209
1210 static void TestDateTimeInteractive()
1211 {
1212 wxPuts(wxT("\n*** interactive wxDateTime tests ***"));
1213
1214 wxChar buf[128];
1215
1216 for ( ;; )
1217 {
1218 wxPrintf(wxT("Enter a date (or 'quit' to escape): "));
1219 if ( !wxFgets(buf, WXSIZEOF(buf), stdin) )
1220 break;
1221
1222 // kill the last '\n'
1223 buf[wxStrlen(buf) - 1] = 0;
1224
1225 if ( wxString(buf).CmpNoCase("quit") == 0 )
1226 break;
1227
1228 wxDateTime dt;
1229 const wxChar *p = dt.ParseDate(buf);
1230 if ( !p )
1231 {
1232 wxPrintf(wxT("ERROR: failed to parse the date '%s'.\n"), buf);
1233
1234 continue;
1235 }
1236 else if ( *p )
1237 {
1238 wxPrintf(wxT("WARNING: parsed only first %u characters.\n"), p - buf);
1239 }
1240
1241 wxPrintf(wxT("%s: day %u, week of month %u/%u, week of year %u\n"),
1242 dt.Format(wxT("%b %d, %Y")).c_str(),
1243 dt.GetDayOfYear(),
1244 dt.GetWeekOfMonth(wxDateTime::Monday_First),
1245 dt.GetWeekOfMonth(wxDateTime::Sunday_First),
1246 dt.GetWeekOfYear(wxDateTime::Monday_First));
1247 }
1248
1249 wxPuts("\n");
1250 }
1251
1252 #endif // TEST_INTERACTIVE
1253 #endif // TEST_DATETIME
1254
1255 // ----------------------------------------------------------------------------
1256 // single instance
1257 // ----------------------------------------------------------------------------
1258
1259 #ifdef TEST_SNGLINST
1260
1261 #include "wx/snglinst.h"
1262
1263 static bool TestSingleIstance()
1264 {
1265 wxPuts(wxT("\n*** Testing wxSingleInstanceChecker ***"));
1266
1267 wxSingleInstanceChecker checker;
1268 if ( checker.Create(wxT(".wxconsole.lock")) )
1269 {
1270 if ( checker.IsAnotherRunning() )
1271 {
1272 wxPrintf(wxT("Another instance of the program is running, exiting.\n"));
1273
1274 return false;
1275 }
1276
1277 // wait some time to give time to launch another instance
1278 wxPuts(wxT("If you try to run another instance of this program now, it won't start."));
1279 wxPrintf(wxT("Press \"Enter\" to exit wxSingleInstanceChecker test and proceed..."));
1280 wxFgetc(stdin);
1281 }
1282 else // failed to create
1283 {
1284 wxPrintf(wxT("Failed to init wxSingleInstanceChecker.\n"));
1285 }
1286
1287 wxPuts("\n");
1288
1289 return true;
1290 }
1291 #endif // TEST_SNGLINST
1292
1293
1294 // ----------------------------------------------------------------------------
1295 // entry point
1296 // ----------------------------------------------------------------------------
1297
1298 int main(int argc, char **argv)
1299 {
1300 #if wxUSE_UNICODE
1301 wxChar **wxArgv = new wxChar *[argc + 1];
1302
1303 {
1304 int n;
1305
1306 for (n = 0; n < argc; n++ )
1307 {
1308 wxMB2WXbuf warg = wxConvertMB2WX(argv[n]);
1309 wxArgv[n] = wxStrdup(warg);
1310 }
1311
1312 wxArgv[n] = NULL;
1313 }
1314 #else // !wxUSE_UNICODE
1315 #define wxArgv argv
1316 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
1317
1318 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "program");
1319
1320 wxInitializer initializer;
1321 if ( !initializer )
1322 {
1323 fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.");
1324
1325 return -1;
1326 }
1327
1328 #ifdef TEST_SNGLINST
1329 if (!TestSingleIstance())
1330 return 1;
1331 #endif // TEST_SNGLINST
1332
1333 #ifdef TEST_DIR
1334 #if TEST_ALL
1335 TestDirExists();
1336 TestDirEnum();
1337 #endif
1338 TestDirTraverse();
1339 #endif // TEST_DIR
1340
1341 #ifdef TEST_DYNLIB
1342 TestDllLoad();
1343 TestDllListLoaded();
1344 #endif // TEST_DYNLIB
1345
1346 #ifdef TEST_ENVIRON
1347 TestEnvironment();
1348 #endif // TEST_ENVIRON
1349
1350 #ifdef TEST_FILE
1351 TestFileRead();
1352 TestTextFileRead();
1353 TestFileCopy();
1354 TestTempFile();
1355 #endif // TEST_FILE
1356
1357 #ifdef TEST_FTP
1358 wxLog::AddTraceMask(FTP_TRACE_MASK);
1359
1360 // wxFTP cannot be a static variable as its ctor needs to access
1361 // wxWidgets internals after it has been initialized
1362 ftp = new wxFTP;
1363 ftp->SetLog(new wxProtocolLog(FTP_TRACE_MASK));
1364 if ( TestFtpConnect() )
1365 TestFtpInteractive();
1366 //else: connecting to the FTP server failed
1367
1368 delete ftp;
1369 #endif // TEST_FTP
1370
1371 #ifdef TEST_MIME
1372 //wxLog::AddTraceMask(wxT("mime"));
1373 TestMimeEnum();
1374 TestMimeAssociate();
1375 TestMimeFilename();
1376 #endif // TEST_MIME
1377
1378 #ifdef TEST_INFO_FUNCTIONS
1379 TestOsInfo();
1380 TestPlatformInfo();
1381 TestUserInfo();
1382
1383 #if TEST_INTERACTIVE
1384 TestDiskInfo();
1385 #endif
1386 #endif // TEST_INFO_FUNCTIONS
1387
1388 #ifdef TEST_PRINTF
1389 TestPrintf();
1390 #endif // TEST_PRINTF
1391
1392 #if defined TEST_REGEX && TEST_INTERACTIVE
1393 TestRegExInteractive();
1394 #endif // defined TEST_REGEX && TEST_INTERACTIVE
1395
1396 #ifdef TEST_DATETIME
1397 #if TEST_INTERACTIVE
1398 TestDateTimeInteractive();
1399 #endif
1400 #endif // TEST_DATETIME
1401
1402 #ifdef TEST_STACKWALKER
1403 #if wxUSE_STACKWALKER
1404 TestStackWalk(argv[0]);
1405 #endif
1406 #endif // TEST_STACKWALKER
1407
1408 #ifdef TEST_STDPATHS
1409 TestStandardPaths();
1410 #endif
1411
1412 #ifdef TEST_USLEEP
1413 wxPuts(wxT("Sleeping for 3 seconds... z-z-z-z-z..."));
1414 wxUsleep(3000);
1415 #endif // TEST_USLEEP
1416
1417 #ifdef TEST_VOLUME
1418 TestFSVolume();
1419 #endif // TEST_VOLUME
1420
1421 #if wxUSE_UNICODE
1422 {
1423 for ( int n = 0; n < argc; n++ )
1424 free(wxArgv[n]);
1425
1426 delete [] wxArgv;
1427 }
1428 #endif // wxUSE_UNICODE
1429
1430 wxUnusedVar(argc);
1431 wxUnusedVar(argv);
1432 return 0;
1433 }