]> git.saurik.com Git - wxWidgets.git/blob - samples/console/console.cpp
f80181e48f7a5b3e799bb4ede21ba6df6888da16
[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_CMDLINE
109 #define TEST_DATETIME
110 #define TEST_DIR
111 #define TEST_DYNLIB
112 #define TEST_ENVIRON
113 #define TEST_FILE
114 #define TEST_FILECONF
115 #define TEST_FILENAME
116 #define TEST_FILETIME
117 #define TEST_FTP
118 #define TEST_INFO_FUNCTIONS
119 #define TEST_LOCALE
120 #define TEST_LOG
121 #define TEST_MIME
122 #define TEST_MODULE
123 #define TEST_PATHLIST
124 #define TEST_PRINTF
125 #define TEST_REGCONF
126 #define TEST_REGEX
127 #define TEST_REGISTRY
128 #define TEST_SCOPEGUARD
129 #define TEST_SNGLINST
130 // #define TEST_SOCKETS --FIXME! (RN)
131 #define TEST_STACKWALKER
132 #define TEST_STDPATHS
133 #define TEST_STREAMS
134 #define TEST_TIMER
135 // #define TEST_VOLUME --FIXME! (RN)
136 #else // #if TEST_ALL
137 #define TEST_DATETIME
138 #endif
139
140 // some tests are interactive, define this to run them
141 #ifdef TEST_INTERACTIVE
142 #undef TEST_INTERACTIVE
143
144 #define TEST_INTERACTIVE 1
145 #else
146 #define TEST_INTERACTIVE 1
147 #endif
148
149 // ============================================================================
150 // implementation
151 // ============================================================================
152
153 // ----------------------------------------------------------------------------
154 // helper functions
155 // ----------------------------------------------------------------------------
156
157 #if defined(TEST_SOCKETS)
158
159 // replace TABs with \t and CRs with \n
160 static wxString MakePrintable(const wxChar *s)
161 {
162 wxString str(s);
163 (void)str.Replace(wxT("\t"), wxT("\\t"));
164 (void)str.Replace(wxT("\n"), wxT("\\n"));
165 (void)str.Replace(wxT("\r"), wxT("\\r"));
166
167 return str;
168 }
169
170 #endif // MakePrintable() is used
171
172 // ----------------------------------------------------------------------------
173 // wxCmdLineParser
174 // ----------------------------------------------------------------------------
175
176 #ifdef TEST_CMDLINE
177
178 #include "wx/cmdline.h"
179 #include "wx/datetime.h"
180
181 #if wxUSE_CMDLINE_PARSER
182
183 static void ShowCmdLine(const wxCmdLineParser& parser)
184 {
185 wxString s = wxT("Command line parsed successfully:\nInput files: ");
186
187 size_t count = parser.GetParamCount();
188 for ( size_t param = 0; param < count; param++ )
189 {
190 s << parser.GetParam(param) << ' ';
191 }
192
193 s << '\n'
194 << wxT("Verbose:\t") << (parser.Found(wxT("v")) ? wxT("yes") : wxT("no")) << '\n'
195 << wxT("Quiet:\t") << (parser.Found(wxT("q")) ? wxT("yes") : wxT("no")) << '\n';
196
197 wxString strVal;
198 long lVal;
199 double dVal;
200 wxDateTime dt;
201 if ( parser.Found(wxT("o"), &strVal) )
202 s << wxT("Output file:\t") << strVal << '\n';
203 if ( parser.Found(wxT("i"), &strVal) )
204 s << wxT("Input dir:\t") << strVal << '\n';
205 if ( parser.Found(wxT("s"), &lVal) )
206 s << wxT("Size:\t") << lVal << '\n';
207 if ( parser.Found(wxT("f"), &dVal) )
208 s << wxT("Double:\t") << dVal << '\n';
209 if ( parser.Found(wxT("d"), &dt) )
210 s << wxT("Date:\t") << dt.FormatISODate() << '\n';
211 if ( parser.Found(wxT("project_name"), &strVal) )
212 s << wxT("Project:\t") << strVal << '\n';
213
214 wxLogMessage(s);
215 }
216
217 #endif // wxUSE_CMDLINE_PARSER
218
219 static void TestCmdLineConvert()
220 {
221 static const wxChar *cmdlines[] =
222 {
223 wxT("arg1 arg2"),
224 wxT("-a \"-bstring 1\" -c\"string 2\" \"string 3\""),
225 wxT("literal \\\" and \"\""),
226 };
227
228 for ( size_t n = 0; n < WXSIZEOF(cmdlines); n++ )
229 {
230 const wxChar *cmdline = cmdlines[n];
231 wxPrintf(wxT("Parsing: %s\n"), cmdline);
232 wxArrayString args = wxCmdLineParser::ConvertStringToArgs(cmdline);
233
234 size_t count = args.GetCount();
235 wxPrintf(wxT("\targc = %u\n"), count);
236 for ( size_t arg = 0; arg < count; arg++ )
237 {
238 wxPrintf(wxT("\targv[%u] = %s\n"), arg, args[arg].c_str());
239 }
240 }
241 }
242
243 #endif // TEST_CMDLINE
244
245 // ----------------------------------------------------------------------------
246 // wxDir
247 // ----------------------------------------------------------------------------
248
249 #ifdef TEST_DIR
250
251 #include "wx/dir.h"
252
253 #ifdef __UNIX__
254 static const wxChar *ROOTDIR = wxT("/");
255 static const wxChar *TESTDIR = wxT("/usr/local/share");
256 #elif defined(__WXMSW__) || defined(__DOS__) || defined(__OS2__)
257 static const wxChar *ROOTDIR = wxT("c:\\");
258 static const wxChar *TESTDIR = wxT("d:\\");
259 #else
260 #error "don't know where the root directory is"
261 #endif
262
263 static void TestDirEnumHelper(wxDir& dir,
264 int flags = wxDIR_DEFAULT,
265 const wxString& filespec = wxEmptyString)
266 {
267 wxString filename;
268
269 if ( !dir.IsOpened() )
270 return;
271
272 bool cont = dir.GetFirst(&filename, filespec, flags);
273 while ( cont )
274 {
275 wxPrintf(wxT("\t%s\n"), filename.c_str());
276
277 cont = dir.GetNext(&filename);
278 }
279
280 wxPuts(wxEmptyString);
281 }
282
283 #if TEST_ALL
284
285 static void TestDirEnum()
286 {
287 wxPuts(wxT("*** Testing wxDir::GetFirst/GetNext ***"));
288
289 wxString cwd = wxGetCwd();
290 if ( !wxDir::Exists(cwd) )
291 {
292 wxPrintf(wxT("ERROR: current directory '%s' doesn't exist?\n"), cwd.c_str());
293 return;
294 }
295
296 wxDir dir(cwd);
297 if ( !dir.IsOpened() )
298 {
299 wxPrintf(wxT("ERROR: failed to open current directory '%s'.\n"), cwd.c_str());
300 return;
301 }
302
303 wxPuts(wxT("Enumerating everything in current directory:"));
304 TestDirEnumHelper(dir);
305
306 wxPuts(wxT("Enumerating really everything in current directory:"));
307 TestDirEnumHelper(dir, wxDIR_DEFAULT | wxDIR_DOTDOT);
308
309 wxPuts(wxT("Enumerating object files in current directory:"));
310 TestDirEnumHelper(dir, wxDIR_DEFAULT, wxT("*.o*"));
311
312 wxPuts(wxT("Enumerating directories in current directory:"));
313 TestDirEnumHelper(dir, wxDIR_DIRS);
314
315 wxPuts(wxT("Enumerating files in current directory:"));
316 TestDirEnumHelper(dir, wxDIR_FILES);
317
318 wxPuts(wxT("Enumerating files including hidden in current directory:"));
319 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
320
321 dir.Open(ROOTDIR);
322
323 wxPuts(wxT("Enumerating everything in root directory:"));
324 TestDirEnumHelper(dir, wxDIR_DEFAULT);
325
326 wxPuts(wxT("Enumerating directories in root directory:"));
327 TestDirEnumHelper(dir, wxDIR_DIRS);
328
329 wxPuts(wxT("Enumerating files in root directory:"));
330 TestDirEnumHelper(dir, wxDIR_FILES);
331
332 wxPuts(wxT("Enumerating files including hidden in root directory:"));
333 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
334
335 wxPuts(wxT("Enumerating files in non existing directory:"));
336 wxDir dirNo(wxT("nosuchdir"));
337 TestDirEnumHelper(dirNo);
338 }
339
340 #endif // TEST_ALL
341
342 class DirPrintTraverser : public wxDirTraverser
343 {
344 public:
345 virtual wxDirTraverseResult OnFile(const wxString& WXUNUSED(filename))
346 {
347 return wxDIR_CONTINUE;
348 }
349
350 virtual wxDirTraverseResult OnDir(const wxString& dirname)
351 {
352 wxString path, name, ext;
353 wxFileName::SplitPath(dirname, &path, &name, &ext);
354
355 if ( !ext.empty() )
356 name << wxT('.') << ext;
357
358 wxString indent;
359 for ( const wxChar *p = path.c_str(); *p; p++ )
360 {
361 if ( wxIsPathSeparator(*p) )
362 indent += wxT(" ");
363 }
364
365 wxPrintf(wxT("%s%s\n"), indent.c_str(), name.c_str());
366
367 return wxDIR_CONTINUE;
368 }
369 };
370
371 static void TestDirTraverse()
372 {
373 wxPuts(wxT("*** Testing wxDir::Traverse() ***"));
374
375 // enum all files
376 wxArrayString files;
377 size_t n = wxDir::GetAllFiles(TESTDIR, &files);
378 wxPrintf(wxT("There are %u files under '%s'\n"), n, TESTDIR);
379 if ( n > 1 )
380 {
381 wxPrintf(wxT("First one is '%s'\n"), files[0u].c_str());
382 wxPrintf(wxT(" last one is '%s'\n"), files[n - 1].c_str());
383 }
384
385 // enum again with custom traverser
386 wxPuts(wxT("Now enumerating directories:"));
387 wxDir dir(TESTDIR);
388 DirPrintTraverser traverser;
389 dir.Traverse(traverser, wxEmptyString, wxDIR_DIRS | wxDIR_HIDDEN);
390 }
391
392 #if TEST_ALL
393
394 static void TestDirExists()
395 {
396 wxPuts(wxT("*** Testing wxDir::Exists() ***"));
397
398 static const wxChar *dirnames[] =
399 {
400 wxT("."),
401 #if defined(__WXMSW__)
402 wxT("c:"),
403 wxT("c:\\"),
404 wxT("\\\\share\\file"),
405 wxT("c:\\dos"),
406 wxT("c:\\dos\\"),
407 wxT("c:\\dos\\\\"),
408 wxT("c:\\autoexec.bat"),
409 #elif defined(__UNIX__)
410 wxT("/"),
411 wxT("//"),
412 wxT("/usr/bin"),
413 wxT("/usr//bin"),
414 wxT("/usr///bin"),
415 #endif
416 };
417
418 for ( size_t n = 0; n < WXSIZEOF(dirnames); n++ )
419 {
420 wxPrintf(wxT("%-40s: %s\n"),
421 dirnames[n],
422 wxDir::Exists(dirnames[n]) ? wxT("exists")
423 : wxT("doesn't exist"));
424 }
425 }
426
427 #endif // TEST_ALL
428
429 #endif // TEST_DIR
430
431 // ----------------------------------------------------------------------------
432 // wxDllLoader
433 // ----------------------------------------------------------------------------
434
435 #ifdef TEST_DYNLIB
436
437 #include "wx/dynlib.h"
438
439 static void TestDllLoad()
440 {
441 #if defined(__WXMSW__)
442 static const wxChar *LIB_NAME = wxT("kernel32.dll");
443 static const wxChar *FUNC_NAME = wxT("lstrlenA");
444 #elif defined(__UNIX__)
445 // weird: using just libc.so does *not* work!
446 static const wxChar *LIB_NAME = wxT("/lib/libc.so.6");
447 static const wxChar *FUNC_NAME = wxT("strlen");
448 #else
449 #error "don't know how to test wxDllLoader on this platform"
450 #endif
451
452 wxPuts(wxT("*** testing basic wxDynamicLibrary functions ***\n"));
453
454 wxDynamicLibrary lib(LIB_NAME);
455 if ( !lib.IsLoaded() )
456 {
457 wxPrintf(wxT("ERROR: failed to load '%s'.\n"), LIB_NAME);
458 }
459 else
460 {
461 typedef int (wxSTDCALL *wxStrlenType)(const char *);
462 wxStrlenType pfnStrlen = (wxStrlenType)lib.GetSymbol(FUNC_NAME);
463 if ( !pfnStrlen )
464 {
465 wxPrintf(wxT("ERROR: function '%s' wasn't found in '%s'.\n"),
466 FUNC_NAME, LIB_NAME);
467 }
468 else
469 {
470 wxPrintf(wxT("Calling %s dynamically loaded from %s "),
471 FUNC_NAME, LIB_NAME);
472
473 if ( pfnStrlen("foo") != 3 )
474 {
475 wxPrintf(wxT("ERROR: loaded function is not wxStrlen()!\n"));
476 }
477 else
478 {
479 wxPuts(wxT("... ok"));
480 }
481 }
482
483 #ifdef __WXMSW__
484 static const wxChar *FUNC_NAME_AW = wxT("lstrlen");
485
486 typedef int (wxSTDCALL *wxStrlenTypeAorW)(const wxChar *);
487 wxStrlenTypeAorW
488 pfnStrlenAorW = (wxStrlenTypeAorW)lib.GetSymbolAorW(FUNC_NAME_AW);
489 if ( !pfnStrlenAorW )
490 {
491 wxPrintf(wxT("ERROR: function '%s' wasn't found in '%s'.\n"),
492 FUNC_NAME_AW, LIB_NAME);
493 }
494 else
495 {
496 if ( pfnStrlenAorW(wxT("foobar")) != 6 )
497 {
498 wxPrintf(wxT("ERROR: loaded function is not wxStrlen()!\n"));
499 }
500 }
501 #endif // __WXMSW__
502 }
503 }
504
505 #if defined(__WXMSW__) || defined(__UNIX__)
506
507 static void TestDllListLoaded()
508 {
509 wxPuts(wxT("*** testing wxDynamicLibrary::ListLoaded() ***\n"));
510
511 puts("\nLoaded modules:");
512 wxDynamicLibraryDetailsArray dlls = wxDynamicLibrary::ListLoaded();
513 const size_t count = dlls.GetCount();
514 for ( size_t n = 0; n < count; ++n )
515 {
516 const wxDynamicLibraryDetails& details = dlls[n];
517 printf("%-45s", (const char *)details.GetPath().mb_str());
518
519 void *addr wxDUMMY_INITIALIZE(NULL);
520 size_t len wxDUMMY_INITIALIZE(0);
521 if ( details.GetAddress(&addr, &len) )
522 {
523 printf(" %08lx:%08lx",
524 (unsigned long)addr, (unsigned long)((char *)addr + len));
525 }
526
527 printf(" %s\n", (const char *)details.GetVersion().mb_str());
528 }
529 }
530
531 #endif
532
533 #endif // TEST_DYNLIB
534
535 // ----------------------------------------------------------------------------
536 // wxGet/SetEnv
537 // ----------------------------------------------------------------------------
538
539 #ifdef TEST_ENVIRON
540
541 #include "wx/utils.h"
542
543 static wxString MyGetEnv(const wxString& var)
544 {
545 wxString val;
546 if ( !wxGetEnv(var, &val) )
547 val = wxT("<empty>");
548 else
549 val = wxString(wxT('\'')) + val + wxT('\'');
550
551 return val;
552 }
553
554 static void TestEnvironment()
555 {
556 const wxChar *var = wxT("wxTestVar");
557
558 wxPuts(wxT("*** testing environment access functions ***"));
559
560 wxPrintf(wxT("Initially getenv(%s) = %s\n"), var, MyGetEnv(var).c_str());
561 wxSetEnv(var, wxT("value for wxTestVar"));
562 wxPrintf(wxT("After wxSetEnv: getenv(%s) = %s\n"), var, MyGetEnv(var).c_str());
563 wxSetEnv(var, wxT("another value"));
564 wxPrintf(wxT("After 2nd wxSetEnv: getenv(%s) = %s\n"), var, MyGetEnv(var).c_str());
565 wxUnsetEnv(var);
566 wxPrintf(wxT("After wxUnsetEnv: getenv(%s) = %s\n"), var, MyGetEnv(var).c_str());
567 wxPrintf(wxT("PATH = %s\n"), MyGetEnv(wxT("PATH")).c_str());
568 }
569
570 #endif // TEST_ENVIRON
571
572 // ----------------------------------------------------------------------------
573 // file
574 // ----------------------------------------------------------------------------
575
576 #ifdef TEST_FILE
577
578 #include "wx/file.h"
579 #include "wx/ffile.h"
580 #include "wx/textfile.h"
581
582 static void TestFileRead()
583 {
584 wxPuts(wxT("*** wxFile read test ***"));
585
586 wxFile file(wxT("testdata.fc"));
587 if ( file.IsOpened() )
588 {
589 wxPrintf(wxT("File length: %lu\n"), file.Length());
590
591 wxPuts(wxT("File dump:\n----------"));
592
593 static const size_t len = 1024;
594 wxChar buf[len];
595 for ( ;; )
596 {
597 size_t nRead = file.Read(buf, len);
598 if ( nRead == (size_t)wxInvalidOffset )
599 {
600 wxPrintf(wxT("Failed to read the file."));
601 break;
602 }
603
604 fwrite(buf, nRead, 1, stdout);
605
606 if ( nRead < len )
607 break;
608 }
609
610 wxPuts(wxT("----------"));
611 }
612 else
613 {
614 wxPrintf(wxT("ERROR: can't open test file.\n"));
615 }
616
617 wxPuts(wxEmptyString);
618 }
619
620 static void TestTextFileRead()
621 {
622 wxPuts(wxT("*** wxTextFile read test ***"));
623
624 wxTextFile file(wxT("testdata.fc"));
625 if ( file.Open() )
626 {
627 wxPrintf(wxT("Number of lines: %u\n"), file.GetLineCount());
628 wxPrintf(wxT("Last line: '%s'\n"), file.GetLastLine().c_str());
629
630 wxString s;
631
632 wxPuts(wxT("\nDumping the entire file:"));
633 for ( s = file.GetFirstLine(); !file.Eof(); s = file.GetNextLine() )
634 {
635 wxPrintf(wxT("%6u: %s\n"), file.GetCurrentLine() + 1, s.c_str());
636 }
637 wxPrintf(wxT("%6u: %s\n"), file.GetCurrentLine() + 1, s.c_str());
638
639 wxPuts(wxT("\nAnd now backwards:"));
640 for ( s = file.GetLastLine();
641 file.GetCurrentLine() != 0;
642 s = file.GetPrevLine() )
643 {
644 wxPrintf(wxT("%6u: %s\n"), file.GetCurrentLine() + 1, s.c_str());
645 }
646 wxPrintf(wxT("%6u: %s\n"), file.GetCurrentLine() + 1, s.c_str());
647 }
648 else
649 {
650 wxPrintf(wxT("ERROR: can't open '%s'\n"), file.GetName());
651 }
652
653 wxPuts(wxEmptyString);
654 }
655
656 static void TestFileCopy()
657 {
658 wxPuts(wxT("*** Testing wxCopyFile ***"));
659
660 static const wxChar *filename1 = wxT("testdata.fc");
661 static const wxChar *filename2 = wxT("test2");
662 if ( !wxCopyFile(filename1, filename2) )
663 {
664 wxPuts(wxT("ERROR: failed to copy file"));
665 }
666 else
667 {
668 wxFFile f1(filename1, wxT("rb")),
669 f2(filename2, wxT("rb"));
670
671 if ( !f1.IsOpened() || !f2.IsOpened() )
672 {
673 wxPuts(wxT("ERROR: failed to open file(s)"));
674 }
675 else
676 {
677 wxString s1, s2;
678 if ( !f1.ReadAll(&s1) || !f2.ReadAll(&s2) )
679 {
680 wxPuts(wxT("ERROR: failed to read file(s)"));
681 }
682 else
683 {
684 if ( (s1.length() != s2.length()) ||
685 (memcmp(s1.c_str(), s2.c_str(), s1.length()) != 0) )
686 {
687 wxPuts(wxT("ERROR: copy error!"));
688 }
689 else
690 {
691 wxPuts(wxT("File was copied ok."));
692 }
693 }
694 }
695 }
696
697 if ( !wxRemoveFile(filename2) )
698 {
699 wxPuts(wxT("ERROR: failed to remove the file"));
700 }
701
702 wxPuts(wxEmptyString);
703 }
704
705 static void TestTempFile()
706 {
707 wxPuts(wxT("*** wxTempFile test ***"));
708
709 wxTempFile tmpFile;
710 if ( tmpFile.Open(wxT("test2")) && tmpFile.Write(wxT("the answer is 42")) )
711 {
712 if ( tmpFile.Commit() )
713 wxPuts(wxT("File committed."));
714 else
715 wxPuts(wxT("ERROR: could't commit temp file."));
716
717 wxRemoveFile(wxT("test2"));
718 }
719
720 wxPuts(wxEmptyString);
721 }
722
723 #endif // TEST_FILE
724
725 // ----------------------------------------------------------------------------
726 // wxFileConfig
727 // ----------------------------------------------------------------------------
728
729 #ifdef TEST_FILECONF
730
731 #include "wx/confbase.h"
732 #include "wx/fileconf.h"
733
734 static const struct FileConfTestData
735 {
736 const wxChar *name; // value name
737 const wxChar *value; // the value from the file
738 } fcTestData[] =
739 {
740 { wxT("value1"), wxT("one") },
741 { wxT("value2"), wxT("two") },
742 { wxT("novalue"), wxT("default") },
743 };
744
745 static void TestFileConfRead()
746 {
747 wxPuts(wxT("*** testing wxFileConfig loading/reading ***"));
748
749 wxFileConfig fileconf(wxT("test"), wxEmptyString,
750 wxT("testdata.fc"), wxEmptyString,
751 wxCONFIG_USE_RELATIVE_PATH);
752
753 // test simple reading
754 wxPuts(wxT("\nReading config file:"));
755 wxString defValue(wxT("default")), value;
756 for ( size_t n = 0; n < WXSIZEOF(fcTestData); n++ )
757 {
758 const FileConfTestData& data = fcTestData[n];
759 value = fileconf.Read(data.name, defValue);
760 wxPrintf(wxT("\t%s = %s "), data.name, value.c_str());
761 if ( value == data.value )
762 {
763 wxPuts(wxT("(ok)"));
764 }
765 else
766 {
767 wxPrintf(wxT("(ERROR: should be %s)\n"), data.value);
768 }
769 }
770
771 // test enumerating the entries
772 wxPuts(wxT("\nEnumerating all root entries:"));
773 long dummy;
774 wxString name;
775 bool cont = fileconf.GetFirstEntry(name, dummy);
776 while ( cont )
777 {
778 wxPrintf(wxT("\t%s = %s\n"),
779 name.c_str(),
780 fileconf.Read(name.c_str(), wxT("ERROR")).c_str());
781
782 cont = fileconf.GetNextEntry(name, dummy);
783 }
784
785 static const wxChar *testEntry = wxT("TestEntry");
786 wxPrintf(wxT("\nTesting deletion of newly created \"Test\" entry: "));
787 fileconf.Write(testEntry, wxT("A value"));
788 fileconf.DeleteEntry(testEntry);
789 wxPrintf(fileconf.HasEntry(testEntry) ? wxT("ERROR\n") : wxT("ok\n"));
790 }
791
792 #endif // TEST_FILECONF
793
794 // ----------------------------------------------------------------------------
795 // wxFileName
796 // ----------------------------------------------------------------------------
797
798 #ifdef TEST_FILENAME
799
800 #include "wx/filename.h"
801
802 #if 0
803 static void DumpFileName(const wxChar *desc, const wxFileName& fn)
804 {
805 wxPuts(desc);
806
807 wxString full = fn.GetFullPath();
808
809 wxString vol, path, name, ext;
810 wxFileName::SplitPath(full, &vol, &path, &name, &ext);
811
812 wxPrintf(wxT("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
813 full.c_str(), vol.c_str(), path.c_str(), name.c_str(), ext.c_str());
814
815 wxFileName::SplitPath(full, &path, &name, &ext);
816 wxPrintf(wxT("or\t\t-> path '%s', name '%s', ext '%s'\n"),
817 path.c_str(), name.c_str(), ext.c_str());
818
819 wxPrintf(wxT("path is also:\t'%s'\n"), fn.GetPath().c_str());
820 wxPrintf(wxT("with volume: \t'%s'\n"),
821 fn.GetPath(wxPATH_GET_VOLUME).c_str());
822 wxPrintf(wxT("with separator:\t'%s'\n"),
823 fn.GetPath(wxPATH_GET_SEPARATOR).c_str());
824 wxPrintf(wxT("with both: \t'%s'\n"),
825 fn.GetPath(wxPATH_GET_SEPARATOR | wxPATH_GET_VOLUME).c_str());
826
827 wxPuts(wxT("The directories in the path are:"));
828 wxArrayString dirs = fn.GetDirs();
829 size_t count = dirs.GetCount();
830 for ( size_t n = 0; n < count; n++ )
831 {
832 wxPrintf(wxT("\t%u: %s\n"), n, dirs[n].c_str());
833 }
834 }
835 #endif
836
837 static void TestFileNameTemp()
838 {
839 wxPuts(wxT("*** testing wxFileName temp file creation ***"));
840
841 static const wxChar *tmpprefixes[] =
842 {
843 wxT(""),
844 wxT("foo"),
845 wxT(".."),
846 wxT("../bar"),
847 #ifdef __UNIX__
848 wxT("/tmp/foo"),
849 wxT("/tmp/foo/bar"), // this one must be an error
850 #endif // __UNIX__
851 };
852
853 for ( size_t n = 0; n < WXSIZEOF(tmpprefixes); n++ )
854 {
855 wxString path = wxFileName::CreateTempFileName(tmpprefixes[n]);
856 if ( path.empty() )
857 {
858 // "error" is not in upper case because it may be ok
859 wxPrintf(wxT("Prefix '%s'\t-> error\n"), tmpprefixes[n]);
860 }
861 else
862 {
863 wxPrintf(wxT("Prefix '%s'\t-> temp file '%s'\n"),
864 tmpprefixes[n], path.c_str());
865
866 if ( !wxRemoveFile(path) )
867 {
868 wxLogWarning(wxT("Failed to remove temp file '%s'"),
869 path.c_str());
870 }
871 }
872 }
873 }
874
875 static void TestFileNameDirManip()
876 {
877 // TODO: test AppendDir(), RemoveDir(), ...
878 }
879
880 static void TestFileNameComparison()
881 {
882 // TODO!
883 }
884
885 static void TestFileNameOperations()
886 {
887 // TODO!
888 }
889
890 static void TestFileNameCwd()
891 {
892 // TODO!
893 }
894
895 #endif // TEST_FILENAME
896
897 // ----------------------------------------------------------------------------
898 // wxFileName time functions
899 // ----------------------------------------------------------------------------
900
901 #ifdef TEST_FILETIME
902
903 #include "wx/filename.h"
904 #include "wx/datetime.h"
905
906 static void TestFileGetTimes()
907 {
908 wxFileName fn(wxT("testdata.fc"));
909
910 wxDateTime dtAccess, dtMod, dtCreate;
911 if ( !fn.GetTimes(&dtAccess, &dtMod, &dtCreate) )
912 {
913 wxPrintf(wxT("ERROR: GetTimes() failed.\n"));
914 }
915 else
916 {
917 static const wxChar *fmt = wxT("%Y-%b-%d %H:%M:%S");
918
919 wxPrintf(wxT("File times for '%s':\n"), fn.GetFullPath().c_str());
920 wxPrintf(wxT("Creation: \t%s\n"), dtCreate.Format(fmt).c_str());
921 wxPrintf(wxT("Last read: \t%s\n"), dtAccess.Format(fmt).c_str());
922 wxPrintf(wxT("Last write: \t%s\n"), dtMod.Format(fmt).c_str());
923 }
924 }
925
926 #if 0
927 static void TestFileSetTimes()
928 {
929 wxFileName fn(wxT("testdata.fc"));
930
931 if ( !fn.Touch() )
932 {
933 wxPrintf(wxT("ERROR: Touch() failed.\n"));
934 }
935 }
936 #endif
937
938 #endif // TEST_FILETIME
939
940 // ----------------------------------------------------------------------------
941 // wxLocale
942 // ----------------------------------------------------------------------------
943
944 #ifdef TEST_LOCALE
945
946 #include "wx/intl.h"
947 #include "wx/utils.h" // for wxSetEnv
948
949 static wxLocale gs_localeDefault;
950 // NOTE: don't init it here as it needs a wxAppTraits object
951 // and thus must be init-ed after creation of the wxInitializer
952 // class in the main()
953
954 // find the name of the language from its value
955 static const wxChar *GetLangName(int lang)
956 {
957 static const wxChar *languageNames[] =
958 {
959 wxT("DEFAULT"),
960 wxT("UNKNOWN"),
961 wxT("ABKHAZIAN"),
962 wxT("AFAR"),
963 wxT("AFRIKAANS"),
964 wxT("ALBANIAN"),
965 wxT("AMHARIC"),
966 wxT("ARABIC"),
967 wxT("ARABIC_ALGERIA"),
968 wxT("ARABIC_BAHRAIN"),
969 wxT("ARABIC_EGYPT"),
970 wxT("ARABIC_IRAQ"),
971 wxT("ARABIC_JORDAN"),
972 wxT("ARABIC_KUWAIT"),
973 wxT("ARABIC_LEBANON"),
974 wxT("ARABIC_LIBYA"),
975 wxT("ARABIC_MOROCCO"),
976 wxT("ARABIC_OMAN"),
977 wxT("ARABIC_QATAR"),
978 wxT("ARABIC_SAUDI_ARABIA"),
979 wxT("ARABIC_SUDAN"),
980 wxT("ARABIC_SYRIA"),
981 wxT("ARABIC_TUNISIA"),
982 wxT("ARABIC_UAE"),
983 wxT("ARABIC_YEMEN"),
984 wxT("ARMENIAN"),
985 wxT("ASSAMESE"),
986 wxT("AYMARA"),
987 wxT("AZERI"),
988 wxT("AZERI_CYRILLIC"),
989 wxT("AZERI_LATIN"),
990 wxT("BASHKIR"),
991 wxT("BASQUE"),
992 wxT("BELARUSIAN"),
993 wxT("BENGALI"),
994 wxT("BHUTANI"),
995 wxT("BIHARI"),
996 wxT("BISLAMA"),
997 wxT("BRETON"),
998 wxT("BULGARIAN"),
999 wxT("BURMESE"),
1000 wxT("CAMBODIAN"),
1001 wxT("CATALAN"),
1002 wxT("CHINESE"),
1003 wxT("CHINESE_SIMPLIFIED"),
1004 wxT("CHINESE_TRADITIONAL"),
1005 wxT("CHINESE_HONGKONG"),
1006 wxT("CHINESE_MACAU"),
1007 wxT("CHINESE_SINGAPORE"),
1008 wxT("CHINESE_TAIWAN"),
1009 wxT("CORSICAN"),
1010 wxT("CROATIAN"),
1011 wxT("CZECH"),
1012 wxT("DANISH"),
1013 wxT("DUTCH"),
1014 wxT("DUTCH_BELGIAN"),
1015 wxT("ENGLISH"),
1016 wxT("ENGLISH_UK"),
1017 wxT("ENGLISH_US"),
1018 wxT("ENGLISH_AUSTRALIA"),
1019 wxT("ENGLISH_BELIZE"),
1020 wxT("ENGLISH_BOTSWANA"),
1021 wxT("ENGLISH_CANADA"),
1022 wxT("ENGLISH_CARIBBEAN"),
1023 wxT("ENGLISH_DENMARK"),
1024 wxT("ENGLISH_EIRE"),
1025 wxT("ENGLISH_JAMAICA"),
1026 wxT("ENGLISH_NEW_ZEALAND"),
1027 wxT("ENGLISH_PHILIPPINES"),
1028 wxT("ENGLISH_SOUTH_AFRICA"),
1029 wxT("ENGLISH_TRINIDAD"),
1030 wxT("ENGLISH_ZIMBABWE"),
1031 wxT("ESPERANTO"),
1032 wxT("ESTONIAN"),
1033 wxT("FAEROESE"),
1034 wxT("FARSI"),
1035 wxT("FIJI"),
1036 wxT("FINNISH"),
1037 wxT("FRENCH"),
1038 wxT("FRENCH_BELGIAN"),
1039 wxT("FRENCH_CANADIAN"),
1040 wxT("FRENCH_LUXEMBOURG"),
1041 wxT("FRENCH_MONACO"),
1042 wxT("FRENCH_SWISS"),
1043 wxT("FRISIAN"),
1044 wxT("GALICIAN"),
1045 wxT("GEORGIAN"),
1046 wxT("GERMAN"),
1047 wxT("GERMAN_AUSTRIAN"),
1048 wxT("GERMAN_BELGIUM"),
1049 wxT("GERMAN_LIECHTENSTEIN"),
1050 wxT("GERMAN_LUXEMBOURG"),
1051 wxT("GERMAN_SWISS"),
1052 wxT("GREEK"),
1053 wxT("GREENLANDIC"),
1054 wxT("GUARANI"),
1055 wxT("GUJARATI"),
1056 wxT("HAUSA"),
1057 wxT("HEBREW"),
1058 wxT("HINDI"),
1059 wxT("HUNGARIAN"),
1060 wxT("ICELANDIC"),
1061 wxT("INDONESIAN"),
1062 wxT("INTERLINGUA"),
1063 wxT("INTERLINGUE"),
1064 wxT("INUKTITUT"),
1065 wxT("INUPIAK"),
1066 wxT("IRISH"),
1067 wxT("ITALIAN"),
1068 wxT("ITALIAN_SWISS"),
1069 wxT("JAPANESE"),
1070 wxT("JAVANESE"),
1071 wxT("KANNADA"),
1072 wxT("KASHMIRI"),
1073 wxT("KASHMIRI_INDIA"),
1074 wxT("KAZAKH"),
1075 wxT("KERNEWEK"),
1076 wxT("KINYARWANDA"),
1077 wxT("KIRGHIZ"),
1078 wxT("KIRUNDI"),
1079 wxT("KONKANI"),
1080 wxT("KOREAN"),
1081 wxT("KURDISH"),
1082 wxT("LAOTHIAN"),
1083 wxT("LATIN"),
1084 wxT("LATVIAN"),
1085 wxT("LINGALA"),
1086 wxT("LITHUANIAN"),
1087 wxT("MACEDONIAN"),
1088 wxT("MALAGASY"),
1089 wxT("MALAY"),
1090 wxT("MALAYALAM"),
1091 wxT("MALAY_BRUNEI_DARUSSALAM"),
1092 wxT("MALAY_MALAYSIA"),
1093 wxT("MALTESE"),
1094 wxT("MANIPURI"),
1095 wxT("MAORI"),
1096 wxT("MARATHI"),
1097 wxT("MOLDAVIAN"),
1098 wxT("MONGOLIAN"),
1099 wxT("NAURU"),
1100 wxT("NEPALI"),
1101 wxT("NEPALI_INDIA"),
1102 wxT("NORWEGIAN_BOKMAL"),
1103 wxT("NORWEGIAN_NYNORSK"),
1104 wxT("OCCITAN"),
1105 wxT("ORIYA"),
1106 wxT("OROMO"),
1107 wxT("PASHTO"),
1108 wxT("POLISH"),
1109 wxT("PORTUGUESE"),
1110 wxT("PORTUGUESE_BRAZILIAN"),
1111 wxT("PUNJABI"),
1112 wxT("QUECHUA"),
1113 wxT("RHAETO_ROMANCE"),
1114 wxT("ROMANIAN"),
1115 wxT("RUSSIAN"),
1116 wxT("RUSSIAN_UKRAINE"),
1117 wxT("SAMOAN"),
1118 wxT("SANGHO"),
1119 wxT("SANSKRIT"),
1120 wxT("SCOTS_GAELIC"),
1121 wxT("SERBIAN"),
1122 wxT("SERBIAN_CYRILLIC"),
1123 wxT("SERBIAN_LATIN"),
1124 wxT("SERBO_CROATIAN"),
1125 wxT("SESOTHO"),
1126 wxT("SETSWANA"),
1127 wxT("SHONA"),
1128 wxT("SINDHI"),
1129 wxT("SINHALESE"),
1130 wxT("SISWATI"),
1131 wxT("SLOVAK"),
1132 wxT("SLOVENIAN"),
1133 wxT("SOMALI"),
1134 wxT("SPANISH"),
1135 wxT("SPANISH_ARGENTINA"),
1136 wxT("SPANISH_BOLIVIA"),
1137 wxT("SPANISH_CHILE"),
1138 wxT("SPANISH_COLOMBIA"),
1139 wxT("SPANISH_COSTA_RICA"),
1140 wxT("SPANISH_DOMINICAN_REPUBLIC"),
1141 wxT("SPANISH_ECUADOR"),
1142 wxT("SPANISH_EL_SALVADOR"),
1143 wxT("SPANISH_GUATEMALA"),
1144 wxT("SPANISH_HONDURAS"),
1145 wxT("SPANISH_MEXICAN"),
1146 wxT("SPANISH_MODERN"),
1147 wxT("SPANISH_NICARAGUA"),
1148 wxT("SPANISH_PANAMA"),
1149 wxT("SPANISH_PARAGUAY"),
1150 wxT("SPANISH_PERU"),
1151 wxT("SPANISH_PUERTO_RICO"),
1152 wxT("SPANISH_URUGUAY"),
1153 wxT("SPANISH_US"),
1154 wxT("SPANISH_VENEZUELA"),
1155 wxT("SUNDANESE"),
1156 wxT("SWAHILI"),
1157 wxT("SWEDISH"),
1158 wxT("SWEDISH_FINLAND"),
1159 wxT("TAGALOG"),
1160 wxT("TAJIK"),
1161 wxT("TAMIL"),
1162 wxT("TATAR"),
1163 wxT("TELUGU"),
1164 wxT("THAI"),
1165 wxT("TIBETAN"),
1166 wxT("TIGRINYA"),
1167 wxT("TONGA"),
1168 wxT("TSONGA"),
1169 wxT("TURKISH"),
1170 wxT("TURKMEN"),
1171 wxT("TWI"),
1172 wxT("UIGHUR"),
1173 wxT("UKRAINIAN"),
1174 wxT("URDU"),
1175 wxT("URDU_INDIA"),
1176 wxT("URDU_PAKISTAN"),
1177 wxT("UZBEK"),
1178 wxT("UZBEK_CYRILLIC"),
1179 wxT("UZBEK_LATIN"),
1180 wxT("VIETNAMESE"),
1181 wxT("VOLAPUK"),
1182 wxT("WELSH"),
1183 wxT("WOLOF"),
1184 wxT("XHOSA"),
1185 wxT("YIDDISH"),
1186 wxT("YORUBA"),
1187 wxT("ZHUANG"),
1188 wxT("ZULU"),
1189 };
1190
1191 if ( (size_t)lang < WXSIZEOF(languageNames) )
1192 return languageNames[lang];
1193 else
1194 return wxT("INVALID");
1195 }
1196
1197 static void TestDefaultLang()
1198 {
1199 wxPuts(wxT("*** Testing wxLocale::GetSystemLanguage ***"));
1200
1201 gs_localeDefault.Init(wxLANGUAGE_ENGLISH);
1202
1203 static const wxChar *langStrings[] =
1204 {
1205 NULL, // system default
1206 wxT("C"),
1207 wxT("fr"),
1208 wxT("fr_FR"),
1209 wxT("en"),
1210 wxT("en_GB"),
1211 wxT("en_US"),
1212 wxT("de_DE.iso88591"),
1213 wxT("german"),
1214 wxT("?"), // invalid lang spec
1215 wxT("klingonese"), // I bet on some systems it does exist...
1216 };
1217
1218 wxPrintf(wxT("The default system encoding is %s (%d)\n"),
1219 wxLocale::GetSystemEncodingName().c_str(),
1220 wxLocale::GetSystemEncoding());
1221
1222 for ( size_t n = 0; n < WXSIZEOF(langStrings); n++ )
1223 {
1224 const wxChar *langStr = langStrings[n];
1225 if ( langStr )
1226 {
1227 // FIXME: this doesn't do anything at all under Windows, we need
1228 // to create a new wxLocale!
1229 wxSetEnv(wxT("LC_ALL"), langStr);
1230 }
1231
1232 int lang = gs_localeDefault.GetSystemLanguage();
1233 wxPrintf(wxT("Locale for '%s' is %s.\n"),
1234 langStr ? langStr : wxT("system default"), GetLangName(lang));
1235 }
1236 }
1237
1238 #endif // TEST_LOCALE
1239
1240 // ----------------------------------------------------------------------------
1241 // MIME types
1242 // ----------------------------------------------------------------------------
1243
1244 #ifdef TEST_MIME
1245
1246 #include "wx/mimetype.h"
1247
1248 static void TestMimeEnum()
1249 {
1250 wxPuts(wxT("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1251
1252 wxArrayString mimetypes;
1253
1254 size_t count = wxTheMimeTypesManager->EnumAllFileTypes(mimetypes);
1255
1256 wxPrintf(wxT("*** All %u known filetypes: ***\n"), count);
1257
1258 wxArrayString exts;
1259 wxString desc;
1260
1261 for ( size_t n = 0; n < count; n++ )
1262 {
1263 wxFileType *filetype =
1264 wxTheMimeTypesManager->GetFileTypeFromMimeType(mimetypes[n]);
1265 if ( !filetype )
1266 {
1267 wxPrintf(wxT("nothing known about the filetype '%s'!\n"),
1268 mimetypes[n].c_str());
1269 continue;
1270 }
1271
1272 filetype->GetDescription(&desc);
1273 filetype->GetExtensions(exts);
1274
1275 filetype->GetIcon(NULL);
1276
1277 wxString extsAll;
1278 for ( size_t e = 0; e < exts.GetCount(); e++ )
1279 {
1280 if ( e > 0 )
1281 extsAll << wxT(", ");
1282 extsAll += exts[e];
1283 }
1284
1285 wxPrintf(wxT("\t%s: %s (%s)\n"),
1286 mimetypes[n].c_str(), desc.c_str(), extsAll.c_str());
1287 }
1288
1289 wxPuts(wxEmptyString);
1290 }
1291
1292 static void TestMimeFilename()
1293 {
1294 wxPuts(wxT("*** Testing MIME type from filename query ***\n"));
1295
1296 static const wxChar *filenames[] =
1297 {
1298 wxT("readme.txt"),
1299 wxT("document.pdf"),
1300 wxT("image.gif"),
1301 wxT("picture.jpeg"),
1302 };
1303
1304 for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
1305 {
1306 const wxString fname = filenames[n];
1307 wxString ext = fname.AfterLast(wxT('.'));
1308 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
1309 if ( !ft )
1310 {
1311 wxPrintf(wxT("WARNING: extension '%s' is unknown.\n"), ext.c_str());
1312 }
1313 else
1314 {
1315 wxString desc;
1316 if ( !ft->GetDescription(&desc) )
1317 desc = wxT("<no description>");
1318
1319 wxString cmd;
1320 if ( !ft->GetOpenCommand(&cmd,
1321 wxFileType::MessageParameters(fname, wxEmptyString)) )
1322 cmd = wxT("<no command available>");
1323 else
1324 cmd = wxString(wxT('"')) + cmd + wxT('"');
1325
1326 wxPrintf(wxT("To open %s (%s) do %s.\n"),
1327 fname.c_str(), desc.c_str(), cmd.c_str());
1328
1329 delete ft;
1330 }
1331 }
1332
1333 wxPuts(wxEmptyString);
1334 }
1335
1336 // these tests were broken by wxMimeTypesManager changes, temporarily disabling
1337 #if 0
1338
1339 static void TestMimeOverride()
1340 {
1341 wxPuts(wxT("*** Testing wxMimeTypesManager additional files loading ***\n"));
1342
1343 static const wxChar *mailcap = wxT("/tmp/mailcap");
1344 static const wxChar *mimetypes = wxT("/tmp/mime.types");
1345
1346 if ( wxFile::Exists(mailcap) )
1347 wxPrintf(wxT("Loading mailcap from '%s': %s\n"),
1348 mailcap,
1349 wxTheMimeTypesManager->ReadMailcap(mailcap) ? wxT("ok") : wxT("ERROR"));
1350 else
1351 wxPrintf(wxT("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1352 mailcap);
1353
1354 if ( wxFile::Exists(mimetypes) )
1355 wxPrintf(wxT("Loading mime.types from '%s': %s\n"),
1356 mimetypes,
1357 wxTheMimeTypesManager->ReadMimeTypes(mimetypes) ? wxT("ok") : wxT("ERROR"));
1358 else
1359 wxPrintf(wxT("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1360 mimetypes);
1361
1362 wxPuts(wxEmptyString);
1363 }
1364
1365 static void TestMimeAssociate()
1366 {
1367 wxPuts(wxT("*** Testing creation of filetype association ***\n"));
1368
1369 wxFileTypeInfo ftInfo(
1370 wxT("application/x-xyz"),
1371 wxT("xyzview '%s'"), // open cmd
1372 wxT(""), // print cmd
1373 wxT("XYZ File"), // description
1374 wxT(".xyz"), // extensions
1375 wxNullPtr // end of extensions
1376 );
1377 ftInfo.SetShortDesc(wxT("XYZFile")); // used under Win32 only
1378
1379 wxFileType *ft = wxTheMimeTypesManager->Associate(ftInfo);
1380 if ( !ft )
1381 {
1382 wxPuts(wxT("ERROR: failed to create association!"));
1383 }
1384 else
1385 {
1386 // TODO: read it back
1387 delete ft;
1388 }
1389
1390 wxPuts(wxEmptyString);
1391 }
1392
1393 #endif // 0
1394
1395 #endif // TEST_MIME
1396
1397 // ----------------------------------------------------------------------------
1398 // module dependencies feature
1399 // ----------------------------------------------------------------------------
1400
1401 #ifdef TEST_MODULE
1402
1403 #include "wx/module.h"
1404
1405 class wxTestModule : public wxModule
1406 {
1407 protected:
1408 virtual bool OnInit() { wxPrintf(wxT("Load module: %s\n"), GetClassInfo()->GetClassName()); return true; }
1409 virtual void OnExit() { wxPrintf(wxT("Unload module: %s\n"), GetClassInfo()->GetClassName()); }
1410 };
1411
1412 class wxTestModuleA : public wxTestModule
1413 {
1414 public:
1415 wxTestModuleA();
1416 private:
1417 DECLARE_DYNAMIC_CLASS(wxTestModuleA)
1418 };
1419
1420 class wxTestModuleB : public wxTestModule
1421 {
1422 public:
1423 wxTestModuleB();
1424 private:
1425 DECLARE_DYNAMIC_CLASS(wxTestModuleB)
1426 };
1427
1428 class wxTestModuleC : public wxTestModule
1429 {
1430 public:
1431 wxTestModuleC();
1432 private:
1433 DECLARE_DYNAMIC_CLASS(wxTestModuleC)
1434 };
1435
1436 class wxTestModuleD : public wxTestModule
1437 {
1438 public:
1439 wxTestModuleD();
1440 private:
1441 DECLARE_DYNAMIC_CLASS(wxTestModuleD)
1442 };
1443
1444 IMPLEMENT_DYNAMIC_CLASS(wxTestModuleC, wxModule)
1445 wxTestModuleC::wxTestModuleC()
1446 {
1447 AddDependency(CLASSINFO(wxTestModuleD));
1448 }
1449
1450 IMPLEMENT_DYNAMIC_CLASS(wxTestModuleA, wxModule)
1451 wxTestModuleA::wxTestModuleA()
1452 {
1453 AddDependency(CLASSINFO(wxTestModuleB));
1454 AddDependency(CLASSINFO(wxTestModuleD));
1455 }
1456
1457 IMPLEMENT_DYNAMIC_CLASS(wxTestModuleD, wxModule)
1458 wxTestModuleD::wxTestModuleD()
1459 {
1460 }
1461
1462 IMPLEMENT_DYNAMIC_CLASS(wxTestModuleB, wxModule)
1463 wxTestModuleB::wxTestModuleB()
1464 {
1465 AddDependency(CLASSINFO(wxTestModuleD));
1466 AddDependency(CLASSINFO(wxTestModuleC));
1467 }
1468
1469 #endif // TEST_MODULE
1470
1471 // ----------------------------------------------------------------------------
1472 // misc information functions
1473 // ----------------------------------------------------------------------------
1474
1475 #ifdef TEST_INFO_FUNCTIONS
1476
1477 #include "wx/utils.h"
1478
1479 #if TEST_INTERACTIVE
1480 static void TestDiskInfo()
1481 {
1482 wxPuts(wxT("*** Testing wxGetDiskSpace() ***"));
1483
1484 for ( ;; )
1485 {
1486 wxChar pathname[128];
1487 wxPrintf(wxT("\nEnter a directory name: "));
1488 if ( !wxFgets(pathname, WXSIZEOF(pathname), stdin) )
1489 break;
1490
1491 // kill the last '\n'
1492 pathname[wxStrlen(pathname) - 1] = 0;
1493
1494 wxLongLong total, free;
1495 if ( !wxGetDiskSpace(pathname, &total, &free) )
1496 {
1497 wxPuts(wxT("ERROR: wxGetDiskSpace failed."));
1498 }
1499 else
1500 {
1501 wxPrintf(wxT("%sKb total, %sKb free on '%s'.\n"),
1502 (total / 1024).ToString().c_str(),
1503 (free / 1024).ToString().c_str(),
1504 pathname);
1505 }
1506 }
1507 }
1508 #endif // TEST_INTERACTIVE
1509
1510 static void TestOsInfo()
1511 {
1512 wxPuts(wxT("*** Testing OS info functions ***\n"));
1513
1514 int major, minor;
1515 wxGetOsVersion(&major, &minor);
1516 wxPrintf(wxT("Running under: %s, version %d.%d\n"),
1517 wxGetOsDescription().c_str(), major, minor);
1518
1519 wxPrintf(wxT("%ld free bytes of memory left.\n"), wxGetFreeMemory().ToLong());
1520
1521 wxPrintf(wxT("Host name is %s (%s).\n"),
1522 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1523
1524 wxPuts(wxEmptyString);
1525 }
1526
1527 static void TestPlatformInfo()
1528 {
1529 wxPuts(wxT("*** Testing wxPlatformInfo functions ***\n"));
1530
1531 // get this platform
1532 wxPlatformInfo plat;
1533
1534 wxPrintf(wxT("Operating system family name is: %s\n"), plat.GetOperatingSystemFamilyName().c_str());
1535 wxPrintf(wxT("Operating system name is: %s\n"), plat.GetOperatingSystemIdName().c_str());
1536 wxPrintf(wxT("Port ID name is: %s\n"), plat.GetPortIdName().c_str());
1537 wxPrintf(wxT("Port ID short name is: %s\n"), plat.GetPortIdShortName().c_str());
1538 wxPrintf(wxT("Architecture is: %s\n"), plat.GetArchName().c_str());
1539 wxPrintf(wxT("Endianness is: %s\n"), plat.GetEndiannessName().c_str());
1540
1541 wxPuts(wxEmptyString);
1542 }
1543
1544 static void TestUserInfo()
1545 {
1546 wxPuts(wxT("*** Testing user info functions ***\n"));
1547
1548 wxPrintf(wxT("User id is:\t%s\n"), wxGetUserId().c_str());
1549 wxPrintf(wxT("User name is:\t%s\n"), wxGetUserName().c_str());
1550 wxPrintf(wxT("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
1551 wxPrintf(wxT("Email address:\t%s\n"), wxGetEmailAddress().c_str());
1552
1553 wxPuts(wxEmptyString);
1554 }
1555
1556 #endif // TEST_INFO_FUNCTIONS
1557
1558 // ----------------------------------------------------------------------------
1559 // path list
1560 // ----------------------------------------------------------------------------
1561
1562 #ifdef TEST_PATHLIST
1563
1564 #ifdef __UNIX__
1565 #define CMD_IN_PATH wxT("ls")
1566 #else
1567 #define CMD_IN_PATH wxT("command.com")
1568 #endif
1569
1570 static void TestPathList()
1571 {
1572 wxPuts(wxT("*** Testing wxPathList ***\n"));
1573
1574 wxPathList pathlist;
1575 pathlist.AddEnvList(wxT("PATH"));
1576 wxString path = pathlist.FindValidPath(CMD_IN_PATH);
1577 if ( path.empty() )
1578 {
1579 wxPrintf(wxT("ERROR: command not found in the path.\n"));
1580 }
1581 else
1582 {
1583 wxPrintf(wxT("Command found in the path as '%s'.\n"), path.c_str());
1584 }
1585 }
1586
1587 #endif // TEST_PATHLIST
1588
1589 // ----------------------------------------------------------------------------
1590 // regular expressions
1591 // ----------------------------------------------------------------------------
1592
1593 #if defined TEST_REGEX && TEST_INTERACTIVE
1594
1595 #include "wx/regex.h"
1596
1597 static void TestRegExInteractive()
1598 {
1599 wxPuts(wxT("*** Testing RE interactively ***"));
1600
1601 for ( ;; )
1602 {
1603 wxChar pattern[128];
1604 wxPrintf(wxT("\nEnter a pattern: "));
1605 if ( !wxFgets(pattern, WXSIZEOF(pattern), stdin) )
1606 break;
1607
1608 // kill the last '\n'
1609 pattern[wxStrlen(pattern) - 1] = 0;
1610
1611 wxRegEx re;
1612 if ( !re.Compile(pattern) )
1613 {
1614 continue;
1615 }
1616
1617 wxChar text[128];
1618 for ( ;; )
1619 {
1620 wxPrintf(wxT("Enter text to match: "));
1621 if ( !wxFgets(text, WXSIZEOF(text), stdin) )
1622 break;
1623
1624 // kill the last '\n'
1625 text[wxStrlen(text) - 1] = 0;
1626
1627 if ( !re.Matches(text) )
1628 {
1629 wxPrintf(wxT("No match.\n"));
1630 }
1631 else
1632 {
1633 wxPrintf(wxT("Pattern matches at '%s'\n"), re.GetMatch(text).c_str());
1634
1635 size_t start, len;
1636 for ( size_t n = 1; ; n++ )
1637 {
1638 if ( !re.GetMatch(&start, &len, n) )
1639 {
1640 break;
1641 }
1642
1643 wxPrintf(wxT("Subexpr %u matched '%s'\n"),
1644 n, wxString(text + start, len).c_str());
1645 }
1646 }
1647 }
1648 }
1649 }
1650
1651 #endif // TEST_REGEX
1652
1653 // ----------------------------------------------------------------------------
1654 // printf() tests
1655 // ----------------------------------------------------------------------------
1656
1657 /*
1658 NB: this stuff was taken from the glibc test suite and modified to build
1659 in wxWidgets: if I read the copyright below properly, this shouldn't
1660 be a problem
1661 */
1662
1663 #ifdef TEST_PRINTF
1664
1665 #ifdef wxTEST_PRINTF
1666 // use our functions from wxchar.cpp
1667 #undef wxPrintf
1668 #undef wxSprintf
1669
1670 // NB: do _not_ use WX_ATTRIBUTE_PRINTF here, we have some invalid formats
1671 // in the tests below
1672 int wxPrintf( const wxChar *format, ... );
1673 int wxSprintf( wxChar *str, const wxChar *format, ... );
1674 #endif
1675
1676 #include "wx/longlong.h"
1677
1678 #include <float.h>
1679
1680 static void rfg1 (void);
1681 static void rfg2 (void);
1682
1683
1684 static void
1685 fmtchk (const wxChar *fmt)
1686 {
1687 (void) wxPrintf(wxT("%s:\t`"), fmt);
1688 (void) wxPrintf(fmt, 0x12);
1689 (void) wxPrintf(wxT("'\n"));
1690 }
1691
1692 static void
1693 fmtst1chk (const wxChar *fmt)
1694 {
1695 (void) wxPrintf(wxT("%s:\t`"), fmt);
1696 (void) wxPrintf(fmt, 4, 0x12);
1697 (void) wxPrintf(wxT("'\n"));
1698 }
1699
1700 static void
1701 fmtst2chk (const wxChar *fmt)
1702 {
1703 (void) wxPrintf(wxT("%s:\t`"), fmt);
1704 (void) wxPrintf(fmt, 4, 4, 0x12);
1705 (void) wxPrintf(wxT("'\n"));
1706 }
1707
1708 /* This page is covered by the following copyright: */
1709
1710 /* (C) Copyright C E Chew
1711 *
1712 * Feel free to copy, use and distribute this software provided:
1713 *
1714 * 1. you do not pretend that you wrote it
1715 * 2. you leave this copyright notice intact.
1716 */
1717
1718 /*
1719 * Extracted from exercise.c for glibc-1.05 bug report by Bruce Evans.
1720 */
1721
1722 #define DEC -123
1723 #define INT 255
1724 #define UNS (~0)
1725
1726 /* Formatted Output Test
1727 *
1728 * This exercises the output formatting code.
1729 */
1730
1731 wxChar *PointerNull = NULL;
1732
1733 static void
1734 fp_test (void)
1735 {
1736 int i, j, k, l;
1737 wxChar buf[7];
1738 wxChar *prefix = buf;
1739 wxChar tp[20];
1740
1741 wxPuts(wxT("\nFormatted output test"));
1742 wxPrintf(wxT("prefix 6d 6o 6x 6X 6u\n"));
1743 wxStrcpy(prefix, wxT("%"));
1744 for (i = 0; i < 2; i++) {
1745 for (j = 0; j < 2; j++) {
1746 for (k = 0; k < 2; k++) {
1747 for (l = 0; l < 2; l++) {
1748 wxStrcpy(prefix, wxT("%"));
1749 if (i == 0) wxStrcat(prefix, wxT("-"));
1750 if (j == 0) wxStrcat(prefix, wxT("+"));
1751 if (k == 0) wxStrcat(prefix, wxT("#"));
1752 if (l == 0) wxStrcat(prefix, wxT("0"));
1753 wxPrintf(wxT("%5s |"), prefix);
1754 wxStrcpy(tp, prefix);
1755 wxStrcat(tp, wxT("6d |"));
1756 wxPrintf(tp, DEC);
1757 wxStrcpy(tp, prefix);
1758 wxStrcat(tp, wxT("6o |"));
1759 wxPrintf(tp, INT);
1760 wxStrcpy(tp, prefix);
1761 wxStrcat(tp, wxT("6x |"));
1762 wxPrintf(tp, INT);
1763 wxStrcpy(tp, prefix);
1764 wxStrcat(tp, wxT("6X |"));
1765 wxPrintf(tp, INT);
1766 wxStrcpy(tp, prefix);
1767 wxStrcat(tp, wxT("6u |"));
1768 wxPrintf(tp, UNS);
1769 wxPrintf(wxT("\n"));
1770 }
1771 }
1772 }
1773 }
1774 wxPrintf(wxT("%10s\n"), PointerNull);
1775 wxPrintf(wxT("%-10s\n"), PointerNull);
1776 }
1777
1778 static void TestPrintf()
1779 {
1780 static wxChar shortstr[] = wxT("Hi, Z.");
1781 static wxChar longstr[] = wxT("Good morning, Doctor Chandra. This is Hal. \
1782 I am ready for my first lesson today.");
1783 int result = 0;
1784 wxString test_format;
1785
1786 fmtchk(wxT("%.4x"));
1787 fmtchk(wxT("%04x"));
1788 fmtchk(wxT("%4.4x"));
1789 fmtchk(wxT("%04.4x"));
1790 fmtchk(wxT("%4.3x"));
1791 fmtchk(wxT("%04.3x"));
1792
1793 fmtst1chk(wxT("%.*x"));
1794 fmtst1chk(wxT("%0*x"));
1795 fmtst2chk(wxT("%*.*x"));
1796 fmtst2chk(wxT("%0*.*x"));
1797
1798 wxString bad_format = wxT("bad format:\t\"%b\"\n");
1799 wxPrintf(bad_format.c_str());
1800 wxPrintf(wxT("nil pointer (padded):\t\"%10p\"\n"), (void *) NULL);
1801
1802 wxPrintf(wxT("decimal negative:\t\"%d\"\n"), -2345);
1803 wxPrintf(wxT("octal negative:\t\"%o\"\n"), -2345);
1804 wxPrintf(wxT("hex negative:\t\"%x\"\n"), -2345);
1805 wxPrintf(wxT("long decimal number:\t\"%ld\"\n"), -123456L);
1806 wxPrintf(wxT("long octal negative:\t\"%lo\"\n"), -2345L);
1807 wxPrintf(wxT("long unsigned decimal number:\t\"%lu\"\n"), -123456L);
1808 wxPrintf(wxT("zero-padded LDN:\t\"%010ld\"\n"), -123456L);
1809 test_format = wxT("left-adjusted ZLDN:\t\"%-010ld\"\n");
1810 wxPrintf(test_format.c_str(), -123456);
1811 wxPrintf(wxT("space-padded LDN:\t\"%10ld\"\n"), -123456L);
1812 wxPrintf(wxT("left-adjusted SLDN:\t\"%-10ld\"\n"), -123456L);
1813
1814 test_format = wxT("zero-padded string:\t\"%010s\"\n");
1815 wxPrintf(test_format.c_str(), shortstr);
1816 test_format = wxT("left-adjusted Z string:\t\"%-010s\"\n");
1817 wxPrintf(test_format.c_str(), shortstr);
1818 wxPrintf(wxT("space-padded string:\t\"%10s\"\n"), shortstr);
1819 wxPrintf(wxT("left-adjusted S string:\t\"%-10s\"\n"), shortstr);
1820 wxPrintf(wxT("null string:\t\"%s\"\n"), PointerNull);
1821 wxPrintf(wxT("limited string:\t\"%.22s\"\n"), longstr);
1822
1823 wxPrintf(wxT("e-style >= 1:\t\"%e\"\n"), 12.34);
1824 wxPrintf(wxT("e-style >= .1:\t\"%e\"\n"), 0.1234);
1825 wxPrintf(wxT("e-style < .1:\t\"%e\"\n"), 0.001234);
1826 wxPrintf(wxT("e-style big:\t\"%.60e\"\n"), 1e20);
1827 wxPrintf(wxT("e-style == .1:\t\"%e\"\n"), 0.1);
1828 wxPrintf(wxT("f-style >= 1:\t\"%f\"\n"), 12.34);
1829 wxPrintf(wxT("f-style >= .1:\t\"%f\"\n"), 0.1234);
1830 wxPrintf(wxT("f-style < .1:\t\"%f\"\n"), 0.001234);
1831 wxPrintf(wxT("g-style >= 1:\t\"%g\"\n"), 12.34);
1832 wxPrintf(wxT("g-style >= .1:\t\"%g\"\n"), 0.1234);
1833 wxPrintf(wxT("g-style < .1:\t\"%g\"\n"), 0.001234);
1834 wxPrintf(wxT("g-style big:\t\"%.60g\"\n"), 1e20);
1835
1836 wxPrintf (wxT(" %6.5f\n"), .099999999860301614);
1837 wxPrintf (wxT(" %6.5f\n"), .1);
1838 wxPrintf (wxT("x%5.4fx\n"), .5);
1839
1840 wxPrintf (wxT("%#03x\n"), 1);
1841
1842 //wxPrintf (wxT("something really insane: %.10000f\n"), 1.0);
1843
1844 {
1845 double d = FLT_MIN;
1846 int niter = 17;
1847
1848 while (niter-- != 0)
1849 wxPrintf (wxT("%.17e\n"), d / 2);
1850 fflush (stdout);
1851 }
1852
1853 #ifndef __WATCOMC__
1854 // Open Watcom cause compiler error here
1855 // Error! E173: col(24) floating-point constant too small to represent
1856 wxPrintf (wxT("%15.5e\n"), 4.9406564584124654e-324);
1857 #endif
1858
1859 #define FORMAT wxT("|%12.4f|%12.4e|%12.4g|\n")
1860 wxPrintf (FORMAT, 0.0, 0.0, 0.0);
1861 wxPrintf (FORMAT, 1.0, 1.0, 1.0);
1862 wxPrintf (FORMAT, -1.0, -1.0, -1.0);
1863 wxPrintf (FORMAT, 100.0, 100.0, 100.0);
1864 wxPrintf (FORMAT, 1000.0, 1000.0, 1000.0);
1865 wxPrintf (FORMAT, 10000.0, 10000.0, 10000.0);
1866 wxPrintf (FORMAT, 12345.0, 12345.0, 12345.0);
1867 wxPrintf (FORMAT, 100000.0, 100000.0, 100000.0);
1868 wxPrintf (FORMAT, 123456.0, 123456.0, 123456.0);
1869 #undef FORMAT
1870
1871 {
1872 wxChar buf[20];
1873 int rc = wxSnprintf (buf, WXSIZEOF(buf), wxT("%30s"), wxT("foo"));
1874
1875 wxPrintf(wxT("snprintf (\"%%30s\", \"foo\") == %d, \"%.*s\"\n"),
1876 rc, WXSIZEOF(buf), buf);
1877 #if 0
1878 wxChar buf2[512];
1879 wxPrintf ("snprintf (\"%%.999999u\", 10)\n",
1880 wxSnprintf(buf2, WXSIZEOFbuf2), "%.999999u", 10));
1881 #endif
1882 }
1883
1884 fp_test ();
1885
1886 wxPrintf (wxT("%e should be 1.234568e+06\n"), 1234567.8);
1887 wxPrintf (wxT("%f should be 1234567.800000\n"), 1234567.8);
1888 wxPrintf (wxT("%g should be 1.23457e+06\n"), 1234567.8);
1889 wxPrintf (wxT("%g should be 123.456\n"), 123.456);
1890 wxPrintf (wxT("%g should be 1e+06\n"), 1000000.0);
1891 wxPrintf (wxT("%g should be 10\n"), 10.0);
1892 wxPrintf (wxT("%g should be 0.02\n"), 0.02);
1893
1894 {
1895 double x=1.0;
1896 wxPrintf(wxT("%.17f\n"),(1.0/x/10.0+1.0)*x-x);
1897 }
1898
1899 {
1900 wxChar buf[200];
1901
1902 wxSprintf(buf,wxT("%*s%*s%*s"),-1,wxT("one"),-20,wxT("two"),-30,wxT("three"));
1903
1904 result |= wxStrcmp (buf,
1905 wxT("onetwo three "));
1906
1907 wxPuts (result != 0 ? wxT("Test failed!") : wxT("Test ok."));
1908 }
1909
1910 #ifdef wxLongLong_t
1911 {
1912 wxChar buf[200];
1913
1914 wxSprintf(buf, "%07" wxLongLongFmtSpec "o", wxLL(040000000000));
1915 #if 0
1916 // for some reason below line fails under Borland
1917 wxPrintf (wxT("sprintf (buf, \"%%07Lo\", 040000000000ll) = %s"), buf);
1918 #endif
1919
1920 if (wxStrcmp (buf, wxT("40000000000")) != 0)
1921 {
1922 result = 1;
1923 wxPuts (wxT("\tFAILED"));
1924 }
1925 wxUnusedVar(result);
1926 wxPuts (wxEmptyString);
1927 }
1928 #endif // wxLongLong_t
1929
1930 wxPrintf (wxT("printf (\"%%hhu\", %u) = %hhu\n"), UCHAR_MAX + 2, UCHAR_MAX + 2);
1931 wxPrintf (wxT("printf (\"%%hu\", %u) = %hu\n"), USHRT_MAX + 2, USHRT_MAX + 2);
1932
1933 wxPuts (wxT("--- Should be no further output. ---"));
1934 rfg1 ();
1935 rfg2 ();
1936
1937 #if 0
1938 {
1939 wxChar bytes[7];
1940 wxChar buf[20];
1941
1942 memset (bytes, '\xff', sizeof bytes);
1943 wxSprintf (buf, wxT("foo%hhn\n"), &bytes[3]);
1944 if (bytes[0] != '\xff' || bytes[1] != '\xff' || bytes[2] != '\xff'
1945 || bytes[4] != '\xff' || bytes[5] != '\xff' || bytes[6] != '\xff')
1946 {
1947 wxPuts (wxT("%hhn overwrite more bytes"));
1948 result = 1;
1949 }
1950 if (bytes[3] != 3)
1951 {
1952 wxPuts (wxT("%hhn wrote incorrect value"));
1953 result = 1;
1954 }
1955 }
1956 #endif
1957 }
1958
1959 static void
1960 rfg1 (void)
1961 {
1962 wxChar buf[100];
1963
1964 wxSprintf (buf, wxT("%5.s"), wxT("xyz"));
1965 if (wxStrcmp (buf, wxT(" ")) != 0)
1966 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT(" "));
1967 wxSprintf (buf, wxT("%5.f"), 33.3);
1968 if (wxStrcmp (buf, wxT(" 33")) != 0)
1969 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT(" 33"));
1970 wxSprintf (buf, wxT("%8.e"), 33.3e7);
1971 if (wxStrcmp (buf, wxT(" 3e+08")) != 0)
1972 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT(" 3e+08"));
1973 wxSprintf (buf, wxT("%8.E"), 33.3e7);
1974 if (wxStrcmp (buf, wxT(" 3E+08")) != 0)
1975 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT(" 3E+08"));
1976 wxSprintf (buf, wxT("%.g"), 33.3);
1977 if (wxStrcmp (buf, wxT("3e+01")) != 0)
1978 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT("3e+01"));
1979 wxSprintf (buf, wxT("%.G"), 33.3);
1980 if (wxStrcmp (buf, wxT("3E+01")) != 0)
1981 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT("3E+01"));
1982 }
1983
1984 static void
1985 rfg2 (void)
1986 {
1987 int prec;
1988 wxChar buf[100];
1989 wxString test_format;
1990
1991 prec = 0;
1992 wxSprintf (buf, wxT("%.*g"), prec, 3.3);
1993 if (wxStrcmp (buf, wxT("3")) != 0)
1994 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT("3"));
1995 prec = 0;
1996 wxSprintf (buf, wxT("%.*G"), prec, 3.3);
1997 if (wxStrcmp (buf, wxT("3")) != 0)
1998 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT("3"));
1999 prec = 0;
2000 wxSprintf (buf, wxT("%7.*G"), prec, 3.33);
2001 if (wxStrcmp (buf, wxT(" 3")) != 0)
2002 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT(" 3"));
2003 prec = 3;
2004 test_format = wxT("%04.*o");
2005 wxSprintf (buf, test_format.c_str(), prec, 33);
2006 if (wxStrcmp (buf, wxT(" 041")) != 0)
2007 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT(" 041"));
2008 prec = 7;
2009 test_format = wxT("%09.*u");
2010 wxSprintf (buf, test_format.c_str(), prec, 33);
2011 if (wxStrcmp (buf, wxT(" 0000033")) != 0)
2012 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT(" 0000033"));
2013 prec = 3;
2014 test_format = wxT("%04.*x");
2015 wxSprintf (buf, test_format.c_str(), prec, 33);
2016 if (wxStrcmp (buf, wxT(" 021")) != 0)
2017 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT(" 021"));
2018 prec = 3;
2019 test_format = wxT("%04.*X");
2020 wxSprintf (buf, test_format.c_str(), prec, 33);
2021 if (wxStrcmp (buf, wxT(" 021")) != 0)
2022 wxPrintf (wxT("got: '%s', expected: '%s'\n"), buf, wxT(" 021"));
2023 }
2024
2025 #endif // TEST_PRINTF
2026
2027 // ----------------------------------------------------------------------------
2028 // registry and related stuff
2029 // ----------------------------------------------------------------------------
2030
2031 // this is for MSW only
2032 #ifndef __WXMSW__
2033 #undef TEST_REGCONF
2034 #undef TEST_REGISTRY
2035 #endif
2036
2037 #ifdef TEST_REGCONF
2038
2039 #include "wx/confbase.h"
2040 #include "wx/msw/regconf.h"
2041
2042 #if 0
2043 static void TestRegConfWrite()
2044 {
2045 wxConfig *config = new wxConfig(wxT("myapp"));
2046 config->SetPath(wxT("/group1"));
2047 config->Write(wxT("entry1"), wxT("foo"));
2048 config->SetPath(wxT("/group2"));
2049 config->Write(wxT("entry1"), wxT("bar"));
2050 }
2051 #endif
2052
2053 static void TestRegConfRead()
2054 {
2055 wxRegConfig *config = new wxRegConfig(wxT("myapp"));
2056
2057 wxString str;
2058 long dummy;
2059 config->SetPath(wxT("/"));
2060 wxPuts(wxT("Enumerating / subgroups:"));
2061 bool bCont = config->GetFirstGroup(str, dummy);
2062 while(bCont)
2063 {
2064 wxPuts(str);
2065 bCont = config->GetNextGroup(str, dummy);
2066 }
2067 }
2068
2069 #endif // TEST_REGCONF
2070
2071 #ifdef TEST_REGISTRY
2072
2073 #include "wx/msw/registry.h"
2074
2075 // I chose this one because I liked its name, but it probably only exists under
2076 // NT
2077 static const wxChar *TESTKEY =
2078 wxT("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2079
2080 static void TestRegistryRead()
2081 {
2082 wxPuts(wxT("*** testing registry reading ***"));
2083
2084 wxRegKey key(TESTKEY);
2085 wxPrintf(wxT("The test key name is '%s'.\n"), key.GetName().c_str());
2086 if ( !key.Open() )
2087 {
2088 wxPuts(wxT("ERROR: test key can't be opened, aborting test."));
2089
2090 return;
2091 }
2092
2093 size_t nSubKeys, nValues;
2094 if ( key.GetKeyInfo(&nSubKeys, NULL, &nValues, NULL) )
2095 {
2096 wxPrintf(wxT("It has %u subkeys and %u values.\n"), nSubKeys, nValues);
2097 }
2098
2099 wxPrintf(wxT("Enumerating values:\n"));
2100
2101 long dummy;
2102 wxString value;
2103 bool cont = key.GetFirstValue(value, dummy);
2104 while ( cont )
2105 {
2106 wxPrintf(wxT("Value '%s': type "), value.c_str());
2107 switch ( key.GetValueType(value) )
2108 {
2109 case wxRegKey::Type_None: wxPrintf(wxT("ERROR (none)")); break;
2110 case wxRegKey::Type_String: wxPrintf(wxT("SZ")); break;
2111 case wxRegKey::Type_Expand_String: wxPrintf(wxT("EXPAND_SZ")); break;
2112 case wxRegKey::Type_Binary: wxPrintf(wxT("BINARY")); break;
2113 case wxRegKey::Type_Dword: wxPrintf(wxT("DWORD")); break;
2114 case wxRegKey::Type_Multi_String: wxPrintf(wxT("MULTI_SZ")); break;
2115 default: wxPrintf(wxT("other (unknown)")); break;
2116 }
2117
2118 wxPrintf(wxT(", value = "));
2119 if ( key.IsNumericValue(value) )
2120 {
2121 long val;
2122 key.QueryValue(value, &val);
2123 wxPrintf(wxT("%ld"), val);
2124 }
2125 else // string
2126 {
2127 wxString val;
2128 key.QueryValue(value, val);
2129 wxPrintf(wxT("'%s'"), val.c_str());
2130
2131 key.QueryRawValue(value, val);
2132 wxPrintf(wxT(" (raw value '%s')"), val.c_str());
2133 }
2134
2135 wxPutchar('\n');
2136
2137 cont = key.GetNextValue(value, dummy);
2138 }
2139 }
2140
2141 static void TestRegistryAssociation()
2142 {
2143 /*
2144 The second call to deleteself genertaes an error message, with a
2145 messagebox saying .flo is crucial to system operation, while the .ddf
2146 call also fails, but with no error message
2147 */
2148
2149 wxRegKey key;
2150
2151 key.SetName(wxT("HKEY_CLASSES_ROOT\\.ddf") );
2152 key.Create();
2153 key = wxT("ddxf_auto_file") ;
2154 key.SetName(wxT("HKEY_CLASSES_ROOT\\.flo") );
2155 key.Create();
2156 key = wxT("ddxf_auto_file") ;
2157 key.SetName(wxT("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2158 key.Create();
2159 key = wxT("program,0") ;
2160 key.SetName(wxT("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2161 key.Create();
2162 key = wxT("program \"%1\"") ;
2163
2164 key.SetName(wxT("HKEY_CLASSES_ROOT\\.ddf") );
2165 key.DeleteSelf();
2166 key.SetName(wxT("HKEY_CLASSES_ROOT\\.flo") );
2167 key.DeleteSelf();
2168 key.SetName(wxT("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2169 key.DeleteSelf();
2170 key.SetName(wxT("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2171 key.DeleteSelf();
2172 }
2173
2174 #endif // TEST_REGISTRY
2175
2176 // ----------------------------------------------------------------------------
2177 // scope guard
2178 // ----------------------------------------------------------------------------
2179
2180 #ifdef TEST_SCOPEGUARD
2181
2182 #include "wx/scopeguard.h"
2183
2184 static void function0() { puts("function0()"); }
2185 static void function1(int n) { printf("function1(%d)\n", n); }
2186 static void function2(double x, char c) { printf("function2(%g, %c)\n", x, c); }
2187
2188 struct Object
2189 {
2190 void method0() { printf("method0()\n"); }
2191 void method1(int n) { printf("method1(%d)\n", n); }
2192 void method2(double x, char c) { printf("method2(%g, %c)\n", x, c); }
2193 };
2194
2195 static void TestScopeGuard()
2196 {
2197 wxON_BLOCK_EXIT0(function0);
2198 wxON_BLOCK_EXIT1(function1, 17);
2199 wxON_BLOCK_EXIT2(function2, 3.14, 'p');
2200
2201 Object obj;
2202 wxON_BLOCK_EXIT_OBJ0(obj, Object::method0);
2203 wxON_BLOCK_EXIT_OBJ1(obj, Object::method1, 7);
2204 wxON_BLOCK_EXIT_OBJ2(obj, Object::method2, 2.71, 'e');
2205
2206 wxScopeGuard dismissed = wxMakeGuard(function0);
2207 dismissed.Dismiss();
2208 }
2209
2210 #endif
2211
2212 // ----------------------------------------------------------------------------
2213 // sockets
2214 // ----------------------------------------------------------------------------
2215
2216 #ifdef TEST_SOCKETS
2217
2218 #include "wx/socket.h"
2219 #include "wx/protocol/protocol.h"
2220 #include "wx/protocol/http.h"
2221
2222 static void TestSocketServer()
2223 {
2224 wxPuts(wxT("*** Testing wxSocketServer ***\n"));
2225
2226 static const int PORT = 3000;
2227
2228 wxIPV4address addr;
2229 addr.Service(PORT);
2230
2231 wxSocketServer *server = new wxSocketServer(addr);
2232 if ( !server->Ok() )
2233 {
2234 wxPuts(wxT("ERROR: failed to bind"));
2235
2236 return;
2237 }
2238
2239 bool quit = false;
2240 while ( !quit )
2241 {
2242 wxPrintf(wxT("Server: waiting for connection on port %d...\n"), PORT);
2243
2244 wxSocketBase *socket = server->Accept();
2245 if ( !socket )
2246 {
2247 wxPuts(wxT("ERROR: wxSocketServer::Accept() failed."));
2248 break;
2249 }
2250
2251 wxPuts(wxT("Server: got a client."));
2252
2253 server->SetTimeout(60); // 1 min
2254
2255 bool close = false;
2256 while ( !close && socket->IsConnected() )
2257 {
2258 wxString s;
2259 wxChar ch = wxT('\0');
2260 for ( ;; )
2261 {
2262 if ( socket->Read(&ch, sizeof(ch)).Error() )
2263 {
2264 // don't log error if the client just close the connection
2265 if ( socket->IsConnected() )
2266 {
2267 wxPuts(wxT("ERROR: in wxSocket::Read."));
2268 }
2269
2270 break;
2271 }
2272
2273 if ( ch == '\r' )
2274 continue;
2275
2276 if ( ch == '\n' )
2277 break;
2278
2279 s += ch;
2280 }
2281
2282 if ( ch != '\n' )
2283 {
2284 break;
2285 }
2286
2287 wxPrintf(wxT("Server: got '%s'.\n"), s.c_str());
2288 if ( s == wxT("close") )
2289 {
2290 wxPuts(wxT("Closing connection"));
2291
2292 close = true;
2293 }
2294 else if ( s == wxT("quit") )
2295 {
2296 close =
2297 quit = true;
2298
2299 wxPuts(wxT("Shutting down the server"));
2300 }
2301 else // not a special command
2302 {
2303 socket->Write(s.MakeUpper().c_str(), s.length());
2304 socket->Write("\r\n", 2);
2305 wxPrintf(wxT("Server: wrote '%s'.\n"), s.c_str());
2306 }
2307 }
2308
2309 if ( !close )
2310 {
2311 wxPuts(wxT("Server: lost a client unexpectedly."));
2312 }
2313
2314 socket->Destroy();
2315 }
2316
2317 // same as "delete server" but is consistent with GUI programs
2318 server->Destroy();
2319 }
2320
2321 static void TestSocketClient()
2322 {
2323 wxPuts(wxT("*** Testing wxSocketClient ***\n"));
2324
2325 static const wxChar *hostname = wxT("www.wxwidgets.org");
2326
2327 wxIPV4address addr;
2328 addr.Hostname(hostname);
2329 addr.Service(80);
2330
2331 wxPrintf(wxT("--- Attempting to connect to %s:80...\n"), hostname);
2332
2333 wxSocketClient client;
2334 if ( !client.Connect(addr) )
2335 {
2336 wxPrintf(wxT("ERROR: failed to connect to %s\n"), hostname);
2337 }
2338 else
2339 {
2340 wxPrintf(wxT("--- Connected to %s:%u...\n"),
2341 addr.Hostname().c_str(), addr.Service());
2342
2343 wxChar buf[8192];
2344
2345 // could use simply "GET" here I suppose
2346 wxString cmdGet =
2347 wxString::Format(wxT("GET http://%s/\r\n"), hostname);
2348 client.Write(cmdGet, cmdGet.length());
2349 wxPrintf(wxT("--- Sent command '%s' to the server\n"),
2350 MakePrintable(cmdGet).c_str());
2351 client.Read(buf, WXSIZEOF(buf));
2352 wxPrintf(wxT("--- Server replied:\n%s"), buf);
2353 }
2354 }
2355
2356 #endif // TEST_SOCKETS
2357
2358 // ----------------------------------------------------------------------------
2359 // FTP
2360 // ----------------------------------------------------------------------------
2361
2362 #ifdef TEST_FTP
2363
2364 #include "wx/protocol/ftp.h"
2365 #include "wx/protocol/log.h"
2366
2367 #define FTP_ANONYMOUS
2368
2369 static wxFTP *ftp;
2370
2371 #ifdef FTP_ANONYMOUS
2372 static const wxChar *directory = wxT("/pub");
2373 static const wxChar *filename = wxT("welcome.msg");
2374 #else
2375 static const wxChar *directory = wxT("/etc");
2376 static const wxChar *filename = wxT("issue");
2377 #endif
2378
2379 static bool TestFtpConnect()
2380 {
2381 wxPuts(wxT("*** Testing FTP connect ***"));
2382
2383 #ifdef FTP_ANONYMOUS
2384 static const wxChar *hostname = wxT("ftp.wxwidgets.org");
2385
2386 wxPrintf(wxT("--- Attempting to connect to %s:21 anonymously...\n"), hostname);
2387 #else // !FTP_ANONYMOUS
2388 static const wxChar *hostname = "localhost";
2389
2390 wxChar user[256];
2391 wxFgets(user, WXSIZEOF(user), stdin);
2392 user[wxStrlen(user) - 1] = '\0'; // chop off '\n'
2393 ftp->SetUser(user);
2394
2395 wxChar password[256];
2396 wxPrintf(wxT("Password for %s: "), password);
2397 wxFgets(password, WXSIZEOF(password), stdin);
2398 password[wxStrlen(password) - 1] = '\0'; // chop off '\n'
2399 ftp->SetPassword(password);
2400
2401 wxPrintf(wxT("--- Attempting to connect to %s:21 as %s...\n"), hostname, user);
2402 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2403
2404 if ( !ftp->Connect(hostname) )
2405 {
2406 wxPrintf(wxT("ERROR: failed to connect to %s\n"), hostname);
2407
2408 return false;
2409 }
2410 else
2411 {
2412 wxPrintf(wxT("--- Connected to %s, current directory is '%s'\n"),
2413 hostname, ftp->Pwd().c_str());
2414 ftp->Close();
2415 }
2416
2417 return true;
2418 }
2419
2420 static void TestFtpList()
2421 {
2422 wxPuts(wxT("*** Testing wxFTP file listing ***\n"));
2423
2424 // test CWD
2425 if ( !ftp->ChDir(directory) )
2426 {
2427 wxPrintf(wxT("ERROR: failed to cd to %s\n"), directory);
2428 }
2429
2430 wxPrintf(wxT("Current directory is '%s'\n"), ftp->Pwd().c_str());
2431
2432 // test NLIST and LIST
2433 wxArrayString files;
2434 if ( !ftp->GetFilesList(files) )
2435 {
2436 wxPuts(wxT("ERROR: failed to get NLIST of files"));
2437 }
2438 else
2439 {
2440 wxPrintf(wxT("Brief list of files under '%s':\n"), ftp->Pwd().c_str());
2441 size_t count = files.GetCount();
2442 for ( size_t n = 0; n < count; n++ )
2443 {
2444 wxPrintf(wxT("\t%s\n"), files[n].c_str());
2445 }
2446 wxPuts(wxT("End of the file list"));
2447 }
2448
2449 if ( !ftp->GetDirList(files) )
2450 {
2451 wxPuts(wxT("ERROR: failed to get LIST of files"));
2452 }
2453 else
2454 {
2455 wxPrintf(wxT("Detailed list of files under '%s':\n"), ftp->Pwd().c_str());
2456 size_t count = files.GetCount();
2457 for ( size_t n = 0; n < count; n++ )
2458 {
2459 wxPrintf(wxT("\t%s\n"), files[n].c_str());
2460 }
2461 wxPuts(wxT("End of the file list"));
2462 }
2463
2464 if ( !ftp->ChDir(wxT("..")) )
2465 {
2466 wxPuts(wxT("ERROR: failed to cd to .."));
2467 }
2468
2469 wxPrintf(wxT("Current directory is '%s'\n"), ftp->Pwd().c_str());
2470 }
2471
2472 static void TestFtpDownload()
2473 {
2474 wxPuts(wxT("*** Testing wxFTP download ***\n"));
2475
2476 // test RETR
2477 wxInputStream *in = ftp->GetInputStream(filename);
2478 if ( !in )
2479 {
2480 wxPrintf(wxT("ERROR: couldn't get input stream for %s\n"), filename);
2481 }
2482 else
2483 {
2484 size_t size = in->GetSize();
2485 wxPrintf(wxT("Reading file %s (%u bytes)..."), filename, size);
2486 fflush(stdout);
2487
2488 wxChar *data = new wxChar[size];
2489 if ( !in->Read(data, size) )
2490 {
2491 wxPuts(wxT("ERROR: read error"));
2492 }
2493 else
2494 {
2495 wxPrintf(wxT("\nContents of %s:\n%s\n"), filename, data);
2496 }
2497
2498 delete [] data;
2499 delete in;
2500 }
2501 }
2502
2503 static void TestFtpFileSize()
2504 {
2505 wxPuts(wxT("*** Testing FTP SIZE command ***"));
2506
2507 if ( !ftp->ChDir(directory) )
2508 {
2509 wxPrintf(wxT("ERROR: failed to cd to %s\n"), directory);
2510 }
2511
2512 wxPrintf(wxT("Current directory is '%s'\n"), ftp->Pwd().c_str());
2513
2514 if ( ftp->FileExists(filename) )
2515 {
2516 int size = ftp->GetFileSize(filename);
2517 if ( size == -1 )
2518 wxPrintf(wxT("ERROR: couldn't get size of '%s'\n"), filename);
2519 else
2520 wxPrintf(wxT("Size of '%s' is %d bytes.\n"), filename, size);
2521 }
2522 else
2523 {
2524 wxPrintf(wxT("ERROR: '%s' doesn't exist\n"), filename);
2525 }
2526 }
2527
2528 static void TestFtpMisc()
2529 {
2530 wxPuts(wxT("*** Testing miscellaneous wxFTP functions ***"));
2531
2532 if ( ftp->SendCommand(wxT("STAT")) != '2' )
2533 {
2534 wxPuts(wxT("ERROR: STAT failed"));
2535 }
2536 else
2537 {
2538 wxPrintf(wxT("STAT returned:\n\n%s\n"), ftp->GetLastResult().c_str());
2539 }
2540
2541 if ( ftp->SendCommand(wxT("HELP SITE")) != '2' )
2542 {
2543 wxPuts(wxT("ERROR: HELP SITE failed"));
2544 }
2545 else
2546 {
2547 wxPrintf(wxT("The list of site-specific commands:\n\n%s\n"),
2548 ftp->GetLastResult().c_str());
2549 }
2550 }
2551
2552 #if TEST_INTERACTIVE
2553
2554 static void TestFtpInteractive()
2555 {
2556 wxPuts(wxT("\n*** Interactive wxFTP test ***"));
2557
2558 wxChar buf[128];
2559
2560 for ( ;; )
2561 {
2562 wxPrintf(wxT("Enter FTP command: "));
2563 if ( !wxFgets(buf, WXSIZEOF(buf), stdin) )
2564 break;
2565
2566 // kill the last '\n'
2567 buf[wxStrlen(buf) - 1] = 0;
2568
2569 // special handling of LIST and NLST as they require data connection
2570 wxString start(buf, 4);
2571 start.MakeUpper();
2572 if ( start == wxT("LIST") || start == wxT("NLST") )
2573 {
2574 wxString wildcard;
2575 if ( wxStrlen(buf) > 4 )
2576 wildcard = buf + 5;
2577
2578 wxArrayString files;
2579 if ( !ftp->GetList(files, wildcard, start == wxT("LIST")) )
2580 {
2581 wxPrintf(wxT("ERROR: failed to get %s of files\n"), start.c_str());
2582 }
2583 else
2584 {
2585 wxPrintf(wxT("--- %s of '%s' under '%s':\n"),
2586 start.c_str(), wildcard.c_str(), ftp->Pwd().c_str());
2587 size_t count = files.GetCount();
2588 for ( size_t n = 0; n < count; n++ )
2589 {
2590 wxPrintf(wxT("\t%s\n"), files[n].c_str());
2591 }
2592 wxPuts(wxT("--- End of the file list"));
2593 }
2594 }
2595 else // !list
2596 {
2597 wxChar ch = ftp->SendCommand(buf);
2598 wxPrintf(wxT("Command %s"), ch ? wxT("succeeded") : wxT("failed"));
2599 if ( ch )
2600 {
2601 wxPrintf(wxT(" (return code %c)"), ch);
2602 }
2603
2604 wxPrintf(wxT(", server reply:\n%s\n\n"), ftp->GetLastResult().c_str());
2605 }
2606 }
2607
2608 wxPuts(wxT("\n*** done ***"));
2609 }
2610
2611 #endif // TEST_INTERACTIVE
2612
2613 static void TestFtpUpload()
2614 {
2615 wxPuts(wxT("*** Testing wxFTP uploading ***\n"));
2616
2617 // upload a file
2618 static const wxChar *file1 = wxT("test1");
2619 static const wxChar *file2 = wxT("test2");
2620 wxOutputStream *out = ftp->GetOutputStream(file1);
2621 if ( out )
2622 {
2623 wxPrintf(wxT("--- Uploading to %s ---\n"), file1);
2624 out->Write("First hello", 11);
2625 delete out;
2626 }
2627
2628 // send a command to check the remote file
2629 if ( ftp->SendCommand(wxString(wxT("STAT ")) + file1) != '2' )
2630 {
2631 wxPrintf(wxT("ERROR: STAT %s failed\n"), file1);
2632 }
2633 else
2634 {
2635 wxPrintf(wxT("STAT %s returned:\n\n%s\n"),
2636 file1, ftp->GetLastResult().c_str());
2637 }
2638
2639 out = ftp->GetOutputStream(file2);
2640 if ( out )
2641 {
2642 wxPrintf(wxT("--- Uploading to %s ---\n"), file1);
2643 out->Write("Second hello", 12);
2644 delete out;
2645 }
2646 }
2647
2648 #endif // TEST_FTP
2649
2650 // ----------------------------------------------------------------------------
2651 // stack backtrace
2652 // ----------------------------------------------------------------------------
2653
2654 #ifdef TEST_STACKWALKER
2655
2656 #if wxUSE_STACKWALKER
2657
2658 #include "wx/stackwalk.h"
2659
2660 class StackDump : public wxStackWalker
2661 {
2662 public:
2663 StackDump(const char *argv0)
2664 : wxStackWalker(argv0)
2665 {
2666 }
2667
2668 virtual void Walk(size_t skip = 1, size_t maxdepth = wxSTACKWALKER_MAX_DEPTH)
2669 {
2670 wxPuts(wxT("Stack dump:"));
2671
2672 wxStackWalker::Walk(skip, maxdepth);
2673 }
2674
2675 protected:
2676 virtual void OnStackFrame(const wxStackFrame& frame)
2677 {
2678 printf("[%2d] ", (int) frame.GetLevel());
2679
2680 wxString name = frame.GetName();
2681 if ( !name.empty() )
2682 {
2683 printf("%-20.40s", (const char*)name.mb_str());
2684 }
2685 else
2686 {
2687 printf("0x%08lx", (unsigned long)frame.GetAddress());
2688 }
2689
2690 if ( frame.HasSourceLocation() )
2691 {
2692 printf("\t%s:%d",
2693 (const char*)frame.GetFileName().mb_str(),
2694 (int)frame.GetLine());
2695 }
2696
2697 puts("");
2698
2699 wxString type, val;
2700 for ( size_t n = 0; frame.GetParam(n, &type, &name, &val); n++ )
2701 {
2702 printf("\t%s %s = %s\n", (const char*)type.mb_str(),
2703 (const char*)name.mb_str(),
2704 (const char*)val.mb_str());
2705 }
2706 }
2707 };
2708
2709 static void TestStackWalk(const char *argv0)
2710 {
2711 wxPuts(wxT("*** Testing wxStackWalker ***\n"));
2712
2713 StackDump dump(argv0);
2714 dump.Walk();
2715 }
2716
2717 #endif // wxUSE_STACKWALKER
2718
2719 #endif // TEST_STACKWALKER
2720
2721 // ----------------------------------------------------------------------------
2722 // standard paths
2723 // ----------------------------------------------------------------------------
2724
2725 #ifdef TEST_STDPATHS
2726
2727 #include "wx/stdpaths.h"
2728 #include "wx/wxchar.h" // wxPrintf
2729
2730 static void TestStandardPaths()
2731 {
2732 wxPuts(wxT("*** Testing wxStandardPaths ***\n"));
2733
2734 wxTheApp->SetAppName(wxT("console"));
2735
2736 wxStandardPathsBase& stdp = wxStandardPaths::Get();
2737 wxPrintf(wxT("Config dir (sys):\t%s\n"), stdp.GetConfigDir().c_str());
2738 wxPrintf(wxT("Config dir (user):\t%s\n"), stdp.GetUserConfigDir().c_str());
2739 wxPrintf(wxT("Data dir (sys):\t\t%s\n"), stdp.GetDataDir().c_str());
2740 wxPrintf(wxT("Data dir (sys local):\t%s\n"), stdp.GetLocalDataDir().c_str());
2741 wxPrintf(wxT("Data dir (user):\t%s\n"), stdp.GetUserDataDir().c_str());
2742 wxPrintf(wxT("Data dir (user local):\t%s\n"), stdp.GetUserLocalDataDir().c_str());
2743 wxPrintf(wxT("Documents dir:\t\t%s\n"), stdp.GetDocumentsDir().c_str());
2744 wxPrintf(wxT("Executable path:\t%s\n"), stdp.GetExecutablePath().c_str());
2745 wxPrintf(wxT("Plugins dir:\t\t%s\n"), stdp.GetPluginsDir().c_str());
2746 wxPrintf(wxT("Resources dir:\t\t%s\n"), stdp.GetResourcesDir().c_str());
2747 wxPrintf(wxT("Localized res. dir:\t%s\n"),
2748 stdp.GetLocalizedResourcesDir(wxT("fr")).c_str());
2749 wxPrintf(wxT("Message catalogs dir:\t%s\n"),
2750 stdp.GetLocalizedResourcesDir
2751 (
2752 wxT("fr"),
2753 wxStandardPaths::ResourceCat_Messages
2754 ).c_str());
2755 }
2756
2757 #endif // TEST_STDPATHS
2758
2759 // ----------------------------------------------------------------------------
2760 // streams
2761 // ----------------------------------------------------------------------------
2762
2763 #ifdef TEST_STREAMS
2764
2765 #include "wx/wfstream.h"
2766 #include "wx/mstream.h"
2767
2768 static void TestFileStream()
2769 {
2770 wxPuts(wxT("*** Testing wxFileInputStream ***"));
2771
2772 static const wxString filename = wxT("testdata.fs");
2773 {
2774 wxFileOutputStream fsOut(filename);
2775 fsOut.Write("foo", 3);
2776 }
2777
2778 {
2779 wxFileInputStream fsIn(filename);
2780 wxPrintf(wxT("File stream size: %u\n"), fsIn.GetSize());
2781 int c;
2782 while ( (c=fsIn.GetC()) != wxEOF )
2783 {
2784 wxPutchar(c);
2785 }
2786 }
2787
2788 if ( !wxRemoveFile(filename) )
2789 {
2790 wxPrintf(wxT("ERROR: failed to remove the file '%s'.\n"), filename.c_str());
2791 }
2792
2793 wxPuts(wxT("\n*** wxFileInputStream test done ***"));
2794 }
2795
2796 static void TestMemoryStream()
2797 {
2798 wxPuts(wxT("*** Testing wxMemoryOutputStream ***"));
2799
2800 wxMemoryOutputStream memOutStream;
2801 wxPrintf(wxT("Initially out stream offset: %lu\n"),
2802 (unsigned long)memOutStream.TellO());
2803
2804 for ( const wxChar *p = wxT("Hello, stream!"); *p; p++ )
2805 {
2806 memOutStream.PutC(*p);
2807 }
2808
2809 wxPrintf(wxT("Final out stream offset: %lu\n"),
2810 (unsigned long)memOutStream.TellO());
2811
2812 wxPuts(wxT("*** Testing wxMemoryInputStream ***"));
2813
2814 wxChar buf[1024];
2815 size_t len = memOutStream.CopyTo(buf, WXSIZEOF(buf));
2816
2817 wxMemoryInputStream memInpStream(buf, len);
2818 wxPrintf(wxT("Memory stream size: %u\n"), memInpStream.GetSize());
2819 int c;
2820 while ( (c=memInpStream.GetC()) != wxEOF )
2821 {
2822 wxPutchar(c);
2823 }
2824
2825 wxPuts(wxT("\n*** wxMemoryInputStream test done ***"));
2826 }
2827
2828 #endif // TEST_STREAMS
2829
2830 // ----------------------------------------------------------------------------
2831 // timers
2832 // ----------------------------------------------------------------------------
2833
2834 #ifdef TEST_TIMER
2835
2836 #include "wx/stopwatch.h"
2837 #include "wx/utils.h"
2838
2839 static void TestStopWatch()
2840 {
2841 wxPuts(wxT("*** Testing wxStopWatch ***\n"));
2842
2843 wxStopWatch sw;
2844 sw.Pause();
2845 wxPrintf(wxT("Initially paused, after 2 seconds time is..."));
2846 fflush(stdout);
2847 wxSleep(2);
2848 wxPrintf(wxT("\t%ldms\n"), sw.Time());
2849
2850 wxPrintf(wxT("Resuming stopwatch and sleeping 3 seconds..."));
2851 fflush(stdout);
2852 sw.Resume();
2853 wxSleep(3);
2854 wxPrintf(wxT("\telapsed time: %ldms\n"), sw.Time());
2855
2856 sw.Pause();
2857 wxPrintf(wxT("Pausing agan and sleeping 2 more seconds..."));
2858 fflush(stdout);
2859 wxSleep(2);
2860 wxPrintf(wxT("\telapsed time: %ldms\n"), sw.Time());
2861
2862 sw.Resume();
2863 wxPrintf(wxT("Finally resuming and sleeping 2 more seconds..."));
2864 fflush(stdout);
2865 wxSleep(2);
2866 wxPrintf(wxT("\telapsed time: %ldms\n"), sw.Time());
2867
2868 wxStopWatch sw2;
2869 wxPuts(wxT("\nChecking for 'backwards clock' bug..."));
2870 for ( size_t n = 0; n < 70; n++ )
2871 {
2872 sw2.Start();
2873
2874 for ( size_t m = 0; m < 100000; m++ )
2875 {
2876 if ( sw.Time() < 0 || sw2.Time() < 0 )
2877 {
2878 wxPuts(wxT("\ntime is negative - ERROR!"));
2879 }
2880 }
2881
2882 wxPutchar('.');
2883 fflush(stdout);
2884 }
2885
2886 wxPuts(wxT(", ok."));
2887 }
2888
2889 #include "wx/timer.h"
2890 #include "wx/evtloop.h"
2891
2892 void TestTimer()
2893 {
2894 wxPuts(wxT("*** Testing wxTimer ***\n"));
2895
2896 class MyTimer : public wxTimer
2897 {
2898 public:
2899 MyTimer() : wxTimer() { m_num = 0; }
2900
2901 virtual void Notify()
2902 {
2903 wxPrintf(wxT("%d"), m_num++);
2904 fflush(stdout);
2905
2906 if ( m_num == 10 )
2907 {
2908 wxPrintf(wxT("... exiting the event loop"));
2909 Stop();
2910
2911 wxEventLoop::GetActive()->Exit(0);
2912 wxPuts(wxT(", ok."));
2913 }
2914
2915 fflush(stdout);
2916 }
2917
2918 private:
2919 int m_num;
2920 };
2921
2922 wxEventLoop loop;
2923
2924 wxTimer timer1;
2925 timer1.Start(100, true /* one shot */);
2926 timer1.Stop();
2927 timer1.Start(100, true /* one shot */);
2928
2929 MyTimer timer;
2930 timer.Start(500);
2931
2932 loop.Run();
2933 }
2934
2935 #endif // TEST_TIMER
2936
2937 // ----------------------------------------------------------------------------
2938 // wxVolume tests
2939 // ----------------------------------------------------------------------------
2940
2941 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
2942 #undef TEST_VOLUME
2943 #endif
2944
2945 #ifdef TEST_VOLUME
2946
2947 #include "wx/volume.h"
2948
2949 static const wxChar *volumeKinds[] =
2950 {
2951 wxT("floppy"),
2952 wxT("hard disk"),
2953 wxT("CD-ROM"),
2954 wxT("DVD-ROM"),
2955 wxT("network volume"),
2956 wxT("other volume"),
2957 };
2958
2959 static void TestFSVolume()
2960 {
2961 wxPuts(wxT("*** Testing wxFSVolume class ***"));
2962
2963 wxArrayString volumes = wxFSVolume::GetVolumes();
2964 size_t count = volumes.GetCount();
2965
2966 if ( !count )
2967 {
2968 wxPuts(wxT("ERROR: no mounted volumes?"));
2969 return;
2970 }
2971
2972 wxPrintf(wxT("%u mounted volumes found:\n"), count);
2973
2974 for ( size_t n = 0; n < count; n++ )
2975 {
2976 wxFSVolume vol(volumes[n]);
2977 if ( !vol.IsOk() )
2978 {
2979 wxPuts(wxT("ERROR: couldn't create volume"));
2980 continue;
2981 }
2982
2983 wxPrintf(wxT("%u: %s (%s), %s, %s, %s\n"),
2984 n + 1,
2985 vol.GetDisplayName().c_str(),
2986 vol.GetName().c_str(),
2987 volumeKinds[vol.GetKind()],
2988 vol.IsWritable() ? wxT("rw") : wxT("ro"),
2989 vol.GetFlags() & wxFS_VOL_REMOVABLE ? wxT("removable")
2990 : wxT("fixed"));
2991 }
2992 }
2993
2994 #endif // TEST_VOLUME
2995
2996 // ----------------------------------------------------------------------------
2997 // date time
2998 // ----------------------------------------------------------------------------
2999
3000 #ifdef TEST_DATETIME
3001
3002 #include "wx/math.h"
3003 #include "wx/datetime.h"
3004
3005 #if TEST_INTERACTIVE
3006
3007 static void TestDateTimeInteractive()
3008 {
3009 wxPuts(wxT("\n*** interactive wxDateTime tests ***"));
3010
3011 wxChar buf[128];
3012
3013 for ( ;; )
3014 {
3015 wxPrintf(wxT("Enter a date: "));
3016 if ( !wxFgets(buf, WXSIZEOF(buf), stdin) )
3017 break;
3018
3019 // kill the last '\n'
3020 buf[wxStrlen(buf) - 1] = 0;
3021
3022 wxDateTime dt;
3023 const wxChar *p = dt.ParseDate(buf);
3024 if ( !p )
3025 {
3026 wxPrintf(wxT("ERROR: failed to parse the date '%s'.\n"), buf);
3027
3028 continue;
3029 }
3030 else if ( *p )
3031 {
3032 wxPrintf(wxT("WARNING: parsed only first %u characters.\n"), p - buf);
3033 }
3034
3035 wxPrintf(wxT("%s: day %u, week of month %u/%u, week of year %u\n"),
3036 dt.Format(wxT("%b %d, %Y")).c_str(),
3037 dt.GetDayOfYear(),
3038 dt.GetWeekOfMonth(wxDateTime::Monday_First),
3039 dt.GetWeekOfMonth(wxDateTime::Sunday_First),
3040 dt.GetWeekOfYear(wxDateTime::Monday_First));
3041 }
3042
3043 wxPuts(wxT("\n*** done ***"));
3044 }
3045
3046 #endif // TEST_INTERACTIVE
3047 #endif // TEST_DATETIME
3048
3049 // ----------------------------------------------------------------------------
3050 // entry point
3051 // ----------------------------------------------------------------------------
3052
3053 #ifdef TEST_SNGLINST
3054 #include "wx/snglinst.h"
3055 #endif // TEST_SNGLINST
3056
3057 int main(int argc, char **argv)
3058 {
3059 #if wxUSE_UNICODE
3060 wxChar **wxArgv = new wxChar *[argc + 1];
3061
3062 {
3063 int n;
3064
3065 for (n = 0; n < argc; n++ )
3066 {
3067 wxMB2WXbuf warg = wxConvertMB2WX(argv[n]);
3068 wxArgv[n] = wxStrdup(warg);
3069 }
3070
3071 wxArgv[n] = NULL;
3072 }
3073 #else // !wxUSE_UNICODE
3074 #define wxArgv argv
3075 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
3076
3077 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "program");
3078
3079 wxInitializer initializer;
3080 if ( !initializer )
3081 {
3082 fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.");
3083
3084 return -1;
3085 }
3086
3087 #ifdef TEST_SNGLINST
3088 wxSingleInstanceChecker checker;
3089 if ( checker.Create(wxT(".wxconsole.lock")) )
3090 {
3091 if ( checker.IsAnotherRunning() )
3092 {
3093 wxPrintf(wxT("Another instance of the program is running, exiting.\n"));
3094
3095 return 1;
3096 }
3097
3098 // wait some time to give time to launch another instance
3099 wxPrintf(wxT("Press \"Enter\" to continue..."));
3100 wxFgetc(stdin);
3101 }
3102 else // failed to create
3103 {
3104 wxPrintf(wxT("Failed to init wxSingleInstanceChecker.\n"));
3105 }
3106 #endif // TEST_SNGLINST
3107
3108 #ifdef TEST_CMDLINE
3109 TestCmdLineConvert();
3110
3111 #if wxUSE_CMDLINE_PARSER
3112 static const wxCmdLineEntryDesc cmdLineDesc[] =
3113 {
3114 { wxCMD_LINE_SWITCH, "h", "help", "show this help message",
3115 wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
3116 { wxCMD_LINE_SWITCH, "v", "verbose", "be verbose" },
3117 { wxCMD_LINE_SWITCH, "q", "quiet", "be quiet" },
3118
3119 { wxCMD_LINE_OPTION, "o", "output", "output file" },
3120 { wxCMD_LINE_OPTION, "i", "input", "input dir" },
3121 { wxCMD_LINE_OPTION, "s", "size", "output block size",
3122 wxCMD_LINE_VAL_NUMBER },
3123 { wxCMD_LINE_OPTION, "d", "date", "output file date",
3124 wxCMD_LINE_VAL_DATE },
3125 { wxCMD_LINE_OPTION, "f", "double", "output double",
3126 wxCMD_LINE_VAL_DOUBLE },
3127
3128 { wxCMD_LINE_PARAM, NULL, NULL, "input file",
3129 wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_MULTIPLE },
3130
3131 { wxCMD_LINE_NONE }
3132 };
3133
3134 wxCmdLineParser parser(cmdLineDesc, argc, wxArgv);
3135
3136 parser.AddOption(wxT("project_name"), wxT(""), wxT("full path to project file"),
3137 wxCMD_LINE_VAL_STRING,
3138 wxCMD_LINE_OPTION_MANDATORY | wxCMD_LINE_NEEDS_SEPARATOR);
3139
3140 switch ( parser.Parse() )
3141 {
3142 case -1:
3143 wxLogMessage(wxT("Help was given, terminating."));
3144 break;
3145
3146 case 0:
3147 ShowCmdLine(parser);
3148 break;
3149
3150 default:
3151 wxLogMessage(wxT("Syntax error detected, aborting."));
3152 break;
3153 }
3154 #endif // wxUSE_CMDLINE_PARSER
3155
3156 #endif // TEST_CMDLINE
3157
3158 #ifdef TEST_DIR
3159 #if TEST_ALL
3160 TestDirExists();
3161 TestDirEnum();
3162 #endif
3163 TestDirTraverse();
3164 #endif // TEST_DIR
3165
3166 #ifdef TEST_DYNLIB
3167 TestDllLoad();
3168 TestDllListLoaded();
3169 #endif // TEST_DYNLIB
3170
3171 #ifdef TEST_ENVIRON
3172 TestEnvironment();
3173 #endif // TEST_ENVIRON
3174
3175 #ifdef TEST_FILECONF
3176 TestFileConfRead();
3177 #endif // TEST_FILECONF
3178
3179 #ifdef TEST_LOCALE
3180 TestDefaultLang();
3181 #endif // TEST_LOCALE
3182
3183 #ifdef TEST_LOG
3184 wxPuts(wxT("*** Testing wxLog ***"));
3185
3186 wxString s;
3187 for ( size_t n = 0; n < 8000; n++ )
3188 {
3189 s << (wxChar)(wxT('A') + (n % 26));
3190 }
3191
3192 wxLogWarning(wxT("The length of the string is %lu"),
3193 (unsigned long)s.length());
3194
3195 wxString msg;
3196 msg.Printf(wxT("A very very long message: '%s', the end!\n"), s.c_str());
3197
3198 // this one shouldn't be truncated
3199 wxPrintf(msg);
3200
3201 // but this one will because log functions use fixed size buffer
3202 // (note that it doesn't need '\n' at the end neither - will be added
3203 // by wxLog anyhow)
3204 wxLogMessage(wxT("A very very long message 2: '%s', the end!"), s.c_str());
3205 #endif // TEST_LOG
3206
3207 #ifdef TEST_FILE
3208 TestFileRead();
3209 TestTextFileRead();
3210 TestFileCopy();
3211 TestTempFile();
3212 #endif // TEST_FILE
3213
3214 #ifdef TEST_FILENAME
3215 TestFileNameTemp();
3216 TestFileNameCwd();
3217 TestFileNameDirManip();
3218 TestFileNameComparison();
3219 TestFileNameOperations();
3220 #endif // TEST_FILENAME
3221
3222 #ifdef TEST_FILETIME
3223 TestFileGetTimes();
3224 #if 0
3225 TestFileSetTimes();
3226 #endif
3227 #endif // TEST_FILETIME
3228
3229 #ifdef TEST_FTP
3230 wxLog::AddTraceMask(FTP_TRACE_MASK);
3231
3232 // wxFTP cannot be a static variable as its ctor needs to access
3233 // wxWidgets internals after it has been initialized
3234 ftp = new wxFTP;
3235 ftp->SetLog(new wxProtocolLog(FTP_TRACE_MASK));
3236
3237 if ( TestFtpConnect() )
3238 {
3239 #if TEST_ALL
3240 TestFtpList();
3241 TestFtpDownload();
3242 TestFtpMisc();
3243 TestFtpFileSize();
3244 TestFtpUpload();
3245 #endif // TEST_ALL
3246
3247 #if TEST_INTERACTIVE
3248 //TestFtpInteractive();
3249 #endif
3250 }
3251 //else: connecting to the FTP server failed
3252
3253 delete ftp;
3254 #endif // TEST_FTP
3255
3256 #ifdef TEST_MIME
3257 //wxLog::AddTraceMask(wxT("mime"));
3258 TestMimeEnum();
3259 #if 0
3260 TestMimeOverride();
3261 TestMimeAssociate();
3262 #endif
3263 TestMimeFilename();
3264 #endif // TEST_MIME
3265
3266 #ifdef TEST_INFO_FUNCTIONS
3267 TestOsInfo();
3268 TestPlatformInfo();
3269 TestUserInfo();
3270
3271 #if TEST_INTERACTIVE
3272 TestDiskInfo();
3273 #endif
3274 #endif // TEST_INFO_FUNCTIONS
3275
3276 #ifdef TEST_PATHLIST
3277 TestPathList();
3278 #endif // TEST_PATHLIST
3279
3280 #ifdef TEST_PRINTF
3281 TestPrintf();
3282 #endif // TEST_PRINTF
3283
3284 #ifdef TEST_REGCONF
3285 #if 0
3286 TestRegConfWrite();
3287 #endif
3288 TestRegConfRead();
3289 #endif // TEST_REGCONF
3290
3291 #if defined TEST_REGEX && TEST_INTERACTIVE
3292 TestRegExInteractive();
3293 #endif // defined TEST_REGEX && TEST_INTERACTIVE
3294
3295 #ifdef TEST_REGISTRY
3296 TestRegistryRead();
3297 TestRegistryAssociation();
3298 #endif // TEST_REGISTRY
3299
3300 #ifdef TEST_SOCKETS
3301 TestSocketServer();
3302 TestSocketClient();
3303 #endif // TEST_SOCKETS
3304
3305 #ifdef TEST_STREAMS
3306 #if TEST_ALL
3307 TestFileStream();
3308 #endif
3309 TestMemoryStream();
3310 #endif // TEST_STREAMS
3311
3312 #ifdef TEST_TIMER
3313 TestStopWatch();
3314 TestTimer();
3315 #endif // TEST_TIMER
3316
3317 #ifdef TEST_DATETIME
3318 #if TEST_INTERACTIVE
3319 TestDateTimeInteractive();
3320 #endif
3321 #endif // TEST_DATETIME
3322
3323 #ifdef TEST_SCOPEGUARD
3324 TestScopeGuard();
3325 #endif
3326
3327 #ifdef TEST_STACKWALKER
3328 #if wxUSE_STACKWALKER
3329 TestStackWalk(argv[0]);
3330 #endif
3331 #endif // TEST_STACKWALKER
3332
3333 #ifdef TEST_STDPATHS
3334 TestStandardPaths();
3335 #endif
3336
3337 #ifdef TEST_USLEEP
3338 wxPuts(wxT("Sleeping for 3 seconds... z-z-z-z-z..."));
3339 wxUsleep(3000);
3340 #endif // TEST_USLEEP
3341
3342 #ifdef TEST_VOLUME
3343 TestFSVolume();
3344 #endif // TEST_VOLUME
3345
3346 #if wxUSE_UNICODE
3347 {
3348 for ( int n = 0; n < argc; n++ )
3349 free(wxArgv[n]);
3350
3351 delete [] wxArgv;
3352 }
3353 #endif // wxUSE_UNICODE
3354
3355 wxUnusedVar(argc);
3356 wxUnusedVar(argv);
3357 return 0;
3358 }