OSDN Git Service

Batch mode is implemented (still testing)
authorToshi Nagata <alchemist.2005@nifty.com>
Sun, 14 Nov 2021 13:33:30 +0000 (22:33 +0900)
committerToshi Nagata <alchemist.2005@nifty.com>
Sun, 14 Nov 2021 13:33:30 +0000 (22:33 +0900)
MolLib/MainView.c
MolLib/Ruby_bind/Molby_extern.h
MolLib/Ruby_bind/ruby_bind.c
build-xcode/Molby.xcodeproj/project.pbxproj
build-xcode/Molby.xcodeproj/xcshareddata/xcschemes/Molby.xcscheme
wxSources/ConsoleFrame.cpp
wxSources/MoleculeView.cpp
wxSources/MyApp.cpp
wxSources/MyDocument.cpp

index dd1f3ac..361c257 100755 (executable)
@@ -232,6 +232,8 @@ MainView_resizeToFit(MainView *mview)
 {
        Vector p;
        double f[4];
+    if (!gUseGUI)
+        return;
        if (mview == NULL || mview->mol == NULL)
                return;
        if (mview->mol->natoms == 0) {
@@ -560,6 +562,8 @@ MainView_screenCenterPointOfAtom(MainView *mview, int index, float *outScreenPos
 void
 MainView_getCamera(MainView *mview, Vector *outCamera, Vector *outLookAt, Vector *outUp)
 {
+    if (!gUseGUI)
+        return;
        if (mview != NULL) {
                *outCamera = mview->camera;
                *outLookAt = mview->lookat;
@@ -3686,6 +3690,8 @@ MainView_dragTableSelectionToRow(MainView *mview, int row)
 IntGroup *
 MainView_selectedMO(MainView *mview)
 {
+    if (!gUseGUI)
+        return NULL;
        if (mview == NULL || mview->mol == NULL || mview->tableIndex != kMainViewMOTableIndex)
                return NULL;
        return MainViewCallback_getTableSelection(mview);  /*  Note: the indices are 0 based  */
index efc56fa..b67effa 100755 (executable)
@@ -30,6 +30,9 @@ typedef void *RubyValue;
 #define RubyNil ((RubyValue)4)
 #endif
 
+extern int gSuppressConsole;
+extern int gUseGUI;
+    
 extern char *gRubyVersion;
 extern char *gRubyCopyright;
 
@@ -37,6 +40,7 @@ extern void Ruby_showError(int status);
 extern int Ruby_showValue(RubyValue value, char **outValueString);
 extern int Ruby_UpdateUI(int index, Molecule *mol, int *outChecked, char **outTitle);
 
+extern int Molby_loadScript(const char *script, int from_file);
 extern void Molby_startup(const char *script_path, const char *dir);
 extern void Molby_getDescription(char **versionString, char **auxString);
 extern RubyValue Molby_evalRubyScriptOnMolecule(const char *script, Molecule *mol, const char *fname, int *status);
index 6df44fa..44d1ca5 100644 (file)
@@ -340,8 +340,11 @@ static VALUE
 s_Kernel_ExportToClipboard(VALUE self, VALUE sval)
 {
 #if !defined(__CMDMAC__)
-       const char *s = StringValuePtr(sval);
+    const char *s;
        char *ns;
+    if (!gUseGUI)
+        return Qnil;
+    s = StringValuePtr(sval);
 #if __WXMSW__
        /*  Convert the end-of-line characters  */
        {       const char *p; int nc; char *np;
@@ -5395,6 +5398,11 @@ s_Molecule_Open(int argc, VALUE *argv, VALUE self)
        const char *p;
        Molecule *mp;
        VALUE iflag;
+    
+    if (!gUseGUI) {
+        rb_raise(rb_eMolbyError, "Molecule.open is not usable in non-GUI mode. Use Molecule.new instead.");
+    }
+    
        rb_scan_args(argc, argv, "01", &fname);
        if (NIL_P(fname))
                p = NULL;
@@ -12065,31 +12073,68 @@ void
 Ruby_showError(int status)
 {
        static const int tag_raise = 6;
+    char *main_message = "Molby script error";
        char *msg = NULL, *msg2;
        VALUE val, backtrace;
        int interrupted = 0;
+    int exit_status = -1;
        if (status == tag_raise) {
                VALUE errinfo = rb_errinfo();
                VALUE eclass = CLASS_OF(errinfo);
                if (eclass == rb_eInterrupt) {
-                       msg = "Interrupt";
+            main_message = "Molby script interrupted";
+            msg = "Interrupt";
                        interrupted = 1;
-               }
+        } else if (eclass == rb_eSystemExit) {
+            main_message = "Molby script exit";
+            interrupted = 2;
+            val = rb_eval_string_protect("$!.status", &status);
+            if (status == 0) {
+                exit_status = NUM2INT(rb_Integer(val));
+                asprintf(&msg, "Molby script exit with status %d", exit_status);
+            } else {
+                asprintf(&msg, "Molby script exit with unknown status");
+            }
+        }
        }
        gMolbyRunLevel++;
-       backtrace = rb_eval_string_protect("$backtrace = $!.backtrace.join(\"\\n\")", &status);
-       if (msg == NULL) {
-               val = rb_eval_string_protect("$!.to_s", &status);
-               if (status == 0)
-                       msg = RSTRING_PTR(val);
-               else msg = "(message not available)";
-       }
-       asprintf(&msg2, "%s\n%s", msg, RSTRING_PTR(backtrace));
-       MyAppCallback_messageBox(msg2, (interrupted == 0 ? "Molby script error" : "Molby script interrupted"), 0, 3);
+    if (exit_status != 0) {
+        backtrace = rb_eval_string_protect("$backtrace = $!.backtrace.join(\"\\n\")", &status);
+        if (msg == NULL) {
+            val = rb_eval_string_protect("$!.to_s", &status);
+            if (status == 0)
+                msg = RSTRING_PTR(val);
+            else
+                msg = "(message not available)";
+        }
+        asprintf(&msg2, "%s\n%s", msg, RSTRING_PTR(backtrace));
+    } else {
+        msg2 = strdup(msg);
+    }
+       MyAppCallback_messageBox(msg2, main_message, 0, 3);
        free(msg2);
+    if (interrupted == 2) {
+        free(msg);
+        if (!gUseGUI && exit_status == 0)
+            exit(0);  // Capture exit(0) here and force exit
+    }
        gMolbyRunLevel--;
 }
 
+/*  Wrapper function for rb_load_protect or rb_eval_string_protect. Used only in non-GUI mode.  */
+int
+Molby_loadScript(const char *script, int from_file)
+{
+    int status;
+    gMolbyRunLevel++;
+    if (from_file)
+        rb_load_protect(rb_str_new2(script), 0, &status);
+    else
+        rb_eval_string_protect(script, &status);
+    gMolbyRunLevel--;
+    return status;
+}
+
 void
 Molby_getDescription(char **versionString, char **auxString)
 {
@@ -12113,23 +12158,28 @@ Molby_getDescription(char **versionString, char **auxString)
              "Molby",
 #endif
              gVersionString, revisionString, gCopyrightString, gLastBuildString);
-    asprintf(&s2,
-#if !defined(__CMDMAC__)
-                        "\nIncluding:\n"
-                        "%s"
-#else
-                        "Including "
-#endif
-                        "ruby %s, http://www.ruby-lang.org/\n"
-                        "%s\n"
-                        "FFTW 3.3.2, http://www.fftw.org/\n"
-                        "  Copyright (C) 2003, 2007-11 Matteo Frigo"
-                        "  and Massachusetts Institute of Technology",
-                        
-#if !defined(__CMDMAC__)
-                        MyAppCallback_getGUIDescriptionString(),
-#endif
-                        gRubyVersion, gRubyCopyright);
+    if (gUseGUI) {
+        asprintf(&s2,
+                 "\nIncluding:\n"
+                 "%s"
+                 "ruby %s, http://www.ruby-lang.org/\n"
+                 "%s\n"
+                 "FFTW 3.3.2, http://www.fftw.org/\n"
+                 "  Copyright (C) 2003, 2007-11 Matteo Frigo"
+                 "  and Massachusetts Institute of Technology",
+                 MyAppCallback_getGUIDescriptionString(),
+                 gRubyVersion, gRubyCopyright);
+    } else {
+        asprintf(&s2,
+                 "Including "
+                 "ruby %s, http://www.ruby-lang.org/\n"
+                 "%s\n"
+                 "FFTW 3.3.2, http://www.fftw.org/\n"
+                 "  Copyright (C) 2003, 2007-11 Matteo Frigo"
+                 "  and Massachusetts Institute of Technology",
+                 gRubyVersion, gRubyCopyright);
+
+    }
        if (revisionString[0] != 0)
                free(revisionString);
        if (versionString != NULL)
@@ -12150,11 +12200,7 @@ Molby_startup(const char *script, const char *dir)
        {
                gRubyVersion = strdup(ruby_version);
                asprintf(&gRubyCopyright, "%sCopyright (C) %d-%d %s",
-#if defined(__CMDMAC__)
-                                "",
-#else
                                 "  ",  /*  Indent for displaying in About dialog  */
-#endif
                                 RUBY_BIRTH_YEAR, RUBY_RELEASE_YEAR, RUBY_AUTHOR);
        }
        
@@ -12187,44 +12233,34 @@ Molby_startup(const char *script, const char *dir)
                }
     } */
 
-#if defined(__CMDMAC__)
-    {
+    if (!gUseGUI) {
         char *wbuf2;
         Molby_getDescription(&wbuf, &wbuf2);
-        printf("%s\n%s\n", wbuf, wbuf2);
+        MyAppCallback_showScriptMessage("%s\n%s\n", wbuf, wbuf2);
         free(wbuf);
         free(wbuf2);
     }
-#endif
        
        /*  Read atom display parameters  */
        if (ElementParameterInitialize("element.par", &wbuf) != 0) {
-#if defined(__CMDMAC__)
-               fprintf(stderr, "%s\n", wbuf);
-#else
-               MyAppCallback_setConsoleColor(1);
-               MyAppCallback_showScriptMessage("%s", wbuf);
-               MyAppCallback_setConsoleColor(0);
-#endif
+        MyAppCallback_setConsoleColor(1);
+        MyAppCallback_showScriptMessage("%s", wbuf);
+        MyAppCallback_setConsoleColor(0);
                free(wbuf);
        }
        
        /*  Read default parameters  */
        ParameterReadFromFile(gBuiltinParameters, "default.par", &wbuf, NULL);
        if (wbuf != NULL) {
-#if defined(__CMDMAC__)
-               fprintf(stderr, "%s\n", wbuf);
-#else
-               MyAppCallback_setConsoleColor(1);
-               MyAppCallback_showScriptMessage("%s", wbuf);
-               MyAppCallback_setConsoleColor(0);
-#endif
+        MyAppCallback_setConsoleColor(1);
+        MyAppCallback_showScriptMessage("%s", wbuf);
+        MyAppCallback_setConsoleColor(0);
                free(wbuf);
        }
                
        /*  Initialize Ruby interpreter  */
 #if __WXMSW__
-       {
+       if (gUseGUI) {
                /*  On Windows, fileno(stdin|stdout|stderr) returns -2 and
                    it causes rb_bug() (= fatal error) during ruby_init().
                    As a workaround, these standard streams are reopend as
@@ -12264,7 +12300,8 @@ Molby_startup(const char *script, const char *dir)
 
        /*  Define Molby classes  */
        Init_Molby();
-       RubyDialogInitClass();
+    if (gUseGUI)
+        RubyDialogInitClass();
 
        rb_define_const(rb_mMolby, "ResourcePath", val);
        val = Ruby_NewFileStringValue(dir);
@@ -12283,32 +12320,29 @@ Molby_startup(const char *script, const char *dir)
        rb_define_const(rb_mMolby, "DocumentDirectory", val);
        free(p);
        
-#if defined(__CMDMAC__)
-       rb_define_const(rb_mMolby, "HasGUI", Qfalse);
-#else
-       rb_define_const(rb_mMolby, "HasGUI", Qtrue);
-#endif
+    if (gUseGUI)
+        rb_define_const(rb_mMolby, "HasGUI", Qtrue);
+    else
+        rb_define_const(rb_mMolby, "HasGUI", Qfalse);
 
-#if !__CMDMAC__
-       
-       /*  Create objects for stdout and stderr  */
-       val = rb_funcall(rb_cObject, rb_intern("new"), 0);
-       rb_define_singleton_method(val, "write", s_StandardOutput, 1);
-       rb_define_singleton_method(val, "flush", s_FlushConsoleOutput, 0);
-       rb_gv_set("$stdout", val);
-       val = rb_funcall(rb_cObject, rb_intern("new"), 0);
-       rb_define_singleton_method(val, "write", s_StandardErrorOutput, 1);
-       rb_define_singleton_method(val, "flush", s_FlushConsoleOutput, 0);
-       rb_gv_set("$stderr", val);
-
-       /*  Create objects for stdin  */
-       val = rb_funcall(rb_cObject, rb_intern("new"), 0);
-       rb_define_singleton_method(val, "gets", s_StandardInputGets, -1);
-       rb_define_singleton_method(val, "readline", s_StandardInputGets, -1);
-       rb_define_singleton_method(val, "method_missing", s_StandardInputMethodMissing, -1);
-       rb_gv_set("$stdin", val);
-       
-#endif
+    {
+        /*  Create objects for stdout and stderr  */
+        val = rb_funcall(rb_cObject, rb_intern("new"), 0);
+        rb_define_singleton_method(val, "write", s_StandardOutput, 1);
+        rb_define_singleton_method(val, "flush", s_FlushConsoleOutput, 0);
+        rb_gv_set("$stdout", val);
+        val = rb_funcall(rb_cObject, rb_intern("new"), 0);
+        rb_define_singleton_method(val, "write", s_StandardErrorOutput, 1);
+        rb_define_singleton_method(val, "flush", s_FlushConsoleOutput, 0);
+        rb_gv_set("$stderr", val);
+
+        /*  Create objects for stdin  */
+        val = rb_funcall(rb_cObject, rb_intern("new"), 0);
+        rb_define_singleton_method(val, "gets", s_StandardInputGets, -1);
+        rb_define_singleton_method(val, "readline", s_StandardInputGets, -1);
+        rb_define_singleton_method(val, "method_missing", s_StandardInputMethodMissing, -1);
+        rb_gv_set("$stdin", val);
+    }
        
        /*  Global variable to hold error information  */
        rb_define_variable("$backtrace", &gMolbyBacktrace);
@@ -12321,15 +12355,12 @@ Molby_startup(const char *script, const char *dir)
        gScriptMenuCommands = rb_ary_new();
        gScriptMenuEnablers = rb_ary_new();
        
-#if !__CMDMAC__
-       /*  Register interrupt check code  */
-       rb_add_event_hook(s_Event_Callback, RUBY_EVENT_ALL, Qnil);
-#endif
-       
-#if !__CMDMAC__
-       /*  Start interval timer (for periodic polling of interrupt); firing every 50 msec  */
-       s_SetIntervalTimer(0, 50);
-#endif
+    if (gUseGUI) {
+        /*  Register interrupt check code  */
+        rb_add_event_hook(s_Event_Callback, RUBY_EVENT_ALL, Qnil);
+        /*  Start interval timer (for periodic polling of interrupt); firing every 50 msec  */
+        s_SetIntervalTimer(0, 50);
+    }
        
        /*  Read the startup script  */
        if (script != NULL && script[0] != 0) {
index a9d44e8..9a5f756 100644 (file)
                E420BDFC1885749000A2B983 /* MyCommand.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MyCommand.h; sourceTree = "<group>"; };
                E420BE02188574AD00A2B983 /* MyDocManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MyDocManager.cpp; sourceTree = "<group>"; };
                E420BE03188574AD00A2B983 /* MyDocManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MyDocManager.h; sourceTree = "<group>"; };
-               E420BE04188574AD00A2B983 /* MyDocument.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MyDocument.cpp; sourceTree = "<group>"; };
+               E420BE04188574AD00A2B983 /* MyDocument.cpp */ = {isa = PBXFileReference; fileEncoding = 4; indentWidth = 2; lastKnownFileType = sourcecode.cpp.cpp; path = MyDocument.cpp; sourceTree = "<group>"; tabWidth = 2; };
                E420BE05188574AD00A2B983 /* MyDocument.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MyDocument.h; sourceTree = "<group>"; };
                E420BE06188574AD00A2B983 /* MyGLCanvas.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MyGLCanvas.cpp; sourceTree = "<group>"; };
                E420BE07188574AD00A2B983 /* MyGLCanvas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MyGLCanvas.h; sourceTree = "<group>"; };
index 7582803..1594bb0 100644 (file)
@@ -46,7 +46,8 @@
       selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
       selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
       launchStyle = "0"
-      useCustomWorkingDirectory = "NO"
+      useCustomWorkingDirectory = "YES"
+      customWorkingDirectory = "/Users/toshi_n/Development/wxMyProjects/Molby"
       ignoresPersistentStateOnLaunch = "NO"
       debugDocumentVersioning = "YES"
       debugServiceExtension = "internal"
             ReferencedContainer = "container:Molby.xcodeproj">
          </BuildableReference>
       </BuildableProductRunnable>
+      <CommandLineArguments>
+         <CommandLineArgument
+            argument = "-b"
+            isEnabled = "YES">
+         </CommandLineArgument>
+         <CommandLineArgument
+            argument = "_test.mrb"
+            isEnabled = "YES">
+         </CommandLineArgument>
+         <CommandLineArgument
+            argument = "bpy-dipy-Cu.inp.mbsf"
+            isEnabled = "YES">
+         </CommandLineArgument>
+      </CommandLineArguments>
       <AdditionalOptions>
       </AdditionalOptions>
    </LaunchAction>
index 6421fa0..ad6ae32 100755 (executable)
@@ -523,6 +523,13 @@ ConsoleFrame::EmptyBuffer(bool showRubyPrompt)
 int
 MyAppCallback_showScriptMessage(const char *fmt, ...)
 {
+    if (!gUseGUI) {
+        if (!gSuppressConsole) {
+            va_list ap;
+            va_start(ap, fmt);
+            return vprintf(fmt, ap);
+        } else return 0;
+    }
        if (fmt != NULL) {
                char *p;
                va_list ap;
@@ -552,6 +559,8 @@ MyAppCallback_showScriptMessage(const char *fmt, ...)
 void
 MyAppCallback_setConsoleColor(int color)
 {
+    if (!gUseGUI)
+        return;
        wxGetApp().GetConsoleFrame()->SetConsoleColor(color);
 }
 
index b77e627..6524180 100755 (executable)
@@ -1097,7 +1097,7 @@ MainViewCallback_frame(MainView *mview, float *rect)
 void
 MainViewCallback_display(MainView *mview)
 {
-       if (mview != NULL && mview->ref != NULL) {
+       if (gUseGUI && mview != NULL && mview->ref != NULL) {
                wxWindow *canvas = ((MoleculeView *)(mview->ref))->canvas;
                canvas->Refresh();
                canvas->Update();
@@ -1107,7 +1107,7 @@ MainViewCallback_display(MainView *mview)
 void
 MainViewCallback_makeFront(MainView *mview)
 {
-       if (mview != NULL && mview->ref != NULL) {
+       if (gUseGUI && mview != NULL && mview->ref != NULL) {
                ((MoleculeView *)(mview->ref))->GetFrame()->Raise();
        }
 }
@@ -1115,7 +1115,7 @@ MainViewCallback_makeFront(MainView *mview)
 void
 MainViewCallback_setNeedsDisplay(MainView *mview, int flag)
 {
-  if (mview != NULL && mview->ref != NULL) {
+  if (gUseGUI && mview != NULL && mview->ref != NULL) {
     if (flag)
       ((MoleculeView *)(mview->ref))->canvas->Refresh();
   }
@@ -1124,7 +1124,7 @@ MainViewCallback_setNeedsDisplay(MainView *mview, int flag)
 void
 MainViewCallback_updateCanvas(MainView *mview)
 {
-    if (mview != NULL && mview->ref != NULL) {
+    if (gUseGUI && mview != NULL && mview->ref != NULL) {
         ((MoleculeView *)(mview->ref))->canvas->Update();
     }
 }
@@ -1132,7 +1132,7 @@ MainViewCallback_updateCanvas(MainView *mview)
 void
 MainViewCallback_setKeyboardFocus(MainView *mview)
 {
-       if (mview != NULL && mview->ref != NULL) {
+       if (gUseGUI && mview != NULL && mview->ref != NULL) {
                ((MoleculeView *)(mview->ref))->canvas->SetFocus();
        }
 }
@@ -1183,7 +1183,7 @@ MainViewCallback_drawLabel(MainView *mview, const float *pos, const char *label)
 void
 MainViewCallback_drawInfoText(MainView *mview, const char *label)
 {
-       if (mview != NULL && mview->ref != NULL) {
+       if (gUseGUI && mview != NULL && mview->ref != NULL) {
                wxString labelstr(label, WX_DEFAULT_CONV);
                ((MoleculeView *)(mview->ref))->infotext->SetLabel(labelstr);
        }
@@ -1393,6 +1393,8 @@ MainViewCallback_labelSize(struct Label *label, float *outSize)
 int
 MainViewCallback_exportGraphic(MainView *mview, const char *fname, float scale, int bg_color, int width, int height)
 {
+    if (!gUseGUI)
+        return 0;
        if (mview != NULL && mview->ref != NULL && ((MoleculeView *)(mview->ref))->MolDocument() != NULL) {
                wxString fnamestr(fname, wxConvFile);
                return ((MoleculeView *)(mview->ref))->DoExportGraphic(fnamestr, scale, bg_color, width, height);
index 77b3c53..13c1ad0 100755 (executable)
@@ -82,6 +82,9 @@ MyFrame *frame = (MyFrame *) NULL;
 
 bool gInitCompleted = false;
 
+int gSuppressConsole = 0;  //  Non-zero if console output should be suppressed in non-GUI mode
+int gUseGUI = 1;
+
 IMPLEMENT_APP(MyApp)
 
 //IMPLEMENT_CLASS(MyApp, wxApp)
@@ -196,6 +199,57 @@ bool MyApp::OnInit(void)
        wxSystemOptions::SetOption(wxT("osx.openfiledialog.always-show-types"), 1);
 #endif
 
+    //  Called with a batch mode?
+    if (argc > 1 && strcmp(argv[1], "-b") == 0) {
+        gUseGUI = 0;
+        gSuppressConsole = 1;
+        
+        if (argc > 2 && strcmp(argv[2], "-v") == 0)
+            gSuppressConsole = 0;
+
+        static const char fname[] = "startup.rb";
+        wxString dirname = FindResourcePath();
+        
+        dirname += wxFILE_SEP_PATH;
+        dirname += wxT("Scripts");
+        wxString cwd = wxGetCwd();
+        wxSetWorkingDirectory(dirname);
+        
+        wxString fnamestr(fname, wxConvFile);
+        Molby_startup(wxFileExists(fnamestr) ? fname : NULL, (const char *)dirname.mb_str(wxConvFile));
+
+        wxSetWorkingDirectory(cwd);
+        
+        //  Build ARGV
+        int c = (gSuppressConsole ? 2 : 3);
+        int i = 1;
+        int status;
+        if (c >= argc) {
+            if (gSuppressConsole) {
+                fprintf(stderr, "The script is not given\n");
+                exit(1);
+            } else exit(0);  //  Show startup message and exit
+        }
+        wxString argv_script;
+        while (i + c < argc) {
+            wxString arg(argv[i + c]);
+            arg.Replace(wxT("\'"), wxT("\\\'"));
+            argv_script += wxString::Format(wxT("ARGV[%d] = \'"), i - 1);
+            argv_script += arg;
+            argv_script += wxT("\'\n");
+            i++;
+        }
+        gSuppressConsole = 0;  //  Console output is no longer suppressed (startup is done)
+        status = Molby_loadScript(argv_script.mb_str(wxConvFile), 0);
+        if (status == 0)
+            status = Molby_loadScript(argv[c].mb_str(wxConvFile), 1);
+        if (status != 0) {
+            Ruby_showError(status);
+            exit(1);
+        }
+        exit(0);
+    }
+
 #if __WXMSW__
        {
                //  Check if the same application is already running
@@ -671,9 +725,10 @@ sModifyMenuForFilterMode(wxMenuBar *mbar)
 void
 MyApp::ShowProgressPanel(const char *mes)
 {
-       wxString string((mes ? mes : ""), WX_DEFAULT_CONV);
-       if (m_progressDialog == NULL) {
+    wxString string((mes ? mes : ""), WX_DEFAULT_CONV);
+    if (m_progressDialog == NULL) {
         m_progressDialog = new wxProgressDialog(wxT("Progress"), mes);
+    }
 /*
 #if __WXMAC__
                {
@@ -688,7 +743,6 @@ MyApp::ShowProgressPanel(const char *mes)
                m_progressCanceled = false;
                m_progressValue = -1;
 */
-    }
 }
 
 void
@@ -739,13 +793,13 @@ MyApp::SetProgressMessage(const char *mes)
 int
 MyApp::IsInterrupted()
 {
-       if (m_progressDialog != NULL)
+    if (m_progressDialog != NULL)
         return m_progressDialog->WasCancelled();
-       else {
-               if (::wxGetKeyState(WXK_ESCAPE))
-                       return 1;
-               else return 0;          
-       }
+    else {
+        if (::wxGetKeyState(WXK_ESCAPE))
+            return 1;
+        else return 0;
+    }
 }
 
 void
@@ -1862,12 +1916,16 @@ MyAppCallback_getGUIDescriptionString(void)
 void
 MyAppCallback_loadGlobalSettings(void)
 {
+    if (!gUseGUI)
+        return;
        wxGetApp().LoadDefaultSettings();
 }
 
 void
 MyAppCallback_saveGlobalSettings(void)
 {
+    if (!gUseGUI)
+        return;
        wxGetApp().SaveDefaultSettings();
 }
 
@@ -1881,14 +1939,18 @@ MyAppCallback_saveGlobalSettings(void)
 char *
 MyAppCallback_getGlobalSettings(const char *key)
 {
-       wxString wxkey(key, WX_DEFAULT_CONV);
-       wxString wxvalue = wxGetApp().GetDefaultSetting(wxkey);
-       return strdup(wxvalue.mb_str(WX_DEFAULT_CONV));
+    if (!gUseGUI)
+        return NULL;
+    wxString wxkey(key, WX_DEFAULT_CONV);
+    wxString wxvalue = wxGetApp().GetDefaultSetting(wxkey);
+    return strdup(wxvalue.mb_str(WX_DEFAULT_CONV));
 }
 
 void
 MyAppCallback_setGlobalSettings(const char *key, const char *value)
 {
+    if (!gUseGUI)
+        return;
        wxString wxkey(key, WX_DEFAULT_CONV);
        wxString wxvalue(value, WX_DEFAULT_CONV);
        wxGetApp().SetDefaultSetting(wxkey, wxvalue);
@@ -1928,36 +1990,50 @@ MyAppCallback_setGlobalSettingsWithType(const char *key, int type, const void *p
 int
 MyAppCallback_checkInterrupt(void)
 {
-       return wxGetApp().IsInterrupted();
+    if (!gUseGUI)
+        return 0;
+    return wxGetApp().IsInterrupted();
 }
 
 void
 MyAppCallback_showProgressPanel(const char *msg)
 {
-       wxGetApp().ShowProgressPanel(msg);
+    if (!gUseGUI)
+        return;
+    wxGetApp().ShowProgressPanel(msg);
 }
 
 void
 MyAppCallback_hideProgressPanel(void)
 {
-       wxGetApp().HideProgressPanel();
+    if (!gUseGUI)
+        return;
+    wxGetApp().HideProgressPanel();
 }
 
 void
 MyAppCallback_setProgressValue(double dval)
 {
-       wxGetApp().SetProgressValue(dval);
+    if (!gUseGUI)
+        return;
+    wxGetApp().SetProgressValue(dval);
 }
 
 void
 MyAppCallback_setProgressMessage(const char *msg)
 {
-       wxGetApp().SetProgressMessage(msg);
+    if (!gUseGUI)
+        return;
+    wxGetApp().SetProgressMessage(msg);
 }
 
 int
 MyAppCallback_getTextWithPrompt(const char *prompt, char *buf, int bufsize)
 {
+    if (!gUseGUI) {
+        buf[0] = 0;
+        return 0;
+    }
        wxDialog *dialog = new wxDialog(NULL, -1, _T("Input request"), wxDefaultPosition);
        wxStaticText *stext;
        wxTextCtrl *tctrl;
@@ -1995,6 +2071,11 @@ MyAppCallback_getTextWithPrompt(const char *prompt, char *buf, int bufsize)
 int
 MyAppCallback_messageBox(const char *message, const char *title, int flags, int icon)
 {
+    if (!gUseGUI) {
+        printf("%s\n%s\n", title, message);
+        return 1;
+    }
+    
        int wxflags, wxicon, retval;
        if (!wxGetApp().IsMainLoopRunning()) {
                MyAppCallback_setConsoleColor(1);
@@ -2019,6 +2100,12 @@ MyAppCallback_messageBox(const char *message, const char *title, int flags, int
 void
 MyAppCallback_errorMessageBox(const char *fmt, ...)
 {
+    if (!gUseGUI) {
+        va_list ap;
+        va_start(ap, fmt);
+        vfprintf(stderr, fmt, ap);
+        return;
+    }
        char *s;
        int need_free = 0;
        va_list ap;
@@ -2075,18 +2162,26 @@ MyAppCallback_getDocumentHomeDir(void)
 int
 MyAppCallback_registerScriptMenu(const char *title)
 {
+    if (!gUseGUI)
+        return -1;
        return wxGetApp().RegisterScriptMenu(title);
 }
 
 int
 MyAppCallback_lookupScriptMenu(const char *title)
 {
+    if (!gUseGUI)
+        return 0;
        return wxGetApp().LookupScriptMenu(title);
 }
 
 RubyValue
 MyAppCallback_executeScriptFromFile(const char *cpath, int *status)
 {
+    if (!gUseGUI) {
+        return 0;
+    }
+    
        RubyValue retval;
        wxString cwd = wxFileName::GetCwd();
        wxString path(cpath, wxConvFile);
@@ -2173,6 +2268,8 @@ MyAppCallback_executeScriptFromFile(const char *cpath, int *status)
 
 void MyAppCallback_beginUndoGrouping(void)
 {
+    if (!gUseGUI)
+        return;
        wxList &doclist = wxGetApp().DocManager()->GetDocuments();
        wxList::iterator iter;
        for (iter = doclist.begin(); iter != doclist.end(); ++iter) {
@@ -2182,6 +2279,8 @@ void MyAppCallback_beginUndoGrouping(void)
 
 void MyAppCallback_endUndoGrouping(void)
 {
+    if (!gUseGUI)
+        return;
        wxList &doclist = wxGetApp().DocManager()->GetDocuments();
        wxList::iterator iter;
        for (iter = doclist.begin(); iter != doclist.end(); ++iter) {
@@ -2191,11 +2290,15 @@ void MyAppCallback_endUndoGrouping(void)
 
 int MyAppCallback_callSubProcess(const char *cmdline, const char *procname, int (*callback)(void *), void *callback_data, FILE *output, FILE *errout, int *exitstatus_p, int *pid_p)
 {
+    if (!gUseGUI)
+        return system(cmdline);
        return wxGetApp().CallSubProcess(cmdline, procname, callback, callback_data, output, errout, exitstatus_p, pid_p);
 }
 
 void MyAppCallback_showConsoleWindow(void)
 {
+    if (!gUseGUI)
+        return;
        ConsoleFrame *frame = wxGetApp().GetConsoleFrame();
        frame->Show(true);
        frame->Raise();
@@ -2203,17 +2306,23 @@ void MyAppCallback_showConsoleWindow(void)
 
 void MyAppCallback_hideConsoleWindow(void)
 {
+    if (!gUseGUI)
+        return;
        ConsoleFrame *frame = wxGetApp().GetConsoleFrame();
        frame->Hide();
 }
 
 void MyAppCallback_bell(void)
 {
-       wxBell();
+    if (!gUseGUI)
+        return;
+    wxBell();
 }
 
 int MyAppCallback_playSound(const char *filename, int flag)
 {
+    if (!gUseGUI)
+        return 0;
        unsigned uflag = wxSOUND_SYNC;
        if (flag == 1)
                uflag = wxSOUND_ASYNC;
@@ -2226,6 +2335,8 @@ int MyAppCallback_playSound(const char *filename, int flag)
 
 void MyAppCallback_stopSound(void)
 {
+    if (!gUseGUI)
+        return;
        wxSound::Stop();
 }
 
index c7e249c..4941bcf 100755 (executable)
@@ -1520,6 +1520,8 @@ MyDocumentFromMolecule(Molecule *mp)
 Molecule *
 MoleculeCallback_openNewMolecule(const char *fname)
 {
+  if (!gUseGUI)
+    return NULL;
        wxDocument *doc;
        MyDocManager *manager = wxGetApp().DocManager();
        if (fname == NULL || *fname == 0) {
@@ -1536,6 +1538,8 @@ MoleculeCallback_openNewMolecule(const char *fname)
 void
 MoleculeCallback_notifyModification(Molecule *mp, int now_flag)
 {
+  if (!gUseGUI)
+    return;
        MyDocument *doc = MyDocumentFromMolecule(mp);
        if (doc && !doc->isModifyNotificationSent) {
                doc->isModifyNotificationSent = true;
@@ -1646,6 +1650,8 @@ MoleculeCallback_isDataInPasteboard(const char *type)
 Molecule *
 MoleculeCallback_currentMolecule(void)
 {
+  if (!gUseGUI)
+    return NULL;
   MainView *mview = MainViewCallback_activeView();
   if (mview != NULL)
     return mview->mol;
@@ -1655,6 +1661,8 @@ MoleculeCallback_currentMolecule(void)
 Molecule *
 MoleculeCallback_moleculeAtIndex(int idx)
 {
+  if (!gUseGUI)
+    return NULL;
   MainView *mview = MainViewCallback_viewWithTag(idx);
   if (mview != NULL)
     return mview->mol;
@@ -1670,6 +1678,10 @@ MoleculeCallback_moleculeAtOrderedIndex(int idx)
 void
 MoleculeCallback_displayName(Molecule *mol, char *buf, int bufsize)
 {
+  if (!gUseGUI) {
+    buf[0] = 0;
+    return;
+  }
   MyDocument *doc = MyDocumentFromMolecule(mol);
   if (doc != NULL) {
     wxString fname;
@@ -1684,6 +1696,13 @@ MoleculeCallback_displayName(Molecule *mol, char *buf, int bufsize)
 void
 MoleculeCallback_pathName(Molecule *mol, char *buf, int bufsize)
 {
+  if (!gUseGUI) {
+    if (mol != NULL && mol->path != NULL) {
+      strncpy(buf, mol->path, bufsize - 1);
+      buf[bufsize - 1] = 0;
+    } else buf[0] = 0;
+    return;
+  }
        MyDocument *doc = MyDocumentFromMolecule(mol);
        if (doc != NULL && doc->hasFile)
                MainViewCallback_getFilename(mol->mview, buf, bufsize);
@@ -1693,6 +1712,9 @@ MoleculeCallback_pathName(Molecule *mol, char *buf, int bufsize)
 int
 MoleculeCallback_setDisplayName(Molecule *mol, const char *name)
 {
+  if (!gUseGUI) {
+    return 0;
+  }
        MyDocument *doc = MyDocumentFromMolecule(mol);
        if (doc == NULL || doc->hasFile)
                return 1; /*  Cannot change file-associated window title  */
@@ -1705,13 +1727,15 @@ MoleculeCallback_setDisplayName(Molecule *mol, const char *name)
 void
 MoleculeCallback_lockMutex(void *mutex)
 {
-       ((wxMutex *)mutex)->Lock();
+  if (gUseGUI)
+    ((wxMutex *)mutex)->Lock();
 }
 
 void
 MoleculeCallback_unlockMutex(void *mutex)
 {
-       ((wxMutex *)mutex)->Unlock();
+  if (gUseGUI)
+    ((wxMutex *)mutex)->Unlock();
 }
 
 void
@@ -1747,6 +1771,8 @@ MoleculeCallback_cannotModifyMoleculeDuringMDError(Molecule *mol)
 int
 MoleculeCallback_callSubProcessAsync(Molecule *mol, const char *cmd, int (*callback)(Molecule *, int), int (*timerCallback)(Molecule *, int), FILE *output, FILE *errout)
 {
+  if (!gUseGUI)
+    return -1;
        MyDocument *doc = MyDocumentFromMolecule(mol);
        if (doc != NULL)
                return doc->RunSubProcess(cmd, callback, timerCallback, output, errout);
@@ -1756,6 +1782,8 @@ MoleculeCallback_callSubProcessAsync(Molecule *mol, const char *cmd, int (*callb
 void
 MolActionCallback_registerUndo(Molecule *mol, MolAction *action)
 {
+  if (!gUseGUI)
+    return;
        MyDocument *doc = MyDocumentFromMolecule(mol);
        if (doc != NULL && doc->IsUndoEnabled())
                doc->PushUndoAction(action);
@@ -1764,6 +1792,8 @@ MolActionCallback_registerUndo(Molecule *mol, MolAction *action)
 int
 MolActionCallback_setUndoRegistrationEnabled(Molecule *mol, int flag)
 {
+  if (!gUseGUI)
+    return 0;
        MyDocument *doc = MyDocumentFromMolecule(mol);
        if (doc != NULL) {
                doc->SetUndoEnabled(flag);
@@ -1774,6 +1804,8 @@ MolActionCallback_setUndoRegistrationEnabled(Molecule *mol, int flag)
 int
 MolActionCallback_isUndoRegistrationEnabled(Molecule *mol)
 {
+  if (!gUseGUI)
+    return 0;
        MyDocument *doc = MyDocumentFromMolecule(mol);
        if (doc != NULL && doc->IsUndoEnabled())
                return 1;