1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: A sample console (as opposed to GUI) program using wxWidgets
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
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:
20 int main(int argc, char **argv)
22 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "program");
24 wxInitializer initializer;
27 fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.");
31 static const wxCmdLineEntryDesc cmdLineDesc[] =
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...
40 wxCmdLineParser parser(cmdLineDesc, argc, wxArgv);
41 switch ( parser.Parse() )
44 wxLogMessage(wxT("Help was given, terminating."));
48 // everything is ok; proceed
52 wxLogMessage(wxT("Syntax error detected, aborting."));
56 // do something useful here
63 // ============================================================================
65 // ============================================================================
67 // ----------------------------------------------------------------------------
69 // ----------------------------------------------------------------------------
75 #include "wx/string.h"
77 #include "wx/filename.h"
80 #include "wx/apptrait.h"
81 #include "wx/platinfo.h"
82 #include "wx/wxchar.h"
84 // without this pragma, the stupid compiler precompiles #defines below so that
85 // changing them doesn't "take place" later!
90 // ----------------------------------------------------------------------------
91 // conditional compilation
92 // ----------------------------------------------------------------------------
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.
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.
106 // some tests are interactive, define this to run them
107 #define TEST_INTERACTIVE 1
110 #define TEST_DATETIME
112 #define TEST_STDPATHS
113 #define TEST_STACKWALKER
115 #define TEST_SNGLINST
117 #define TEST_INFO_FUNCTIONS
120 #else // #if TEST_ALL
123 // ============================================================================
125 // ============================================================================
127 // ----------------------------------------------------------------------------
129 // ----------------------------------------------------------------------------
133 #include "wx/dynlib.h"
135 #if defined(__WXMSW__) || defined(__UNIX__)
137 static void TestDllListLoaded()
139 wxPuts(wxT("*** testing wxDynamicLibrary::ListLoaded() ***\n"));
141 wxPuts("Loaded modules:");
142 wxDynamicLibraryDetailsArray dlls
= wxDynamicLibrary::ListLoaded();
143 const size_t count
= dlls
.GetCount();
144 for ( size_t n
= 0; n
< count
; ++n
)
146 const wxDynamicLibraryDetails
& details
= dlls
[n
];
147 printf("%-45s", (const char *)details
.GetPath().mb_str());
149 void *addr
wxDUMMY_INITIALIZE(NULL
);
150 size_t len
wxDUMMY_INITIALIZE(0);
151 if ( details
.GetAddress(&addr
, &len
) )
153 printf(" %08lx:%08lx",
154 (unsigned long)addr
, (unsigned long)((char *)addr
+ len
));
157 printf(" %s\n", (const char *)details
.GetVersion().mb_str());
160 wxPuts(wxEmptyString
);
165 #endif // TEST_DYNLIB
167 // ----------------------------------------------------------------------------
169 // ----------------------------------------------------------------------------
173 #include "wx/mimetype.h"
175 static void TestMimeEnum()
177 wxPuts(wxT("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
179 wxArrayString mimetypes
;
181 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
183 wxPrintf(wxT("*** All %u known filetypes: ***\n"), count
);
188 for ( size_t n
= 0; n
< count
; n
++ )
190 wxFileType
*filetype
=
191 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
194 wxPrintf(wxT(" nothing known about the filetype '%s'!\n"),
195 mimetypes
[n
].c_str());
199 filetype
->GetDescription(&desc
);
200 filetype
->GetExtensions(exts
);
202 filetype
->GetIcon(NULL
);
205 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
208 extsAll
<< wxT(", ");
212 wxPrintf(wxT(" %s: %s (%s)\n"),
213 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
216 wxPuts(wxEmptyString
);
219 static void TestMimeFilename()
221 wxPuts(wxT("*** Testing MIME type from filename query ***\n"));
223 static const wxChar
*filenames
[] =
231 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
233 const wxString fname
= filenames
[n
];
234 wxString ext
= fname
.AfterLast(wxT('.'));
235 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
238 wxPrintf(wxT("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
243 if ( !ft
->GetDescription(&desc
) )
244 desc
= wxT("<no description>");
247 if ( !ft
->GetOpenCommand(&cmd
,
248 wxFileType::MessageParameters(fname
, wxEmptyString
)) )
249 cmd
= wxT("<no command available>");
251 cmd
= wxString(wxT('"')) + cmd
+ wxT('"');
253 wxPrintf(wxT("To open %s (%s) run:\n %s\n"),
254 fname
.c_str(), desc
.c_str(), cmd
.c_str());
260 wxPuts(wxEmptyString
);
263 static void TestMimeAssociate()
265 wxPuts(wxT("*** Testing creation of filetype association ***\n"));
267 wxFileTypeInfo
ftInfo(
268 wxT("application/x-xyz"),
269 wxT("xyzview '%s'"), // open cmd
270 wxT(""), // print cmd
271 wxT("XYZ File"), // description
272 wxT(".xyz"), // extensions
273 wxNullPtr
// end of extensions
275 ftInfo
.SetShortDesc(wxT("XYZFile")); // used under Win32 only
277 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
280 wxPuts(wxT("ERROR: failed to create association!"));
284 // TODO: read it back
288 wxPuts(wxEmptyString
);
294 // ----------------------------------------------------------------------------
295 // misc information functions
296 // ----------------------------------------------------------------------------
298 #ifdef TEST_INFO_FUNCTIONS
300 #include "wx/utils.h"
303 static void TestDiskInfo()
305 wxPuts(wxT("*** Testing wxGetDiskSpace() ***"));
309 wxChar pathname
[128];
310 wxPrintf(wxT("Enter a directory name (press ENTER or type 'quit' to escape): "));
311 if ( !wxFgets(pathname
, WXSIZEOF(pathname
), stdin
) )
314 // kill the last '\n'
315 pathname
[wxStrlen(pathname
) - 1] = 0;
317 if (pathname
[0] == '\0' || wxStrcmp(pathname
, "quit") == 0)
320 wxLongLong total
, free
;
321 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
323 wxPuts(wxT("ERROR: wxGetDiskSpace failed."));
327 wxPrintf(wxT("%sKb total, %sKb free on '%s'.\n"),
328 (total
/ 1024).ToString().c_str(),
329 (free
/ 1024).ToString().c_str(),
338 #endif // TEST_INTERACTIVE
340 static void TestOsInfo()
342 wxPuts(wxT("*** Testing OS info functions ***\n"));
345 wxGetOsVersion(&major
, &minor
);
346 wxPrintf(wxT("Running under: %s, version %d.%d\n"),
347 wxGetOsDescription().c_str(), major
, minor
);
349 wxPrintf(wxT("%ld free bytes of memory left.\n"), wxGetFreeMemory().ToLong());
351 wxPrintf(wxT("Host name is %s (%s).\n"),
352 wxGetHostName().c_str(), wxGetFullHostName().c_str());
354 wxPuts(wxEmptyString
);
357 static void TestPlatformInfo()
359 wxPuts(wxT("*** Testing wxPlatformInfo functions ***\n"));
364 wxPrintf(wxT("Operating system family name is: %s\n"), plat
.GetOperatingSystemFamilyName().c_str());
365 wxPrintf(wxT("Operating system name is: %s\n"), plat
.GetOperatingSystemIdName().c_str());
366 wxPrintf(wxT("Port ID name is: %s\n"), plat
.GetPortIdName().c_str());
367 wxPrintf(wxT("Port ID short name is: %s\n"), plat
.GetPortIdShortName().c_str());
368 wxPrintf(wxT("Architecture is: %s\n"), plat
.GetArchName().c_str());
369 wxPrintf(wxT("Endianness is: %s\n"), plat
.GetEndiannessName().c_str());
371 wxPuts(wxEmptyString
);
374 static void TestUserInfo()
376 wxPuts(wxT("*** Testing user info functions ***\n"));
378 wxPrintf(wxT("User id is:\t%s\n"), wxGetUserId().c_str());
379 wxPrintf(wxT("User name is:\t%s\n"), wxGetUserName().c_str());
380 wxPrintf(wxT("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
381 wxPrintf(wxT("Email address:\t%s\n"), wxGetEmailAddress().c_str());
383 wxPuts(wxEmptyString
);
386 #endif // TEST_INFO_FUNCTIONS
388 // ----------------------------------------------------------------------------
389 // regular expressions
390 // ----------------------------------------------------------------------------
392 #if defined TEST_REGEX && TEST_INTERACTIVE
394 #include "wx/regex.h"
396 static void TestRegExInteractive()
398 wxPuts(wxT("*** Testing RE interactively ***"));
403 wxPrintf(wxT("Enter a pattern (press ENTER or type 'quit' to escape): "));
404 if ( !wxFgets(pattern
, WXSIZEOF(pattern
), stdin
) )
407 // kill the last '\n'
408 pattern
[wxStrlen(pattern
) - 1] = 0;
410 if (pattern
[0] == '\0' || wxStrcmp(pattern
, "quit") == 0)
414 if ( !re
.Compile(pattern
) )
422 wxPrintf(wxT("Enter text to match: "));
423 if ( !wxFgets(text
, WXSIZEOF(text
), stdin
) )
426 // kill the last '\n'
427 text
[wxStrlen(text
) - 1] = 0;
429 if ( !re
.Matches(text
) )
431 wxPrintf(wxT("No match.\n"));
435 wxPrintf(wxT("Pattern matches at '%s'\n"), re
.GetMatch(text
).c_str());
438 for ( size_t n
= 1; ; n
++ )
440 if ( !re
.GetMatch(&start
, &len
, n
) )
445 wxPrintf(wxT("Subexpr %u matched '%s'\n"),
446 n
, wxString(text
+ start
, len
).c_str());
457 // ----------------------------------------------------------------------------
459 // ----------------------------------------------------------------------------
461 #if defined(TEST_FTP) && TEST_INTERACTIVE
463 #include "wx/protocol/ftp.h"
464 #include "wx/protocol/log.h"
466 #define FTP_ANONYMOUS
470 static const wxChar
*hostname
= wxT("ftp.wxwidgets.org");
472 static const wxChar
*hostname
= "localhost";
475 static void TestFtpInteractive()
477 wxPuts(wxT("\n*** Interactive wxFTP test ***"));
480 wxPrintf(wxT("--- Attempting to connect to %s:21 anonymously...\n"), hostname
);
481 #else // !FTP_ANONYMOUS
483 wxFgets(user
, WXSIZEOF(user
), stdin
);
484 user
[wxStrlen(user
) - 1] = '\0'; // chop off '\n'
487 wxChar password
[256];
488 wxPrintf(wxT("Password for %s: "), password
);
489 wxFgets(password
, WXSIZEOF(password
), stdin
);
490 password
[wxStrlen(password
) - 1] = '\0'; // chop off '\n'
491 ftp
->SetPassword(password
);
493 wxPrintf(wxT("--- Attempting to connect to %s:21 as %s...\n"), hostname
, user
);
494 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
496 if ( !ftp
->Connect(hostname
) )
498 wxPrintf(wxT("ERROR: failed to connect to %s\n"), hostname
);
504 wxPrintf(wxT("--- Connected to %s, current directory is '%s'\n"),
505 hostname
, ftp
->Pwd().c_str());
511 wxPrintf(wxT("Enter FTP command (press ENTER or type 'quit' to escape): "));
512 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
515 // kill the last '\n'
516 buf
[wxStrlen(buf
) - 1] = 0;
518 if (buf
[0] == '\0' || wxStrcmp(buf
, "quit") == 0)
521 // special handling of LIST and NLST as they require data connection
522 wxString
start(buf
, 4);
524 if ( start
== wxT("LIST") || start
== wxT("NLST") )
527 if ( wxStrlen(buf
) > 4 )
531 if ( !ftp
->GetList(files
, wildcard
, start
== wxT("LIST")) )
533 wxPrintf(wxT("ERROR: failed to get %s of files\n"), start
.c_str());
537 wxPrintf(wxT("--- %s of '%s' under '%s':\n"),
538 start
.c_str(), wildcard
.c_str(), ftp
->Pwd().c_str());
539 size_t count
= files
.GetCount();
540 for ( size_t n
= 0; n
< count
; n
++ )
542 wxPrintf(wxT("\t%s\n"), files
[n
].c_str());
544 wxPuts(wxT("--- End of the file list"));
549 wxChar ch
= ftp
->SendCommand(buf
);
550 wxPrintf(wxT("Command %s"), ch
? wxT("succeeded") : wxT("failed"));
553 wxPrintf(wxT(" (return code %c)"), ch
);
556 wxPrintf(wxT(", server reply:\n%s\n\n"), ftp
->GetLastResult().c_str());
564 // ----------------------------------------------------------------------------
566 // ----------------------------------------------------------------------------
568 #ifdef TEST_STACKWALKER
570 #if wxUSE_STACKWALKER
572 #include "wx/stackwalk.h"
574 class StackDump
: public wxStackWalker
577 StackDump(const char *argv0
)
578 : wxStackWalker(argv0
)
582 virtual void Walk(size_t skip
= 1, size_t maxdepth
= wxSTACKWALKER_MAX_DEPTH
)
584 wxPuts(wxT("Stack dump:"));
586 wxStackWalker::Walk(skip
, maxdepth
);
590 virtual void OnStackFrame(const wxStackFrame
& frame
)
592 printf("[%2d] ", (int) frame
.GetLevel());
594 wxString name
= frame
.GetName();
597 printf("%-20.40s", (const char*)name
.mb_str());
601 printf("0x%08lx", (unsigned long)frame
.GetAddress());
604 if ( frame
.HasSourceLocation() )
607 (const char*)frame
.GetFileName().mb_str(),
608 (int)frame
.GetLine());
614 for ( size_t n
= 0; frame
.GetParam(n
, &type
, &name
, &val
); n
++ )
616 printf("\t%s %s = %s\n", (const char*)type
.mb_str(),
617 (const char*)name
.mb_str(),
618 (const char*)val
.mb_str());
623 static void TestStackWalk(const char *argv0
)
625 wxPuts(wxT("*** Testing wxStackWalker ***"));
627 StackDump
dump(argv0
);
633 #endif // wxUSE_STACKWALKER
635 #endif // TEST_STACKWALKER
637 // ----------------------------------------------------------------------------
639 // ----------------------------------------------------------------------------
643 #include "wx/stdpaths.h"
644 #include "wx/wxchar.h" // wxPrintf
646 static void TestStandardPaths()
648 wxPuts(wxT("*** Testing wxStandardPaths ***"));
650 wxTheApp
->SetAppName(wxT("console"));
652 wxStandardPathsBase
& stdp
= wxStandardPaths::Get();
653 wxPrintf(wxT("Config dir (sys):\t%s\n"), stdp
.GetConfigDir().c_str());
654 wxPrintf(wxT("Config dir (user):\t%s\n"), stdp
.GetUserConfigDir().c_str());
655 wxPrintf(wxT("Data dir (sys):\t\t%s\n"), stdp
.GetDataDir().c_str());
656 wxPrintf(wxT("Data dir (sys local):\t%s\n"), stdp
.GetLocalDataDir().c_str());
657 wxPrintf(wxT("Data dir (user):\t%s\n"), stdp
.GetUserDataDir().c_str());
658 wxPrintf(wxT("Data dir (user local):\t%s\n"), stdp
.GetUserLocalDataDir().c_str());
659 wxPrintf(wxT("Documents dir:\t\t%s\n"), stdp
.GetDocumentsDir().c_str());
660 wxPrintf(wxT("Executable path:\t%s\n"), stdp
.GetExecutablePath().c_str());
661 wxPrintf(wxT("Plugins dir:\t\t%s\n"), stdp
.GetPluginsDir().c_str());
662 wxPrintf(wxT("Resources dir:\t\t%s\n"), stdp
.GetResourcesDir().c_str());
663 wxPrintf(wxT("Localized res. dir:\t%s\n"),
664 stdp
.GetLocalizedResourcesDir(wxT("fr")).c_str());
665 wxPrintf(wxT("Message catalogs dir:\t%s\n"),
666 stdp
.GetLocalizedResourcesDir
669 wxStandardPaths::ResourceCat_Messages
675 #endif // TEST_STDPATHS
677 // ----------------------------------------------------------------------------
679 // ----------------------------------------------------------------------------
681 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
687 #include "wx/volume.h"
689 static const wxChar
*volumeKinds
[] =
695 wxT("network volume"),
699 static void TestFSVolume()
701 wxPuts(wxT("*** Testing wxFSVolume class ***"));
703 wxArrayString volumes
= wxFSVolume::GetVolumes();
704 size_t count
= volumes
.GetCount();
708 wxPuts(wxT("ERROR: no mounted volumes?"));
712 wxPrintf(wxT("%u mounted volumes found:\n"), count
);
714 for ( size_t n
= 0; n
< count
; n
++ )
716 wxFSVolume
vol(volumes
[n
]);
719 wxPuts(wxT("ERROR: couldn't create volume"));
723 wxPrintf(wxT("%u: %s (%s), %s, %s, %s\n"),
725 vol
.GetDisplayName().c_str(),
726 vol
.GetName().c_str(),
727 volumeKinds
[vol
.GetKind()],
728 vol
.IsWritable() ? wxT("rw") : wxT("ro"),
729 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? wxT("removable")
736 #endif // TEST_VOLUME
738 // ----------------------------------------------------------------------------
740 // ----------------------------------------------------------------------------
745 #include "wx/datetime.h"
749 static void TestDateTimeInteractive()
751 wxPuts(wxT("\n*** interactive wxDateTime tests ***"));
757 wxPrintf(wxT("Enter a date (press ENTER or type 'quit' to escape): "));
758 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
761 // kill the last '\n'
762 buf
[wxStrlen(buf
) - 1] = 0;
764 if ( buf
[0] == '\0' || wxStrcmp(buf
, "quit") == 0 )
768 const wxChar
*p
= dt
.ParseDate(buf
);
771 wxPrintf(wxT("ERROR: failed to parse the date '%s'.\n"), buf
);
777 wxPrintf(wxT("WARNING: parsed only first %u characters.\n"), p
- buf
);
780 wxPrintf(wxT("%s: day %u, week of month %u/%u, week of year %u\n"),
781 dt
.Format(wxT("%b %d, %Y")).c_str(),
783 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
784 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
785 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
791 #endif // TEST_INTERACTIVE
792 #endif // TEST_DATETIME
794 // ----------------------------------------------------------------------------
796 // ----------------------------------------------------------------------------
798 #if defined(TEST_SNGLINST) && TEST_INTERACTIVE
800 #include "wx/snglinst.h"
802 static bool TestSingleIstance()
804 wxPuts(wxT("\n*** Testing wxSingleInstanceChecker ***"));
806 wxSingleInstanceChecker checker
;
807 if ( checker
.Create(wxT(".wxconsole.lock")) )
809 if ( checker
.IsAnotherRunning() )
811 wxPrintf(wxT("Another instance of the program is running, exiting.\n"));
816 // wait some time to give time to launch another instance
817 wxPuts(wxT("If you try to run another instance of this program now, it won't start."));
818 wxPrintf(wxT("Press \"Enter\" to exit wxSingleInstanceChecker test and proceed..."));
821 else // failed to create
823 wxPrintf(wxT("Failed to init wxSingleInstanceChecker.\n"));
830 #endif // defined(TEST_SNGLINST) && TEST_INTERACTIVE
833 // ----------------------------------------------------------------------------
835 // ----------------------------------------------------------------------------
837 int main(int argc
, char **argv
)
839 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "program");
841 wxInitializer initializer
;
844 fprintf(stderr
, "Failed to initialize the wxWidgets library, aborting.");
850 // run all non-interactive tests:
851 // ------------------------------
855 #endif // TEST_DYNLIB
863 #ifdef TEST_INFO_FUNCTIONS
867 #endif // TEST_INFO_FUNCTIONS
871 #endif // TEST_PRINTF
873 #ifdef TEST_STACKWALKER
874 #if wxUSE_STACKWALKER
875 TestStackWalk(argv
[0]);
877 #endif // TEST_STACKWALKER
885 #endif // TEST_VOLUME
888 // run all interactive tests:
889 // --------------------------
893 wxPuts(wxT("***************** INTERACTIVE TESTS *****************\n"));
896 if (!TestSingleIstance())
898 #endif // TEST_SNGLINST
901 wxLog::AddTraceMask(FTP_TRACE_MASK
);
903 // wxFTP cannot be a static variable as its ctor needs to access
904 // wxWidgets internals after it has been initialized
906 ftp
->SetLog(new wxProtocolLog(FTP_TRACE_MASK
));
907 TestFtpInteractive();
911 #ifdef TEST_INFO_FUNCTIONS
913 #endif // TEST_INFO_FUNCTIONS
915 #if defined TEST_REGEX
916 TestRegExInteractive();
917 #endif // defined TEST_REGEX
920 TestDateTimeInteractive();
921 #endif // TEST_DATETIME
923 #endif // TEST_INTERACTIVE