#include #include #include #include "FrameUtil/AbsInterp.hh" #include "TclUtils/AbsModuleFactory.hh" #include "TclUtils/FactoryCommand.hh" #include "TclUtils/ModuleRegistry.hh" using namespace std; FactoryCommand::FactoryCommand(const char* const commandName, AbsModuleFactory *factory) : _className(commandName), _factory(factory), _objectCounter(0) { AbsInterp::instance()->createCommand(commandName, this); _defaultDescription = "A module created by "; _defaultDescription += commandName; } FactoryCommand::~FactoryCommand() { AbsInterp::instance()->deleteCommand(_className); } #define check_module do {\ if (module)\ {\ ++_objectCounter;\ ModuleRegistry::instance()->add(name);\ _modules[name] = module;\ std::cout << "Created new module \"" << name << "\"" << std::endl;\ }\ else\ {\ std::cerr << "ERROR in " << _className\ << ": failed to create module \""\ << name << "\"" << std::endl;\ return AbsInterp::ERROR;\ }\ } while(0); #define check_valid_name do {\ if (!*name)\ {\ newname << _className << '_' << _objectCounter << std::ends;\ name = (char*) newname.str().c_str();\ }\ if (ModuleRegistry::instance()->exists(name))\ {\ std::cerr << "ERROR in " << _className\ << ": module named \"" << name\ << "\" already exists" << std::endl;\ return AbsInterp::ERROR;\ }\ } while(0); int FactoryCommand::handle(int argc, char* argv[]) { std::ostringstream newname; AppModule* module = 0; char *name = 0; // The first argument is the name of the command if (argc == 1) { // Create a new name newname << _className << '_' << _objectCounter << std::ends; name = (char*) newname.str().c_str(); check_valid_name; module = _factory->create(name, _defaultDescription.c_str()); check_module; } else if (argc == 2) { if (strcmp(argv[1], "delete") == 0) { std::cerr << "ERROR in " << _className << " delete: module name is missing" << std::endl; } else { name = argv[1]; check_valid_name; module = _factory->create(name, _defaultDescription.c_str()); check_module; } } else if (argc == 3) { if (strcmp(argv[1], "delete") == 0) { name = argv[2]; // Lookup the name std::map::iterator it = _modules.find(name); if (it == _modules.end()) { std::cerr << "ERROR in " << _className << ": didn't create the module \"" << name << "\", can't delete it" << std::endl; return AbsInterp::ERROR; } else if (it->second == 0) { std::cerr << "ERROR in " << _className << ": module \"" << name << "\" is already deleted" << std::endl; return AbsInterp::ERROR; } else { _factory->destroy(it->second); ModuleRegistry::instance()->remove(name); it->second = 0; std::cout << "Deleted module \"" << name << "\"" << std::endl; } } else { name = argv[1]; check_valid_name; module = _factory->create(name, argv[2]); check_module; } } else { std::cerr << "ERROR in " << _className << ": wrong # of arguments" << std::endl; return AbsInterp::ERROR; } return AbsInterp::OK; }