]> git.saurik.com Git - wxWidgets.git/blobdiff - samples/console/console.cpp
Added optional parameter to SelectDocumentType() and SelectViewType() to allow the...
[wxWidgets.git] / samples / console / console.cpp
index a935db655f1da7741ad2d345687ee3c15a3137f6..395b6d6f2fa42799e082b40a23db8134a62c6d50 100644 (file)
 //#define TEST_DATETIME
 //#define TEST_DIR
 //#define TEST_DLLLOADER
+//#define TEST_ENVIRON
 //#define TEST_EXECUTE
-#define TEST_FILE
+//#define TEST_FILE
 //#define TEST_FILECONF
+#define TEST_FILENAME
+//#define TEST_FTP
 //#define TEST_HASH
 //#define TEST_LIST
 //#define TEST_LOG
 //#define TEST_LONGLONG
 //#define TEST_MIME
 //#define TEST_INFO_FUNCTIONS
+//#define TEST_REGISTRY
 //#define TEST_SOCKETS
+//#define TEST_STREAMS
 //#define TEST_STRINGS
 //#define TEST_THREADS
 //#define TEST_TIMER
@@ -281,6 +286,43 @@ static void TestDllLoad()
 
 #endif // TEST_DLLLOADER
 
+// ----------------------------------------------------------------------------
+// wxGet/SetEnv
+// ----------------------------------------------------------------------------
+
+#ifdef TEST_ENVIRON
+
+#include <wx/utils.h>
+
+static wxString MyGetEnv(const wxString& var)
+{
+    wxString val;
+    if ( !wxGetEnv(var, &val) )
+        val = _T("<empty>");
+    else
+        val = wxString(_T('\'')) + val + _T('\'');
+
+    return val;
+}
+
+static void TestEnvironment()
+{
+    const wxChar *var = _T("wxTestVar");
+
+    puts("*** testing environment access functions ***");
+
+    printf("Initially getenv(%s) = %s\n", var, MyGetEnv(var).c_str());
+    wxSetEnv(var, _T("value for wxTestVar"));
+    printf("After wxSetEnv: getenv(%s) = %s\n",  var, MyGetEnv(var).c_str());
+    wxSetEnv(var, _T("another value"));
+    printf("After 2nd wxSetEnv: getenv(%s) = %s\n",  var, MyGetEnv(var).c_str());
+    wxUnsetEnv(var);
+    printf("After wxUnsetEnv: getenv(%s) = %s\n",  var, MyGetEnv(var).c_str());
+    printf("PATH = %s\n",  MyGetEnv(_T("PATH")));
+}
+
+#endif // TEST_ENVIRON
+
 // ----------------------------------------------------------------------------
 // wxExecute
 // ----------------------------------------------------------------------------
@@ -294,9 +336,9 @@ static void TestExecute()
     puts("*** testing wxExecute ***");
 
 #ifdef __UNIX__
-    #define COMMAND "echo hi"
+    #define COMMAND "cat -n ../../Makefile" // "echo hi"
     #define SHELL_COMMAND "echo hi from shell"
-    #define REDIRECT_COMMAND "date"
+    #define REDIRECT_COMMAND COMMAND // "date"
 #elif defined(__WXMSW__)
     #define COMMAND "command.com -c 'echo hi'"
     #define SHELL_COMMAND "echo hi"
@@ -355,6 +397,7 @@ static void TestExecute()
 #ifdef TEST_FILE
 
 #include <wx/file.h>
+#include <wx/ffile.h>
 #include <wx/textfile.h>
 
 static void TestFileRead()
@@ -431,6 +474,55 @@ static void TestTextFileRead()
     puts("");
 }
 
+static void TestFileCopy()
+{
+    puts("*** Testing wxCopyFile ***");
+
+    static const wxChar *filename1 = _T("testdata.fc");
+    static const wxChar *filename2 = _T("test2");
+    if ( !wxCopyFile(filename1, filename2) )
+    {
+        puts("ERROR: failed to copy file");
+    }
+    else
+    {
+        wxFFile f1(filename1, "rb"),
+                f2(filename2, "rb");
+
+        if ( !f1.IsOpened() || !f2.IsOpened() )
+        {
+            puts("ERROR: failed to open file(s)");
+        }
+        else
+        {
+            wxString s1, s2;
+            if ( !f1.ReadAll(&s1) || !f2.ReadAll(&s2) )
+            {
+                puts("ERROR: failed to read file(s)");
+            }
+            else
+            {
+                if ( (s1.length() != s2.length()) ||
+                     (memcmp(s1.c_str(), s2.c_str(), s1.length()) != 0) )
+                {
+                    puts("ERROR: copy error!");
+                }
+                else
+                {
+                    puts("File was copied ok.");
+                }
+            }
+        }
+    }
+
+    if ( !wxRemoveFile(filename2) )
+    {
+        puts("ERROR: failed to remove the file");
+    }
+
+    puts("");
+}
+
 #endif // TEST_FILE
 
 // ----------------------------------------------------------------------------
@@ -496,6 +588,95 @@ static void TestFileConfRead()
 
 #endif // TEST_FILECONF
 
+// ----------------------------------------------------------------------------
+// wxFileName
+// ----------------------------------------------------------------------------
+
+#ifdef TEST_FILENAME
+
+#include <wx/filename.h>
+
+static struct FileNameInfo
+{
+    const wxChar *fullname;
+    const wxChar *path;
+    const wxChar *name;
+    const wxChar *ext;
+} filenames[] =
+{
+    { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
+    { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
+    { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
+    { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
+    { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
+    { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
+    { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
+    { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
+};
+
+static void TestFileNameConstruction()
+{
+    puts("*** testing wxFileName construction ***");
+
+    for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
+    {
+        wxFileName fn(filenames[n].fullname, wxPATH_UNIX);
+
+        printf("Filename: '%s'\t", fn.GetFullPath().c_str());
+        if ( !fn.Normalize(wxPATH_NORM_ALL, _T(""), wxPATH_UNIX) )
+        {
+            puts("ERROR (couldn't be normalized)");
+        }
+        else
+        {
+            printf("normalized: '%s'\n", fn.GetFullPath().c_str());
+        }
+    }
+
+    puts("");
+}
+
+static void TestFileNameSplit()
+{
+    puts("*** testing wxFileName splitting ***");
+
+    for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
+    {
+        const FileNameInfo &fni = filenames[n];
+        wxString path, name, ext;
+        wxFileName::SplitPath(fni.fullname, &path, &name, &ext);
+
+        printf("%s -> path = '%s', name = '%s', ext = '%s'",
+               fni.fullname, path.c_str(), name.c_str(), ext.c_str());
+        if ( path != fni.path )
+            printf(" (ERROR: path = '%s')", fni.path);
+        if ( name != fni.name )
+            printf(" (ERROR: name = '%s')", fni.name);
+        if ( ext != fni.ext )
+            printf(" (ERROR: ext = '%s')", fni.ext);
+        puts("");
+    }
+
+    puts("");
+}
+
+static void TestFileNameComparison()
+{
+    // TODO!
+}
+
+static void TestFileNameOperations()
+{
+    // TODO!
+}
+
+static void TestFileNameCwd()
+{
+    // TODO!
+}
+
+#endif // TEST_FILENAME
+
 // ----------------------------------------------------------------------------
 // wxHashTable
 // ----------------------------------------------------------------------------
@@ -723,6 +904,32 @@ static void TestMimeFilename()
     }
 }
 
+static void TestMimeAssociate()
+{
+    wxPuts(_T("*** Testing creation of filetype association ***\n"));
+
+    wxFileType *ft = g_mimeManager.Associate
+                     (
+                        _T(".xyz"),
+                        _T("application/x-xyz"),
+                        _T("XYZFile"), // filetype (MSW only)
+                        _T("XYZ File") // description (Unix only)
+                     );
+    if ( !ft )
+    {
+        wxPuts(_T("ERROR: failed to create association!"));
+    }
+    else
+    {
+        if ( !ft->SetOpenCommand(_T("myprogram")) )
+        {
+            wxPuts(_T("ERROR: failed to set open command!"));
+        }
+
+        delete ft;
+    }
+}
+
 #endif // TEST_MIME
 
 // ----------------------------------------------------------------------------
@@ -1053,6 +1260,120 @@ static void TestLongLongComparison()
 
 #endif // TEST_LONGLONG
 
+// ----------------------------------------------------------------------------
+// registry
+// ----------------------------------------------------------------------------
+
+// this is for MSW only
+#ifndef __WXMSW__
+    #undef TEST_REGISTRY
+#endif
+
+#ifdef TEST_REGISTRY
+
+#include <wx/msw/registry.h>
+
+// I chose this one because I liked its name, but it probably only exists under
+// NT
+static const wxChar *TESTKEY =
+    _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
+
+static void TestRegistryRead()
+{
+    puts("*** testing registry reading ***");
+
+    wxRegKey key(TESTKEY);
+    printf("The test key name is '%s'.\n", key.GetName().c_str());
+    if ( !key.Open() )
+    {
+        puts("ERROR: test key can't be opened, aborting test.");
+
+        return;
+    }
+
+    size_t nSubKeys, nValues;
+    if ( key.GetKeyInfo(&nSubKeys, NULL, &nValues, NULL) )
+    {
+        printf("It has %u subkeys and %u values.\n", nSubKeys, nValues);
+    }
+
+    printf("Enumerating values:\n");
+
+    long dummy;
+    wxString value;
+    bool cont = key.GetFirstValue(value, dummy);
+    while ( cont )
+    {
+        printf("Value '%s': type ", value.c_str());
+        switch ( key.GetValueType(value) )
+        {
+            case wxRegKey::Type_None:   printf("ERROR (none)"); break;
+            case wxRegKey::Type_String: printf("SZ"); break;
+            case wxRegKey::Type_Expand_String: printf("EXPAND_SZ"); break;
+            case wxRegKey::Type_Binary: printf("BINARY"); break;
+            case wxRegKey::Type_Dword: printf("DWORD"); break;
+            case wxRegKey::Type_Multi_String: printf("MULTI_SZ"); break;
+            default: printf("other (unknown)"); break;
+        }
+
+        printf(", value = ");
+        if ( key.IsNumericValue(value) )
+        {
+            long val;
+            key.QueryValue(value, &val);
+            printf("%ld", val);
+        }
+        else // string
+        {
+            wxString val;
+            key.QueryValue(value, val);
+            printf("'%s'", val.c_str());
+
+            key.QueryRawValue(value, val);
+            printf(" (raw value '%s')", val.c_str());
+        }
+
+        putchar('\n');
+
+        cont = key.GetNextValue(value, dummy);
+    }
+}
+
+static void TestRegistryAssociation()
+{
+    /*
+       The second call to deleteself genertaes an error message, with a
+       messagebox saying .flo is crucial to system operation, while the .ddf
+       call also fails, but with no error message
+    */
+
+    wxRegKey key;
+
+    key.SetName("HKEY_CLASSES_ROOT\\.ddf" );
+    key.Create();
+    key = "ddxf_auto_file" ;
+    key.SetName("HKEY_CLASSES_ROOT\\.flo" );
+    key.Create();
+    key = "ddxf_auto_file" ;
+    key.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
+    key.Create();
+    key = "program,0" ;
+    key.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
+    key.Create();
+    key = "program \"%1\"" ;
+
+    key.SetName("HKEY_CLASSES_ROOT\\.ddf" );
+    key.DeleteSelf();
+    key.SetName("HKEY_CLASSES_ROOT\\.flo" );
+    key.DeleteSelf();
+    key.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
+    key.DeleteSelf();
+    key.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
+    key.DeleteSelf();
+}
+
+#endif // TEST_REGISTRY
+
 // ----------------------------------------------------------------------------
 // sockets
 // ----------------------------------------------------------------------------
@@ -1061,7 +1382,6 @@ static void TestLongLongComparison()
 
 #include <wx/socket.h>
 #include <wx/protocol/protocol.h>
-#include <wx/protocol/ftp.h>
 #include <wx/protocol/http.h>
 
 static void TestSocketServer()
@@ -1184,17 +1504,70 @@ static void TestSocketClient()
     }
 }
 
+#endif // TEST_SOCKETS
+
+#ifdef TEST_FTP
+
+#include <wx/protocol/ftp.h>
+
 static void TestProtocolFtp()
 {
     puts("*** Testing wxFTP download ***\n");
 
-    wxLog::AddTraceMask(_T("ftp"));
+    wxFTP ftp;
+
+#ifdef TEST_WUFTPD // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
+    static const char *hostname = "ftp.eudora.com";
+    if ( !ftp.Connect(hostname) )
+    {
+        printf("ERROR: failed to connect to %s\n", hostname);
+    }
+    else
+    {
+        static const char *filename = "eudora/pubs/draft-gellens-submit-09.txt";
+        wxInputStream *in = ftp.GetInputStream(filename);
+        if ( !in )
+        {
+            printf("ERROR: couldn't get input stream for %s\n", filename);
+        }
+        else
+        {
+            size_t size = in->StreamSize();
+            printf("Reading file %s (%u bytes)...", filename, size);
+
+            char *data = new char[size];
+            if ( !in->Read(data, size) )
+            {
+                puts("ERROR: read error");
+            }
+            else
+            {
+                printf("Successfully retrieved the file.\n");
+            }
 
+            delete [] data;
+            delete in;
+        }
+    }
+#else // !TEST_WUFTPD
+
+#if 1
     static const char *hostname = "ftp.wxwindows.org";
+    static const char *directory = "pub";
+    static const char *filename = "welcome.msg";
 
-    printf("--- Attempting to connect to %s:21...\n", hostname);
+    printf("--- Attempting to connect to %s:21 anonymously...\n", hostname);
+#else
+    static const char *hostname = "localhost";
+    static const char *user = "zeitlin";
+    static const char *directory = "/tmp";
+
+    ftp.SetUser(user);
+    ftp.SetPassword("password");
+
+    printf("--- Attempting to connect to %s:21 as %s...\n", hostname, user);
+#endif
 
-    wxFTP ftp;
     if ( !ftp.Connect(hostname) )
     {
         printf("ERROR: failed to connect to %s\n", hostname);
@@ -1203,19 +1576,37 @@ static void TestProtocolFtp()
     {
         printf("--- Connected to %s, current directory is '%s'\n",
                hostname, ftp.Pwd().c_str());
-        if ( !ftp.ChDir(_T("pub")) )
+
+        // test CWD
+        if ( !ftp.ChDir(directory) )
         {
-            puts("ERROR: failed to cd to pub");
+            printf("ERROR: failed to cd to %s\n", directory);
         }
 
+        // test NLIST and LIST
         wxArrayString files;
-        if ( !ftp.GetList(files) )
+        if ( !ftp.GetFilesList(files) )
         {
-            puts("ERROR: failed to get list of files");
+            puts("ERROR: failed to get NLIST of files");
         }
         else
         {
-            printf("List of files under '%s':\n", ftp.Pwd().c_str());
+            printf("Brief list of files under '%s':\n", ftp.Pwd().c_str());
+            size_t count = files.GetCount();
+            for ( size_t n = 0; n < count; n++ )
+            {
+                printf("\t%s\n", files[n].c_str());
+            }
+            puts("End of the file list");
+        }
+
+        if ( !ftp.GetDirList(files) )
+        {
+            puts("ERROR: failed to get LIST of files");
+        }
+        else
+        {
+            printf("Detailed list of files under '%s':\n", ftp.Pwd().c_str());
             size_t count = files.GetCount();
             for ( size_t n = 0; n < count; n++ )
             {
@@ -1229,11 +1620,11 @@ static void TestProtocolFtp()
             puts("ERROR: failed to cd to ..");
         }
 
-        static const char *filename = "welcome.msg";
+        // test RETR
         wxInputStream *in = ftp.GetInputStream(filename);
         if ( !in )
         {
-            puts("ERROR: couldn't get input stream");
+            printf("ERROR: couldn't get input stream for %s\n", filename);
         }
         else
         {
@@ -1253,22 +1644,41 @@ static void TestProtocolFtp()
             delete [] data;
             delete in;
         }
+
+        // test some other FTP commands
+        if ( ftp.SendCommand("STAT") != '2' )
+        {
+            puts("ERROR: STAT failed");
+        }
+        else
+        {
+            printf("STAT returned:\n\n%s\n", ftp.GetLastResult().c_str());
+        }
+
+        if ( ftp.SendCommand("HELP SITE") != '2' )
+        {
+            puts("ERROR: HELP SITE failed");
+        }
+        else
+        {
+            printf("The list of site-specific commands:\n\n%s\n",
+                   ftp.GetLastResult().c_str());
+        }
     }
+#endif // TEST_WUFTPD/!TEST_WUFTPD
 }
 
 static void TestProtocolFtpUpload()
 {
     puts("*** Testing wxFTP uploading ***\n");
 
-    wxLog::AddTraceMask(_T("ftp"));
-
     static const char *hostname = "localhost";
 
     printf("--- Attempting to connect to %s:21...\n", hostname);
 
     wxFTP ftp;
     ftp.SetUser("zeitlin");
-    ftp.SetPassword("insert your password here");
+    ftp.SetPassword("password");
     if ( !ftp.Connect(hostname) )
     {
         printf("ERROR: failed to connect to %s\n", hostname);
@@ -1289,6 +1699,17 @@ static void TestProtocolFtpUpload()
             delete out;
         }
 
+        // send a command to check the remote file
+        if ( ftp.SendCommand(wxString("STAT ") + file1) != '2' )
+        {
+            printf("ERROR: STAT %s failed\n", file1);
+        }
+        else
+        {
+            printf("STAT %s returned:\n\n%s\n",
+                   file1, ftp.GetLastResult().c_str());
+        }
+
         out = ftp.GetOutputStream(file2);
         if ( out )
         {
@@ -1299,7 +1720,34 @@ static void TestProtocolFtpUpload()
     }
 }
 
-#endif // TEST_SOCKETS
+#endif // TEST_FTP
+
+// ----------------------------------------------------------------------------
+// streams
+// ----------------------------------------------------------------------------
+
+#ifdef TEST_STREAMS
+
+#include <wx/mstream.h>
+
+static void TestMemoryStream()
+{
+    puts("*** Testing wxMemoryInputStream ***");
+
+    wxChar buf[1024];
+    wxStrncpy(buf, _T("Hello, stream!"), WXSIZEOF(buf));
+
+    wxMemoryInputStream memInpStream(buf, wxStrlen(buf));
+    printf(_T("Memory stream size: %u\n"), memInpStream.GetSize());
+    while ( !memInpStream.Eof() )
+    {
+        putchar(memInpStream.GetC());
+    }
+
+    puts("\n*** wxMemoryInputStream test done ***");
+}
+
+#endif // TEST_STREAMS
 
 // ----------------------------------------------------------------------------
 // timers
@@ -2974,11 +3422,57 @@ static void PrintArray(const char* name, const wxArrayString& array)
     }
 }
 
-static int StringLenCompare(const wxString& first, const wxString& second)
+static void PrintArray(const char* name, const wxArrayInt& array)
+{
+    printf("Dump of the array '%s'\n", name);
+
+    size_t nCount = array.GetCount();
+    for ( size_t n = 0; n < nCount; n++ )
+    {
+        printf("\t%s[%u] = %d\n", name, n, array[n]);
+    }
+}
+
+int wxCMPFUNC_CONV StringLenCompare(const wxString& first,
+                                    const wxString& second)
 {
     return first.length() - second.length();
 }
 
+int wxCMPFUNC_CONV IntCompare(int *first,
+                              int *second)
+{
+    return *first - *second;
+}
+
+int wxCMPFUNC_CONV IntRevCompare(int *first,
+                              int *second)
+{
+    return *second - *first;
+}
+
+static void TestArrayOfInts()
+{
+    puts("*** Testing wxArrayInt ***\n");
+
+    wxArrayInt a;
+    a.Add(1);
+    a.Add(17);
+    a.Add(5);
+    a.Add(3);
+
+    puts("Initially:");
+    PrintArray("a", a);
+
+    puts("After sort:");
+    a.Sort(IntCompare);
+    PrintArray("a", a);
+
+    puts("After reverse sort:");
+    a.Sort(IntRevCompare);
+    PrintArray("a", a);
+}
+
 #include "wx/dynarray.h"
 
 WX_DECLARE_OBJARRAY(Bar, ArrayBars);
@@ -3438,6 +3932,8 @@ int main(int argc, char **argv)
 #endif // TEST_STRINGS
 
 #ifdef TEST_ARRAYS
+    if ( 0 )
+    {
     wxArrayString a1;
     a1.Add("tiger");
     a1.Add("cat");
@@ -3481,6 +3977,8 @@ int main(int argc, char **argv)
     PrintArray("a1", a1);
 
     TestArrayOfObjects();
+    }
+    TestArrayOfInts();
 #endif // TEST_ARRAYS
 
 #ifdef TEST_DIR
@@ -3491,6 +3989,10 @@ int main(int argc, char **argv)
     TestDllLoad();
 #endif // TEST_DLLLOADER
 
+#ifdef TEST_ENVIRON
+    TestEnvironment();
+#endif // TEST_ENVIRON
+
 #ifdef TEST_EXECUTE
     TestExecute();
 #endif // TEST_EXECUTE
@@ -3524,10 +4026,24 @@ int main(int argc, char **argv)
 
 #ifdef TEST_FILE
     if ( 0 )
+    {
         TestFileRead();
-    TestTextFileRead();
+        TestTextFileRead();
+    }
+    TestFileCopy();
 #endif // TEST_FILE
 
+#ifdef TEST_FILENAME
+    TestFileNameSplit();
+    if ( 0 )
+    {
+        TestFileNameConstruction();
+        TestFileNameCwd();
+        TestFileNameComparison();
+        TestFileNameOperations();
+    }
+#endif // TEST_FILENAME
+
 #ifdef TEST_THREADS
     int nCPUs = wxThread::GetCPUCount();
     printf("This system has %d CPUs\n", nCPUs);
@@ -3574,9 +4090,12 @@ int main(int argc, char **argv)
 #ifdef TEST_MIME
     wxLog::AddTraceMask(_T("mime"));
     if ( 0 )
+    {
         TestMimeEnum();
-    TestMimeOverride();
-    TestMimeFilename();
+        TestMimeOverride();
+        TestMimeFilename();
+    }
+    TestMimeAssociate();
 #endif // TEST_MIME
 
 #ifdef TEST_INFO_FUNCTIONS
@@ -3584,22 +4103,37 @@ int main(int argc, char **argv)
     TestUserInfo();
 #endif // TEST_INFO_FUNCTIONS
 
+#ifdef TEST_REGISTRY
+    if ( 0 )
+        TestRegistryRead();
+    TestRegistryAssociation();
+#endif // TEST_REGISTRY
+
 #ifdef TEST_SOCKETS
     if ( 0 )
     {
         TestSocketServer();
-        TestSocketClient();
-        TestProtocolFtp();
     }
-        TestProtocolFtpUpload();
+        TestSocketClient();
 #endif // TEST_SOCKETS
 
+#ifdef TEST_FTP
+    wxLog::AddTraceMask(_T("ftp"));
+    TestProtocolFtp();
+    if ( 0 )
+    TestProtocolFtpUpload();
+#endif // TEST_FTP
+
+#ifdef TEST_STREAMS
+    TestMemoryStream();
+#endif // TEST_STREAMS
+
 #ifdef TEST_TIMER
     TestStopWatch();
 #endif // TEST_TIMER
 
 #ifdef TEST_DATETIME
-    if ( 0 )
+    if ( 1 )
     {
         TestTimeSet();
         TestTimeStatic();