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.
107 #define TEST_DATETIME
109 #define TEST_STDPATHS
110 #define TEST_STACKWALKER
112 #define TEST_SNGLINST
114 #define TEST_INFO_FUNCTIONS
117 #else // #if TEST_ALL
120 // some tests are interactive, define this to run them
121 #ifdef TEST_INTERACTIVE
122 #undef TEST_INTERACTIVE
124 #define TEST_INTERACTIVE 1
126 #define TEST_INTERACTIVE 1
129 // ============================================================================
131 // ============================================================================
133 // ----------------------------------------------------------------------------
135 // ----------------------------------------------------------------------------
139 #include "wx/dynlib.h"
141 #if defined(__WXMSW__) || defined(__UNIX__)
143 static void TestDllListLoaded()
145 wxPuts(wxT("*** testing wxDynamicLibrary::ListLoaded() ***\n"));
147 wxPuts("Loaded modules:");
148 wxDynamicLibraryDetailsArray dlls
= wxDynamicLibrary
::ListLoaded();
149 const size_t count
= dlls
.GetCount();
150 for ( size_t n
= 0; n
< count
; ++n
)
152 const wxDynamicLibraryDetails
& details
= dlls
[n
];
153 printf("%-45s", (const char *)details
.GetPath().mb_str());
155 void *addr
wxDUMMY_INITIALIZE(NULL
);
156 size_t len
wxDUMMY_INITIALIZE(0);
157 if ( details
.GetAddress(&addr
, &len
) )
159 printf(" %08lx:%08lx",
160 (unsigned long)addr
, (unsigned long)((char *)addr
+ len
));
163 printf(" %s\n", (const char *)details
.GetVersion().mb_str());
166 wxPuts(wxEmptyString
);
171 #endif // TEST_DYNLIB
173 // ----------------------------------------------------------------------------
175 // ----------------------------------------------------------------------------
179 #include "wx/mimetype.h"
181 static void TestMimeEnum()
183 wxPuts(wxT("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
185 wxArrayString mimetypes
;
187 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
189 wxPrintf(wxT("*** All %u known filetypes: ***\n"), count
);
194 for ( size_t n
= 0; n
< count
; n
++ )
196 wxFileType
*filetype
=
197 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
200 wxPrintf(wxT(" nothing known about the filetype '%s'!\n"),
201 mimetypes
[n
].c_str());
205 filetype
->GetDescription(&desc
);
206 filetype
->GetExtensions(exts
);
208 filetype
->GetIcon(NULL
);
211 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
214 extsAll
<< wxT(", ");
218 wxPrintf(wxT(" %s: %s (%s)\n"),
219 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
222 wxPuts(wxEmptyString
);
225 static void TestMimeFilename()
227 wxPuts(wxT("*** Testing MIME type from filename query ***\n"));
229 static const wxChar
*filenames
[] =
237 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
239 const wxString fname
= filenames
[n
];
240 wxString ext
= fname
.AfterLast(wxT('.'));
241 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
244 wxPrintf(wxT("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
249 if ( !ft
->GetDescription(&desc
) )
250 desc
= wxT("<no description>");
253 if ( !ft
->GetOpenCommand(&cmd
,
254 wxFileType
::MessageParameters(fname
, wxEmptyString
)) )
255 cmd
= wxT("<no command available>");
257 cmd
= wxString(wxT('"')) + cmd
+ wxT('"');
259 wxPrintf(wxT("To open %s (%s) run:\n %s\n"),
260 fname
.c_str(), desc
.c_str(), cmd
.c_str());
266 wxPuts(wxEmptyString
);
269 static void TestMimeAssociate()
271 wxPuts(wxT("*** Testing creation of filetype association ***\n"));
273 wxFileTypeInfo
ftInfo(
274 wxT("application/x-xyz"),
275 wxT("xyzview '%s'"), // open cmd
276 wxT(""), // print cmd
277 wxT("XYZ File"), // description
278 wxT(".xyz"), // extensions
279 wxNullPtr
// end of extensions
281 ftInfo
.SetShortDesc(wxT("XYZFile")); // used under Win32 only
283 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
286 wxPuts(wxT("ERROR: failed to create association!"));
290 // TODO: read it back
294 wxPuts(wxEmptyString
);
300 // ----------------------------------------------------------------------------
301 // misc information functions
302 // ----------------------------------------------------------------------------
304 #ifdef TEST_INFO_FUNCTIONS
306 #include "wx/utils.h"
309 static void TestDiskInfo()
311 wxPuts(wxT("*** Testing wxGetDiskSpace() ***"));
315 wxChar pathname
[128];
316 wxPrintf(wxT("\nEnter a directory name (or 'quit' to escape): "));
317 if ( !wxFgets(pathname
, WXSIZEOF(pathname
), stdin
) )
320 // kill the last '\n'
321 pathname
[wxStrlen(pathname
) - 1] = 0;
323 if (wxStrcmp(pathname
, "quit") == 0)
326 wxLongLong total
, free
;
327 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
329 wxPuts(wxT("ERROR: wxGetDiskSpace failed."));
333 wxPrintf(wxT("%sKb total, %sKb free on '%s'.\n"),
334 (total
/ 1024).ToString().c_str(),
335 (free
/ 1024).ToString().c_str(),
340 #endif // TEST_INTERACTIVE
342 static void TestOsInfo()
344 wxPuts(wxT("*** Testing OS info functions ***\n"));
347 wxGetOsVersion(&major
, &minor
);
348 wxPrintf(wxT("Running under: %s, version %d.%d\n"),
349 wxGetOsDescription().c_str(), major
, minor
);
351 wxPrintf(wxT("%ld free bytes of memory left.\n"), wxGetFreeMemory().ToLong());
353 wxPrintf(wxT("Host name is %s (%s).\n"),
354 wxGetHostName().c_str(), wxGetFullHostName().c_str());
356 wxPuts(wxEmptyString
);
359 static void TestPlatformInfo()
361 wxPuts(wxT("*** Testing wxPlatformInfo functions ***\n"));
366 wxPrintf(wxT("Operating system family name is: %s\n"), plat
.GetOperatingSystemFamilyName().c_str());
367 wxPrintf(wxT("Operating system name is: %s\n"), plat
.GetOperatingSystemIdName().c_str());
368 wxPrintf(wxT("Port ID name is: %s\n"), plat
.GetPortIdName().c_str());
369 wxPrintf(wxT("Port ID short name is: %s\n"), plat
.GetPortIdShortName().c_str());
370 wxPrintf(wxT("Architecture is: %s\n"), plat
.GetArchName().c_str());
371 wxPrintf(wxT("Endianness is: %s\n"), plat
.GetEndiannessName().c_str());
373 wxPuts(wxEmptyString
);
376 static void TestUserInfo()
378 wxPuts(wxT("*** Testing user info functions ***\n"));
380 wxPrintf(wxT("User id is:\t%s\n"), wxGetUserId().c_str());
381 wxPrintf(wxT("User name is:\t%s\n"), wxGetUserName().c_str());
382 wxPrintf(wxT("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
383 wxPrintf(wxT("Email address:\t%s\n"), wxGetEmailAddress().c_str());
385 wxPuts(wxEmptyString
);
388 #endif // TEST_INFO_FUNCTIONS
390 // ----------------------------------------------------------------------------
391 // regular expressions
392 // ----------------------------------------------------------------------------
394 #if defined TEST_REGEX && TEST_INTERACTIVE
396 #include "wx/regex.h"
398 static void TestRegExInteractive()
400 wxPuts(wxT("*** Testing RE interactively ***"));
405 wxPrintf(wxT("\nEnter a pattern (or 'quit' to escape): "));
406 if ( !wxFgets(pattern
, WXSIZEOF(pattern
), stdin
) )
409 // kill the last '\n'
410 pattern
[wxStrlen(pattern
) - 1] = 0;
412 if (wxStrcmp(pattern
, "quit") == 0)
416 if ( !re
.Compile(pattern
) )
424 wxPrintf(wxT("Enter text to match: "));
425 if ( !wxFgets(text
, WXSIZEOF(text
), stdin
) )
428 // kill the last '\n'
429 text
[wxStrlen(text
) - 1] = 0;
431 if ( !re
.Matches(text
) )
433 wxPrintf(wxT("No match.\n"));
437 wxPrintf(wxT("Pattern matches at '%s'\n"), re
.GetMatch(text
).c_str());
440 for ( size_t n
= 1; ; n
++ )
442 if ( !re
.GetMatch(&start
, &len
, n
) )
447 wxPrintf(wxT("Subexpr %u matched '%s'\n"),
448 n
, wxString(text
+ start
, len
).c_str());
457 // ----------------------------------------------------------------------------
459 // ----------------------------------------------------------------------------
463 #include "wx/protocol/ftp.h"
464 #include "wx/protocol/log.h"
466 #define FTP_ANONYMOUS
471 static const wxChar
*hostname
= wxT("ftp.wxwidgets.org");
473 static const wxChar
*hostname
= "localhost";
476 static bool TestFtpConnect()
478 wxPuts(wxT("*** Testing FTP connect ***"));
481 wxPrintf(wxT("--- Attempting to connect to %s:21 anonymously...\n"), hostname
);
482 #else // !FTP_ANONYMOUS
484 wxFgets(user
, WXSIZEOF(user
), stdin
);
485 user
[wxStrlen(user
) - 1] = '\0'; // chop off '\n'
488 wxChar password
[256];
489 wxPrintf(wxT("Password for %s: "), password
);
490 wxFgets(password
, WXSIZEOF(password
), stdin
);
491 password
[wxStrlen(password
) - 1] = '\0'; // chop off '\n'
492 ftp
->SetPassword(password
);
494 wxPrintf(wxT("--- Attempting to connect to %s:21 as %s...\n"), hostname
, user
);
495 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
497 if ( !ftp
->Connect(hostname
) )
499 wxPrintf(wxT("ERROR: failed to connect to %s\n"), hostname
);
505 wxPrintf(wxT("--- Connected to %s, current directory is '%s'\n"),
506 hostname
, ftp
->Pwd().c_str());
514 static void TestFtpInteractive()
516 wxPuts(wxT("\n*** Interactive wxFTP test ***"));
522 wxPrintf(wxT("Enter FTP command (or 'quit' to escape): "));
523 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
526 // kill the last '\n'
527 buf
[wxStrlen(buf
) - 1] = 0;
529 // special handling of LIST and NLST as they require data connection
530 wxString
start(buf
, 4);
532 if ( start
== wxT("LIST") || start
== wxT("NLST") )
535 if ( wxStrlen(buf
) > 4 )
539 if ( !ftp
->GetList(files
, wildcard
, start
== wxT("LIST")) )
541 wxPrintf(wxT("ERROR: failed to get %s of files\n"), start
.c_str());
545 wxPrintf(wxT("--- %s of '%s' under '%s':\n"),
546 start
.c_str(), wildcard
.c_str(), ftp
->Pwd().c_str());
547 size_t count
= files
.GetCount();
548 for ( size_t n
= 0; n
< count
; n
++ )
550 wxPrintf(wxT("\t%s\n"), files
[n
].c_str());
552 wxPuts(wxT("--- End of the file list"));
555 else if ( start
== wxT("QUIT") )
557 break; // get out of here!
561 wxChar ch
= ftp
->SendCommand(buf
);
562 wxPrintf(wxT("Command %s"), ch ?
wxT("succeeded") : wxT("failed"));
565 wxPrintf(wxT(" (return code %c)"), ch
);
568 wxPrintf(wxT(", server reply:\n%s\n\n"), ftp
->GetLastResult().c_str());
574 #endif // TEST_INTERACTIVE
577 // ----------------------------------------------------------------------------
579 // ----------------------------------------------------------------------------
581 #ifdef TEST_STACKWALKER
583 #if wxUSE_STACKWALKER
585 #include "wx/stackwalk.h"
587 class StackDump
: public wxStackWalker
590 StackDump(const char *argv0
)
591 : wxStackWalker(argv0
)
595 virtual void Walk(size_t skip
= 1, size_t maxdepth
= wxSTACKWALKER_MAX_DEPTH
)
597 wxPuts(wxT("Stack dump:"));
599 wxStackWalker
::Walk(skip
, maxdepth
);
603 virtual void OnStackFrame(const wxStackFrame
& frame
)
605 printf("[%2d] ", (int) frame
.GetLevel());
607 wxString name
= frame
.GetName();
610 printf("%-20.40s", (const char*)name
.mb_str());
614 printf("0x%08lx", (unsigned long)frame
.GetAddress());
617 if ( frame
.HasSourceLocation() )
620 (const char*)frame
.GetFileName().mb_str(),
621 (int)frame
.GetLine());
627 for ( size_t n
= 0; frame
.GetParam(n
, &type
, &name
, &val
); n
++ )
629 printf("\t%s %s = %s\n", (const char*)type
.mb_str(),
630 (const char*)name
.mb_str(),
631 (const char*)val
.mb_str());
636 static void TestStackWalk(const char *argv0
)
638 wxPuts(wxT("*** Testing wxStackWalker ***"));
640 StackDump
dump(argv0
);
646 #endif // wxUSE_STACKWALKER
648 #endif // TEST_STACKWALKER
650 // ----------------------------------------------------------------------------
652 // ----------------------------------------------------------------------------
656 #include "wx/stdpaths.h"
657 #include "wx/wxchar.h" // wxPrintf
659 static void TestStandardPaths()
661 wxPuts(wxT("*** Testing wxStandardPaths ***"));
663 wxTheApp
->SetAppName(wxT("console"));
665 wxStandardPathsBase
& stdp
= wxStandardPaths
::Get();
666 wxPrintf(wxT("Config dir (sys):\t%s\n"), stdp
.GetConfigDir().c_str());
667 wxPrintf(wxT("Config dir (user):\t%s\n"), stdp
.GetUserConfigDir().c_str());
668 wxPrintf(wxT("Data dir (sys):\t\t%s\n"), stdp
.GetDataDir().c_str());
669 wxPrintf(wxT("Data dir (sys local):\t%s\n"), stdp
.GetLocalDataDir().c_str());
670 wxPrintf(wxT("Data dir (user):\t%s\n"), stdp
.GetUserDataDir().c_str());
671 wxPrintf(wxT("Data dir (user local):\t%s\n"), stdp
.GetUserLocalDataDir().c_str());
672 wxPrintf(wxT("Documents dir:\t\t%s\n"), stdp
.GetDocumentsDir().c_str());
673 wxPrintf(wxT("Executable path:\t%s\n"), stdp
.GetExecutablePath().c_str());
674 wxPrintf(wxT("Plugins dir:\t\t%s\n"), stdp
.GetPluginsDir().c_str());
675 wxPrintf(wxT("Resources dir:\t\t%s\n"), stdp
.GetResourcesDir().c_str());
676 wxPrintf(wxT("Localized res. dir:\t%s\n"),
677 stdp
.GetLocalizedResourcesDir(wxT("fr")).c_str());
678 wxPrintf(wxT("Message catalogs dir:\t%s\n"),
679 stdp
.GetLocalizedResourcesDir
682 wxStandardPaths
::ResourceCat_Messages
688 #endif // TEST_STDPATHS
690 // ----------------------------------------------------------------------------
692 // ----------------------------------------------------------------------------
694 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
700 #include "wx/volume.h"
702 static const wxChar
*volumeKinds
[] =
708 wxT("network volume"),
712 static void TestFSVolume()
714 wxPuts(wxT("*** Testing wxFSVolume class ***"));
716 wxArrayString volumes
= wxFSVolume
::GetVolumes();
717 size_t count
= volumes
.GetCount();
721 wxPuts(wxT("ERROR: no mounted volumes?"));
725 wxPrintf(wxT("%u mounted volumes found:\n"), count
);
727 for ( size_t n
= 0; n
< count
; n
++ )
729 wxFSVolume
vol(volumes
[n
]);
732 wxPuts(wxT("ERROR: couldn't create volume"));
736 wxPrintf(wxT("%u: %s (%s), %s, %s, %s\n"),
738 vol
.GetDisplayName().c_str(),
739 vol
.GetName().c_str(),
740 volumeKinds
[vol
.GetKind()],
741 vol
.IsWritable() ?
wxT("rw") : wxT("ro"),
742 vol
.GetFlags() & wxFS_VOL_REMOVABLE ?
wxT("removable")
749 #endif // TEST_VOLUME
751 // ----------------------------------------------------------------------------
753 // ----------------------------------------------------------------------------
758 #include "wx/datetime.h"
762 static void TestDateTimeInteractive()
764 wxPuts(wxT("\n*** interactive wxDateTime tests ***"));
770 wxPrintf(wxT("Enter a date (or 'quit' to escape): "));
771 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
774 // kill the last '\n'
775 buf
[wxStrlen(buf
) - 1] = 0;
777 if ( wxString(buf
).CmpNoCase("quit") == 0 )
781 const wxChar
*p
= dt
.ParseDate(buf
);
784 wxPrintf(wxT("ERROR: failed to parse the date '%s'.\n"), buf
);
790 wxPrintf(wxT("WARNING: parsed only first %u characters.\n"), p
- buf
);
793 wxPrintf(wxT("%s: day %u, week of month %u/%u, week of year %u\n"),
794 dt
.Format(wxT("%b %d, %Y")).c_str(),
796 dt
.GetWeekOfMonth(wxDateTime
::Monday_First
),
797 dt
.GetWeekOfMonth(wxDateTime
::Sunday_First
),
798 dt
.GetWeekOfYear(wxDateTime
::Monday_First
));
804 #endif // TEST_INTERACTIVE
805 #endif // TEST_DATETIME
807 // ----------------------------------------------------------------------------
809 // ----------------------------------------------------------------------------
813 #include "wx/snglinst.h"
815 static bool TestSingleIstance()
817 wxPuts(wxT("\n*** Testing wxSingleInstanceChecker ***"));
819 wxSingleInstanceChecker checker
;
820 if ( checker
.Create(wxT(".wxconsole.lock")) )
822 if ( checker
.IsAnotherRunning() )
824 wxPrintf(wxT("Another instance of the program is running, exiting.\n"));
829 // wait some time to give time to launch another instance
830 wxPuts(wxT("If you try to run another instance of this program now, it won't start."));
831 wxPrintf(wxT("Press \"Enter\" to exit wxSingleInstanceChecker test and proceed..."));
834 else // failed to create
836 wxPrintf(wxT("Failed to init wxSingleInstanceChecker.\n"));
843 #endif // TEST_SNGLINST
846 // ----------------------------------------------------------------------------
848 // ----------------------------------------------------------------------------
850 int main(int argc
, char **argv
)
853 wxChar
**wxArgv
= new wxChar
*[argc
+ 1];
858 for (n
= 0; n
< argc
; n
++ )
860 wxMB2WXbuf warg
= wxConvertMB2WX(argv
[n
]);
861 wxArgv
[n
] = wxStrdup(warg
);
866 #else // !wxUSE_UNICODE
868 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
870 wxApp
::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "program");
872 wxInitializer initializer
;
875 fprintf(stderr
, "Failed to initialize the wxWidgets library, aborting.");
881 if (!TestSingleIstance())
883 #endif // TEST_SNGLINST
887 #endif // TEST_DYNLIB
890 wxLog
::AddTraceMask(FTP_TRACE_MASK
);
892 // wxFTP cannot be a static variable as its ctor needs to access
893 // wxWidgets internals after it has been initialized
895 ftp
->SetLog(new wxProtocolLog(FTP_TRACE_MASK
));
896 if ( TestFtpConnect() )
897 TestFtpInteractive();
898 //else: connecting to the FTP server failed
909 #ifdef TEST_INFO_FUNCTIONS
917 #endif // TEST_INFO_FUNCTIONS
921 #endif // TEST_PRINTF
923 #if defined TEST_REGEX && TEST_INTERACTIVE
924 TestRegExInteractive();
925 #endif // defined TEST_REGEX && TEST_INTERACTIVE
929 TestDateTimeInteractive();
931 #endif // TEST_DATETIME
933 #ifdef TEST_STACKWALKER
934 #if wxUSE_STACKWALKER
935 TestStackWalk(argv
[0]);
937 #endif // TEST_STACKWALKER
945 #endif // TEST_VOLUME
949 for ( int n
= 0; n
< argc
; n
++ )
954 #endif // wxUSE_UNICODE