Sort all includes in src/gromacs
[alexxy/gromacs.git] / src / gromacs / selection / selectionoptionmanager.cpp
index d18b721f916eb7c9e523837e0a5dd1e77561ceb7..ee1e486d0ca9a386830d49d836c820095b220e6b 100644 (file)
@@ -1,48 +1,56 @@
 /*
+ * This file is part of the GROMACS molecular simulation package.
  *
- *                This source code is part of
+ * Copyright (c) 2012,2013,2014, by the GROMACS development team, led by
+ * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
+ * and including many others, as listed in the AUTHORS file in the
+ * top-level source directory and at http://www.gromacs.org.
  *
- *                 G   R   O   M   A   C   S
+ * GROMACS is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 2.1
+ * of the License, or (at your option) any later version.
  *
- *          GROningen MAchine for Chemical Simulations
+ * GROMACS is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
  *
- * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
- * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
- * Copyright (c) 2001-2009, The GROMACS development team,
- * check out http://www.gromacs.org for more information.
-
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with GROMACS; if not, see
+ * http://www.gnu.org/licenses, or write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
  *
- * If you want to redistribute modifications, please consider that
- * scientific software is very special. Version control is crucial -
- * bugs must be traceable. We will be happy to consider code for
- * inclusion in the official distribution, but derived work must not
- * be called official GROMACS. Details are found in the README & COPYING
- * files - if they are missing, get the official version at www.gromacs.org.
+ * If you want to redistribute modifications to GROMACS, please
+ * consider that scientific software is very special. Version
+ * control is crucial - bugs must be traceable. We will be happy to
+ * consider code for inclusion in the official distribution, but
+ * derived work must not be called official GROMACS. Details are found
+ * in the README & COPYING files - if they are missing, get the
+ * official version at http://www.gromacs.org.
  *
  * To help us fund GROMACS development, we humbly ask that you cite
- * the papers on the package - you can find them in the top README file.
- *
- * For more info, check our website at http://www.gromacs.org
+ * the research papers on the package. Check out http://www.gromacs.org.
  */
 /*! \internal \file
  * \brief
  * Implements gmx::SelectionOptionManager.
  *
- * \author Teemu Murtola <teemu.murtola@cbr.su.se>
+ * \author Teemu Murtola <teemu.murtola@gmail.com>
  * \ingroup module_selection
  */
+#include "gmxpre.h"
+
 #include "selectionoptionmanager.h"
 
 #include <cstdio>
 
 #include "gromacs/selection/selection.h"
 #include "gromacs/selection/selectioncollection.h"
+#include "gromacs/selection/selectionfileoption.h"
+#include "gromacs/selection/selectionoption.h"
 #include "gromacs/utility/exceptions.h"
-#include "gromacs/utility/format.h"
+#include "gromacs/utility/stringutil.h"
 
 #include "selectionoptionstorage.h"
 
@@ -98,6 +106,8 @@ class SelectionOptionManager::Impl
 
         //! Collection for a list of selection requests.
         typedef std::vector<SelectionRequest> RequestList;
+        //! Collection for list of option storage objects.
+        typedef std::vector<SelectionOptionStorage *> OptionList;
 
         /*! \brief
          * Helper class that clears a request list on scope exit.
@@ -142,9 +152,17 @@ class SelectionOptionManager::Impl
          * from the list.
          */
         void placeSelectionsInRequests(const SelectionList &selections);
+        /*! \brief
+         * Adds a request for each required option that is not yet set.
+         *
+         * \throws    std::bad_alloc if out of memory.
+         */
+        void requestUnsetRequiredOptions();
 
         //! Selection collection to which selections are stored.
         SelectionCollection    &collection_;
+        //! List of selection options (storage objects) this manager manages.
+        OptionList              options_;
         //! List of selections requested for later parsing.
         RequestList             requests_;
 };
@@ -157,31 +175,50 @@ SelectionOptionManager::Impl::Impl(SelectionCollection *collection)
 void SelectionOptionManager::Impl::placeSelectionsInRequests(
         const SelectionList &selections)
 {
-    RequestsClearer clearRequestsOnExit(&requests_);
+    if (requests_.empty())
+    {
+        requestUnsetRequiredOptions();
+    }
+
+    RequestsClearer               clearRequestsOnExit(&requests_);
 
     SelectionList::const_iterator first = selections.begin();
-    SelectionList::const_iterator last = first;
-    RequestList::const_iterator i;
-    // TODO: Improve error messages.
+    SelectionList::const_iterator last  = first;
+    RequestList::const_iterator   i;
     for (i = requests_.begin(); i != requests_.end(); ++i)
     {
         const SelectionRequest &request = *i;
         if (request.count() > 0)
         {
-            if (selections.end() - first < request.count())
+            int remaining = selections.end() - first;
+            if (remaining < request.count())
             {
-                GMX_THROW(InvalidInputError("Too few selections provided"));
+                int assigned = first - selections.begin();
+                GMX_THROW(InvalidInputError(formatString(
+                                                    "Too few selections provided for '%s': "
+                                                    "Expected %d selections, but only %d left "
+                                                    "after assigning the first %d to other selections.",
+                                                    request.name().c_str(), request.count(),
+                                                    remaining, assigned)));
             }
             last = first + request.count();
         }
         else
         {
-            if (i != requests_.end() - 1)
+            RequestList::const_iterator nextRequest = i;
+            ++nextRequest;
+            if (nextRequest != requests_.end())
             {
-                GMX_THROW(InvalidInputError(
-                            formatString("Request for selection '%s' must "
-                                         "not be followed by others",
-                                         request.name().c_str())));
+                const char *name         = request.name().c_str();
+                const char *conflictName = nextRequest->name().c_str();
+                GMX_THROW(InvalidInputError(formatString(
+                                                    "Ambiguous selections for '%s' and '%s': "
+                                                    "Any number of selections is acceptable for "
+                                                    "'%s', but you have requested subsequent "
+                                                    "selections to be assigned to '%s'. "
+                                                    "Resolution for such cases is not implemented, "
+                                                    "and may be impossible.",
+                                                    name, conflictName, name, conflictName)));
             }
             last = selections.end();
         }
@@ -191,7 +228,27 @@ void SelectionOptionManager::Impl::placeSelectionsInRequests(
     }
     if (last != selections.end())
     {
-        GMX_THROW(InvalidInputError("Too many selections provided"));
+        int count     = selections.end() - selections.begin();
+        int remaining = selections.end() - last;
+        int assigned  = last - selections.begin();
+        GMX_THROW(InvalidInputError(formatString(
+                                            "Too many selections provided: "
+                                            "Expected %d selections, but %d provided. "
+                                            "Last %d selections could not be assigned to any option.",
+                                            assigned, count, remaining)));
+    }
+}
+
+void SelectionOptionManager::Impl::requestUnsetRequiredOptions()
+{
+    OptionList::const_iterator i;
+    for (i = options_.begin(); i != options_.end(); ++i)
+    {
+        SelectionOptionStorage &storage = **i;
+        if (storage.isRequired() && !storage.isSet())
+        {
+            requests_.push_back(SelectionRequest(&storage));
+        }
     }
 }
 
@@ -209,14 +266,25 @@ SelectionOptionManager::~SelectionOptionManager()
 {
 }
 
-SelectionCollection &
-SelectionOptionManager::selectionCollection()
+void
+SelectionOptionManager::registerOption(SelectionOptionStorage *storage)
+{
+    impl_->requests_.reserve(impl_->options_.size() + 1);
+    impl_->options_.push_back(storage);
+}
+
+void
+SelectionOptionManager::convertOptionValue(SelectionOptionStorage *storage,
+                                           const std::string      &value,
+                                           bool                    bFullValue)
 {
-    return impl_->collection_;
+    SelectionList selections = impl_->collection_.parseFromString(value);
+    storage->addSelections(selections, bFullValue);
 }
 
 void
-SelectionOptionManager::requestDelayedParsing(SelectionOptionStorage *storage)
+SelectionOptionManager::requestOptionDelayedParsing(
+        SelectionOptionStorage *storage)
 {
     impl_->requests_.push_back(Impl::SelectionRequest(storage));
 }
@@ -224,34 +292,18 @@ SelectionOptionManager::requestDelayedParsing(SelectionOptionStorage *storage)
 void
 SelectionOptionManager::parseRequestedFromStdin(bool bInteractive)
 {
-    Impl::RequestsClearer clearRequestsOnExit(&impl_->requests_);
+    Impl::RequestsClearer             clearRequestsOnExit(&impl_->requests_);
 
     Impl::RequestList::const_iterator i;
     for (i = impl_->requests_.begin(); i != impl_->requests_.end(); ++i)
     {
         const Impl::SelectionRequest &request = *i;
-        if (bInteractive)
-        {
-            std::fprintf(stderr, "\nSpecify ");
-            if (request.count() < 0)
-            {
-                std::fprintf(stderr, "any number of selections");
-            }
-            else if (request.count() == 1)
-            {
-                std::fprintf(stderr, "a selection");
-            }
-            else
-            {
-                std::fprintf(stderr, "%d selections", request.count());
-            }
-            std::fprintf(stderr, " for option '%s' (%s):\n",
+        std::string                   context =
+            formatString("for option '%s'\n(%s)",
                          request.name().c_str(), request.description().c_str());
-            std::fprintf(stderr, "(one selection per line, 'help' for help%s)\n",
-                         request.count() < 0 ? ", Ctrl-D to end" : "");
-        }
-        SelectionList selections;
-        impl_->collection_.parseFromStdin(request.count(), bInteractive, &selections);
+        SelectionList selections
+            = impl_->collection_.parseFromStdin(request.count(), bInteractive,
+                                                context);
         request.storage_->addSelections(selections, true);
     }
 }
@@ -259,16 +311,24 @@ SelectionOptionManager::parseRequestedFromStdin(bool bInteractive)
 void
 SelectionOptionManager::parseRequestedFromFile(const std::string &filename)
 {
-    SelectionList selections;
-    impl_->collection_.parseFromFile(filename, &selections);
-    impl_->placeSelectionsInRequests(selections);
+    SelectionList selections = impl_->collection_.parseFromFile(filename);
+    try
+    {
+        impl_->placeSelectionsInRequests(selections);
+    }
+    catch (GromacsException &ex)
+    {
+        ex.prependContext(formatString(
+                                  "Error in adding selections from file '%s'",
+                                  filename.c_str()));
+        throw;
+    }
 }
 
 void
 SelectionOptionManager::parseRequestedFromString(const std::string &str)
 {
-    SelectionList selections;
-    impl_->collection_.parseFromString(str, &selections);
+    SelectionList selections = impl_->collection_.parseFromString(str);
     impl_->placeSelectionsInRequests(selections);
 }