Пример #1
0
void PluginManager::addPlugin(QDir* dir) {
    QDomDocument doc;
    QFile pluginXmlFile(dir->absolutePath()+QDir::separator()+"plugin.xml");
    if(!pluginXmlFile.exists()) {
        qDebug("error plugin.xml not exist "+dir->absolutePath().toUtf8());
        return;
    }
    pluginXmlFile.open(QIODevice::ReadOnly);
    doc.setContent(&pluginXmlFile);
    pluginXmlFile.close();
    QDomElement plugin = doc.documentElement();
    QString name = plugin.lastChildElement("name").text();
    QString version = plugin.lastChildElement("version").text();
    QString description = plugin.lastChildElement("description").text();
    QString cellBackground = dir->absolutePath()+QDir::separator()+plugin.lastChildElement("cellBackground").text();
    Plugin* p =  new Plugin(name, description,version);
    p->setCellBackground(cellBackground);
    qDebug("Plugin: "+name.toUtf8());
    QDomNodeList listPawns = plugin.lastChildElement("pawns").elementsByTagName("pawn");
    for(int i = 0;i < listPawns.count(); i++)
    {
        QString pid = listPawns.at(i).lastChildElement("id").text();
        QString pname = listPawns.at(i).lastChildElement("name").text();
        QString picon = dir->absolutePath()+QDir::separator()+listPawns.at(i).lastChildElement("icon").text();
        if(!p->existPawn(pid))
        {
            qDebug("  Pawn: "+pname.toUtf8()+" (id:"+pid.toUtf8()+", icon:"+picon.toUtf8()+")");
            Pawn* pawn =  new Pawn(pid, pname, picon);
            p->addPawn(pawn);
        }
        else
        {
            qDebug("  Pawn can't add");
        }
    }
    QDomNodeList listrules = plugin.lastChildElement("rules").elementsByTagName("rule");
    for(int i = 0;i < listrules.count(); i++)
    {
        QString from = listrules.at(i).attributes().namedItem("pawn").toAttr().value();
        QString to = listrules.at(i).attributes().namedItem("newPawn").toAttr().value();
        if(p->existPawn(from) && p->existPawn(to)) {
            Rule* r = new Rule(p->getPawn(from), p->getPawn(to));
            qDebug("  Rule: (from:"+from.toUtf8()+" to:"+to.toUtf8()+")");
            for(int j = 0;j < listrules.at(i).childNodes().count(); j++)
            {
                QString op = listrules.at(i).childNodes().at(j).nodeName();
                QString pawn = listrules.at(i).childNodes().at(j).attributes().namedItem("pawn").toAttr().value();
                QString value = listrules.at(i).childNodes().at(j).toElement().text();

                int intValue = value.toInt();
                AbstractOperator* o = NULL;
                if(op == "pawnNumberIsEqual")
                    o = new EqualOperator(intValue, pawn);
                if(op == "pawnNumberIsLower")
                    o = new LowerOperator(intValue, pawn);
                if(op == "pawnNumberIsGreater")
                    o = new GreaterOperator(intValue, pawn);

                if(o != NULL && p->existPawn(pawn))
                {
                    r->addOperator(o);
                    qDebug("    with "+pawn.toUtf8()+" "+op.toUtf8()+" "+value.toUtf8());
                }
                else
                {
                    qDebug("    Operator can't add");
                }

            }
            p->getPawn(from)->addRule(r);
        }
        else
        {
            qDebug("  Rule can't add");
        }
    }
    plugins->push_back(p);
}
Пример #2
0
/** Load plugin.
 * The loading is interrupted if any of the plugins does not load properly.
 * The already loaded plugins are *not* unloaded, but kept.
 * @param plugin_list string containing a comma-separated list of plugins
 * to load. The plugin list can contain meta plugins.
 */
void
PluginManager::load(const std::list<std::string> &plugin_list)
{
  for (std::list<std::string>::const_iterator i = plugin_list.begin(); i != plugin_list.end(); ++i) {
		if ( i->length() == 0 ) continue;

		bool try_real_plugin = true;
		if ( __meta_plugins.find(*i) == __meta_plugins.end() ) {
			std::string meta_plugin = __meta_plugin_prefix + *i;
			bool found_meta = false;
			std::list<std::string> pset;
			try {
				if (__config->is_list(meta_plugin.c_str())) {
					std::vector<std::string> tmp = __config->get_strings(meta_plugin.c_str());
					pset.insert(pset.end(), tmp.begin(), tmp.end());
				}
				else
					pset = parse_plugin_list(__config->get_string(meta_plugin.c_str()).c_str());
				found_meta = true;
			} catch (ConfigEntryNotFoundException &e) {
				// no meta plugin defined by that name
	      //printf("No meta plugin defined with the name %s\n", i->c_str());
				try_real_plugin = true;
			}

			if (found_meta) {
				if (pset.size() == 0) {
					throw Exception("Refusing to load an empty meta plugin");
				}
				//printf("Going to load meta plugin %s (%s)\n", i->c_str(), pset.c_str());
				__meta_plugins.lock();
				// Setting has to happen here, so that a meta plugin will not cause an
				// endless loop if it references itself!
				__meta_plugins[*i] = pset;
				__meta_plugins.unlock();
				try {
					LibLogger::log_info("PluginManager", "Loading plugins %s for meta plugin %s",
                              str_join(pset.begin(), pset.end(), ",").c_str(), i->c_str());
					load(pset);
					LibLogger::log_debug("PluginManager", "Loaded meta plugin %s", i->c_str());
					notify_loaded(i->c_str());
				} catch (Exception &e) {
					e.append("Could not initialize meta plugin %s, aborting loading.", i->c_str());
					__meta_plugins.erase_locked(*i);
					throw;
				}
			
				try_real_plugin = false;
			}
		}

    if (try_real_plugin &&
	(find_if(plugins.begin(), plugins.end(), plname_eq(*i)) == plugins.end()))
    {
      try {
	//printf("Going to load real plugin %s\n", i->c_str());
	Plugin *plugin = plugin_loader->load(i->c_str());
	plugins.lock();
	try {
	  thread_collector->add(plugin->threads());
	  plugins.push_back(plugin);
	  plugin_ids[*i] = next_plugin_id++;
	  LibLogger::log_debug("PluginManager", "Loaded plugin %s", i->c_str());
	  notify_loaded(i->c_str());
	} catch (CannotInitializeThreadException &e) {
	  e.append("Plugin >>> %s <<< could not be initialized, unloading", i->c_str());
	  plugins.unlock();
	  plugin_loader->unload(plugin);
	  throw;
	}
	plugins.unlock();
      } catch (Exception &e) {
	MutexLocker lock(__meta_plugins.mutex());
	if ( __meta_plugins.find(*i) == __meta_plugins.end() ) {
	  // only throw exception if no meta plugin with that name has
	  // already been loaded
	  throw;
	}
      }
    }
  }
}
Пример #3
0
// FIXME: handle name collisions...
command_result PluginManager::InvokeCommand(color_ostream &out, const std::string & command, std::vector <std::string> & parameters)
{
    Plugin *plugin = getPluginByCommand(command);
    return plugin ? plugin->invoke(out, command, parameters) : CR_NOT_IMPLEMENTED;
}
Пример #4
0
void
enumeratePlugins(Verbosity verbosity)
{
    PluginLoader *loader = PluginLoader::getInstance();

    if (verbosity == PluginInformation) {
        cout << "\nVamp plugin libraries found in search path:" << endl;
    }

    vector<PluginLoader::PluginKey> plugins = loader->listPlugins();
    typedef multimap<string, PluginLoader::PluginKey>
        LibraryMap;
    LibraryMap libraryMap;

    for (size_t i = 0; i < plugins.size(); ++i) {
        string path = loader->getLibraryPathForPlugin(plugins[i]);
        libraryMap.insert(LibraryMap::value_type(path, plugins[i]));
    }

    string prevPath = "";
    int index = 0;

    for (LibraryMap::iterator i = libraryMap.begin();
         i != libraryMap.end(); ++i) {
        
        string path = i->first;
        PluginLoader::PluginKey key = i->second;

        if (path != prevPath) {
            prevPath = path;
            index = 0;
            if (verbosity == PluginInformation) {
                cout << "\n  " << path << ":" << endl;
            } else if (verbosity == PluginInformationDetailed) {
                string::size_type ki = i->second.find(':');
                string text = "Library \"" + i->second.substr(0, ki) + "\"";
                cout << "\n" << header(text, 1);
            }
        }

        Plugin *plugin = loader->loadPlugin(key, 48000);
        if (plugin) {

            char c = char('A' + index);
            if (c > 'Z') c = char('a' + (index - 26));

            PluginLoader::PluginCategoryHierarchy category =
                loader->getPluginCategory(key);
            string catstr;
            if (!category.empty()) {
                for (size_t ci = 0; ci < category.size(); ++ci) {
                    if (ci > 0) catstr += " > ";
                        catstr += category[ci];
                }
            }

            if (verbosity == PluginInformation) {

                cout << "    [" << c << "] [v"
                     << plugin->getVampApiVersion() << "] "
                     << plugin->getName() << ", \""
                     << plugin->getIdentifier() << "\"" << " ["
                     << plugin->getMaker() << "]" << endl;
                
                if (catstr != "") {
                    cout << "       > " << catstr << endl;
                }

                if (plugin->getDescription() != "") {
                    cout << "        - " << plugin->getDescription() << endl;
                }

            } else if (verbosity == PluginInformationDetailed) {

                cout << header(plugin->getName(), 2);
                cout << " - Identifier:         "
                     << key << endl;
                cout << " - Plugin Version:     " 
                     << plugin->getPluginVersion() << endl;
                cout << " - Vamp API Version:   "
                     << plugin->getVampApiVersion() << endl;
                cout << " - Maker:              \""
                     << plugin->getMaker() << "\"" << endl;
                cout << " - Copyright:          \""
                     << plugin->getCopyright() << "\"" << endl;
                cout << " - Description:        \""
                     << plugin->getDescription() << "\"" << endl;
                cout << " - Input Domain:       "
                     << (plugin->getInputDomain() == Vamp::Plugin::TimeDomain ?
                         "Time Domain" : "Frequency Domain") << endl;
                cout << " - Default Step Size:  " 
                     << plugin->getPreferredStepSize() << endl;
                cout << " - Default Block Size: " 
                     << plugin->getPreferredBlockSize() << endl;
                cout << " - Minimum Channels:   " 
                     << plugin->getMinChannelCount() << endl;
                cout << " - Maximum Channels:   " 
                     << plugin->getMaxChannelCount() << endl;

            } else if (verbosity == PluginIds) {
                cout << "vamp:" << key << endl;
            }
            
            Plugin::OutputList outputs =
                plugin->getOutputDescriptors();

            if (verbosity == PluginInformationDetailed) {

                Plugin::ParameterList params = plugin->getParameterDescriptors();
                for (size_t j = 0; j < params.size(); ++j) {
                    Plugin::ParameterDescriptor &pd(params[j]);
                    cout << "\nParameter " << j+1 << ": \"" << pd.name << "\"" << endl;
                    cout << " - Identifier:         " << pd.identifier << endl;
                    cout << " - Description:        \"" << pd.description << "\"" << endl;
                    if (pd.unit != "") {
                        cout << " - Unit:               " << pd.unit << endl;
                    }
                    cout << " - Range:              ";
                    cout << pd.minValue << " -> " << pd.maxValue << endl;
                    cout << " - Default:            ";
                    cout << pd.defaultValue << endl;
                    if (pd.isQuantized) {
                        cout << " - Quantize Step:      "
                             << pd.quantizeStep << endl;
                    }
                    if (!pd.valueNames.empty()) {
                        cout << " - Value Names:        ";
                        for (size_t k = 0; k < pd.valueNames.size(); ++k) {
                            if (k > 0) cout << ", ";
                            cout << "\"" << pd.valueNames[k] << "\"";
                        }
                        cout << endl;
                    }
                }

                if (outputs.empty()) {
                    cout << "\n** Note: This plugin reports no outputs!" << endl;
                }
                for (size_t j = 0; j < outputs.size(); ++j) {
                    Plugin::OutputDescriptor &od(outputs[j]);
                    cout << "\nOutput " << j+1 << ": \"" << od.name << "\"" << endl;
                    cout << " - Identifier:         " << od.identifier << endl;
                    cout << " - Description:        \"" << od.description << "\"" << endl;
                    if (od.unit != "") {
                        cout << " - Unit:               " << od.unit << endl;
                    }
                    if (od.hasFixedBinCount) {
                        cout << " - Default Bin Count:  " << od.binCount << endl;
                    }
                    if (!od.binNames.empty()) {
                        bool have = false;
                        for (size_t k = 0; k < od.binNames.size(); ++k) {
                            if (od.binNames[k] != "") {
                                have = true; break;
                            }
                        }
                        if (have) {
                            cout << " - Bin Names:          ";
                            for (size_t k = 0; k < od.binNames.size(); ++k) {
                                if (k > 0) cout << ", ";
                                cout << "\"" << od.binNames[k] << "\"";
                            }
                            cout << endl;
                        }
                    }
                    if (od.hasKnownExtents) {
                        cout << " - Default Extents:    ";
                        cout << od.minValue << " -> " << od.maxValue << endl;
                    }
                    if (od.isQuantized) {
                        cout << " - Quantize Step:      "
                             << od.quantizeStep << endl;
                    }
                    cout << " - Sample Type:        "
                         << (od.sampleType ==
                             Plugin::OutputDescriptor::OneSamplePerStep ?
                             "One Sample Per Step" :
                             od.sampleType ==
                             Plugin::OutputDescriptor::FixedSampleRate ?
                             "Fixed Sample Rate" :
                             "Variable Sample Rate") << endl;
                    if (od.sampleType !=
                        Plugin::OutputDescriptor::OneSamplePerStep) {
                        cout << " - Default Rate:       "
                             << od.sampleRate << endl;
                    }
                    cout << " - Has Duration:       "
                         << (od.hasDuration ? "Yes" : "No") << endl;
                }
            }

            if (outputs.size() > 1 || verbosity == PluginOutputIds) {
                for (size_t j = 0; j < outputs.size(); ++j) {
                    if (verbosity == PluginInformation) {
                        cout << "         (" << j << ") "
                             << outputs[j].name << ", \""
                             << outputs[j].identifier << "\"" << endl;
                        if (outputs[j].description != "") {
                            cout << "             - " 
                                 << outputs[j].description << endl;
                        }
                    } else if (verbosity == PluginOutputIds) {
                        cout << "vamp:" << key << ":" << outputs[j].identifier << endl;
                    }
                }
            }

            ++index;

            delete plugin;
        }
    }

    if (verbosity == PluginInformation ||
        verbosity == PluginInformationDetailed) {
        cout << endl;
    }
}
Пример #5
0
extern "C" Plugin* loadPlugin() {
    Plugin* plugin = new Plugin("Entropy");
    plugin->addOperation(new EntropyOp());
    return plugin;
}
Пример #6
0
inline double ToGameTime(Plugin const& plugin,
                         Instant const& t) {
  return (t - plugin.GameEpoch()) / Second;
}
Пример #7
0
int main (int argc, char* argv[])
{

   struct dirent **namelist;
   int n;

   bool listHelp = false;
   bool listPlugins = false;
   std::string arg;

   for ( int i=1; i < argc; i++ ) {
      arg = std::string( argv[i] );

      if ( arg.compare( "--help" ) == 0 ) {
         listHelp = true;
      } else if ( arg.compare( "--list-modules" ) == 0 ) {
         listPlugins = true;
      } else {
         std::cout << "usage: " << argv[0] << " [--help] [--list-modules]" << std::endl;
         exit(0);
      }
   } 

   if ( !listPlugins && !listHelp ) {
      std::cout << "usage: " << argv[0] << " [--help] [--list-modules]" << std::endl;
      exit(0);
   }

   if ( listPlugins )
      std::cout << "Nanox runtime library available plugins at '" << PLUGIN_DIR << "':" << std::endl;

   n = scandir( PLUGIN_DIR, &namelist, 0, alphasort );

   if ( n < 0 )
      perror( "scandir" );
   else {
      while ( n-- ) {
         std::string name( namelist[n]->d_name );

         if ( name.compare( 0,9,"libnanox-" ) != 0 ) continue;

         if ( name.compare( name.size()-3,3,".so" ) == 0 ) {
            name.erase( name.size()-3 );
            name.erase( 0, std::string("libnanox-").size() );

            if ( PluginManager::isPlugin( name ) ) {
               Plugin *plugin = PluginManager::loadAndGetPlugin( name , false );

               if ( listPlugins && plugin != NULL )
                  std::cout << "   " << name << " - " << plugin->getName() << " - version " << plugin->getVersion() << std::endl;
            }
         }

         free( namelist[n] );
      }

      free( namelist );
   }

   if ( listHelp ) {
      if ( listPlugins )
         std::cout << std::endl;

      std::cout << "Nanos++ runtime library version " << VERSION << "." << std::endl;
      std::cout << std::endl;
      std::cout << "The runtime configuration can be set using arguments added" << std::endl;
      std::cout << "to the NX_ARGS environment variable or through specialised" << std::endl;
      std::cout << "environment variables. As an example of NX_ARGS, to execute" << std::endl;
      std::cout << "with verbose mode and 4 PEs the NX_ARGS environment variable" << std::endl;
      std::cout << "should be: 'NX_ARGS=\"--pes=4 --verbose\"'." << std::endl;
      std::cout << std::endl;
      std::cout << "All NX_ARGS and env vars are listed below." << std::endl;
      std::cout << std::endl;

      std::cout << Config::getNanosHelp();
   }

}
Пример #8
0
// A thread function... for the interactive console.
void fIOthread(void * iodata)
{
    IODATA * iod = ((IODATA*) iodata);
    Core * core = iod->core;
    PluginManager * plug_mgr = ((IODATA*) iodata)->plug_mgr;
    CommandHistory main_history;
    main_history.load("dfhack.history");
    Console & con = core->con;
    if(plug_mgr == 0 || core == 0)
    {
        con.printerr("Something horrible happened in Core's constructor...\n");
        return;
    }
    con.print("DFHack is ready. Have a nice day!\n"
              "Type in '?' or 'help' for general help, 'ls' to see all commands.\n");
    int clueless_counter = 0;
    while (true)
    {
        string command = "";
        int ret = con.lineedit("[DFHack]# ",command, main_history);
        if(ret == -2)
        {
            cerr << "Console is shutting down properly." << endl;
            return;
        }
        else if(ret == -1)
        {
            cerr << "Console caught an unspecified error." << endl;
            continue;
        }
        else if(ret)
        {
            // a proper, non-empty command was entered
            main_history.add(command);
            main_history.save("dfhack.history");
        }
        // cut the input into parts
        vector <string> parts;
        cheap_tokenise(command,parts);
        if(parts.size() == 0)
        {
            clueless_counter ++;
            continue;
        }
        string first = parts[0];
        parts.erase(parts.begin());
        // let's see what we actually got
        if(first=="help" || first == "?")
        {
            if(!parts.size())
            {
                con.print("This is the DFHack console. You can type commands in and manage DFHack plugins from it.\n"
                          "Some basic editing capabilities are included (single-line text editing).\n"
                          "The console also has a command history - you can navigate it with Up and Down keys.\n"
                          "On Windows, you may have to resize your console window. The appropriate menu is accessible\n"
                          "by clicking on the program icon in the top bar of the window.\n\n"
                          "Basic commands:\n"
                          "  help|?                - This text.\n"
                          "  ls|dir [PLUGIN]           - List available commands. Optionally for single plugin.\n"
                          "  cls                   - Clear the console.\n"
                          "  fpause                - Force DF to pause.\n"
                          "  die                   - Force DF to close immediately\n"
                          "Plugin management (useful for developers):\n"
                          //"  belongs COMMAND       - Tell which plugin a command belongs to.\n"
                          "  plug [PLUGIN|v]       - List plugin state and description.\n"
                          "  load PLUGIN|all       - Load a plugin by name or load all possible plugins.\n"
                          "  unload PLUGIN|all     - Unload a plugin or all loaded plugins.\n"
                          "  reload PLUGIN|all     - Reload a plugin or all loaded plugins.\n"
                         );
            }
            else
            {
                con.printerr("not implemented yet\n");
            }
        }
        else if( first == "load" )
        {
            if(parts.size())
            {
                string & plugname = parts[0];
                if(plugname == "all")
                {
                    for(int i = 0; i < plug_mgr->size();i++)
                    {
                        Plugin * plug = (plug_mgr->operator[](i));
                        plug->load();
                    }
                }
                else
                {
                    Plugin * plug = plug_mgr->getPluginByName(plugname);
                    if(!plug) con.printerr("No such plugin\n");
                    plug->load();
                }
            }
        }
        else if( first == "reload" )
        {
            if(parts.size())
            {
                string & plugname = parts[0];
                if(plugname == "all")
                {
                    for(int i = 0; i < plug_mgr->size();i++)
                    {
                        Plugin * plug = (plug_mgr->operator[](i));
                        plug->reload();
                    }
                }
                else
                {
                    Plugin * plug = plug_mgr->getPluginByName(plugname);
                    if(!plug) con.printerr("No such plugin\n");
                    plug->reload();
                }
            }
        }
        else if( first == "unload" )
        {
            if(parts.size())
            {
                string & plugname = parts[0];
                if(plugname == "all")
                {
                    for(int i = 0; i < plug_mgr->size();i++)
                    {
                        Plugin * plug = (plug_mgr->operator[](i));
                        plug->unload();
                    }
                }
                else
                {
                    Plugin * plug = plug_mgr->getPluginByName(plugname);
                    if(!plug) con.printerr("No such plugin\n");
                    plug->unload();
                }
            }
        }
        else if(first == "ls" || first == "dir")
        {
            if(parts.size())
            {
                string & plugname = parts[0];
                const Plugin * plug = plug_mgr->getPluginByName(plugname);
                if(!plug)
                {
                    con.printerr("There's no plugin called %s!\n",plugname.c_str());
                }
                else for (int j = 0; j < plug->size();j++)
                {
                    const PluginCommand & pcmd = (plug->operator[](j));
                    con.print("  %-22s - %s\n",pcmd.name.c_str(), pcmd.description.c_str());
                }
            }
            else
            {
                con.print(
                "builtin:\n"
                "  help|?                - This text or help specific to a plugin.\n"
                "  ls [PLUGIN]           - List available commands. Optionally for single plugin.\n"
                "  cls                   - Clear the console.\n"
                "  fpause                - Force DF to pause.\n"
                "  die                   - Force DF to close immediately\n"
                "  belongs COMMAND       - Tell which plugin a command belongs to.\n"
                "  plug [PLUGIN|v]       - List plugin state and detailed description.\n"
                "  load PLUGIN|all       - Load a plugin by name or load all possible plugins.\n"
                "  unload PLUGIN|all     - Unload a plugin or all loaded plugins.\n"
                "  reload PLUGIN|all     - Reload a plugin or all loaded plugins.\n"
                "\n"
                "plugins:\n"
                );
                for(int i = 0; i < plug_mgr->size();i++)
                {
                    const Plugin * plug = (plug_mgr->operator[](i));
                    if(!plug->size())
                        continue;
                    for (int j = 0; j < plug->size();j++)
                    {
                        const PluginCommand & pcmd = (plug->operator[](j));
                        con.print("  %-22s- %s\n",pcmd.name.c_str(), pcmd.description.c_str());
                    }
                }
            }
        }
        else if(first == "plug")
        {
            for(int i = 0; i < plug_mgr->size();i++)
            {
                const Plugin * plug = (plug_mgr->operator[](i));
                if(!plug->size())
                    continue;
                con.print("%s\n", plug->getName().c_str());
            }
        }
        else if(first == "fpause")
        {
            World * w = core->getWorld();
            w->SetPauseState(true);
            con.print("The game was forced to pause!");
        }
        else if(first == "cls")
        {
            con.clear();
        }
        else if(first == "die")
        {
            _exit(666);
        }
        else
        {
            vector <string> parts;
            cheap_tokenise(command,parts);
            if(parts.size() == 0)
            {
                clueless_counter++;
            }
            else
            {
                string first = parts[0];
                parts.erase(parts.begin());
                command_result res = plug_mgr->InvokeCommand(first, parts);
                if(res == CR_NOT_IMPLEMENTED)
                {
                    con.printerr("Invalid command.\n");
                    clueless_counter ++;
                }
                /*
                else if(res == CR_FAILURE)
                {
                    con.printerr("ERROR!\n");
                }
                */
            }
        }
        if(clueless_counter == 3)
        {
            con.print("Do 'help' or '?' for the list of available commands.\n");
            clueless_counter = 0;
        }
    }
}
Пример #9
0
// Sets the visibility of the debugger.
void SetVisible(bool visibility)
{
    Plugin* plugin = Plugin::GetInstance();
    if (plugin != NULL)
        plugin->SetVisible(visibility);
}
bool basic_builder::BuildScene(string file_name, Camera &camera, Scene &scene) const {
    int line_num = 0;
    char input_line[512];
    Plugin *dat = NULL;  // A container for arbitrary data.
    Object *obj = NULL;  // The current object, which was the last object created.
    Shader *shd = NULL;  // The current shader.
    Aggregate *agg = NULL;  // Current aggregate object, to which all objects are now added.
    Envmap *env = NULL;  // Current environment map.
    Material *mat = NULL;  // Current material pointer.
    Material material;    // Current material.

    scene.object = NULL;
    scene.envmap = NULL;
    scene.rasterize = NULL;

    // Attempt to open the input file.

    file_name += ".sdf";
    std::ifstream fin;
    fin.open(file_name.c_str());
    if (fin.fail()) {
        cerr << "Error: Could not open file " << file_name << endl;
        return false;  // Report failure.
    }
    cout << "Reading " << file_name << "... ";
    cout.flush();

    // Set some defaults.

    material.diffuse = White;
    material.emission = Black;
    material.specular = White;
    material.ambient = Black;
    material.reflectivity = Black;
    material.translucency = Black;
    material.ref_index = 0.0;
    material.Phong_exp = 0.0;

    camera.x_res = default_image_width;
    camera.y_res = default_image_height;
    camera.x_win = Interval(-1.0, 1.0);
    camera.y_win = Interval(-1.0, 1.0);

    // Process lines until the end of file is reached.
    // Print a warning for all lines that are unrecognizable.

    while (fin.getline(input_line, 512)) {
        line_num++;
        if (Skip(input_line)) continue;

        // Ask each registered object if it recognizes the line.  If it does, it will
        // create a new instance of the object and return it as the function value.

        Plugin *plg = Instance_of_Plugin(input_line);

        if (plg != NULL) {
            switch (plg->PluginType()) {
                case data_plugin:
                    if (obj == NULL) cerr << "Error: data ignored.  Line " << line_num << endl;
                    else obj->AddData(obj);
                    break;

                case shader_plugin:
                    shd = (Shader *) plg;
                    break;

                case aggregate_plugin:
                    obj = (Object *) plg;
                    obj->shader = shd;
                    obj->envmap = env;
                    obj->material = Copy(mat, material);
                    obj->parent = agg;
                    if (Emitter(material)) {
                        cerr << "Error: An aggregate object cannot be an emitter.  Line "
                        << line_num << ": "
                        << input_line << endl;
                        return false;
                    }
                    if (agg != NULL) // If there is alrealy an agg obj, this one is a child.
                    {
                        // agg->AddChild( obj );
                        // Do not add aggregates as children until they are complete.
                        agg->material = Copy(mat, material);
                    }
                    else if (scene.object == NULL) scene.object = obj;
                    agg = (Aggregate *) obj;
                    break;

                case primitive_plugin:
                    obj = (Object *) plg;
                    obj->shader = shd;
                    obj->envmap = env;
                    obj->material = Copy(mat, material);
                    obj->parent = agg;
                    if (Emitter(material)) scene.lights.push_back(obj);
                    if (agg != NULL) {
                        agg->AddChild(obj);
                        agg->material = Copy(mat, material);
                    }
                    else if (scene.object == NULL) scene.object = obj;
                    break;

                case envmap_plugin:
                    env = (Envmap *) plg;
                    // If an environment map is set before any object is created, use it as
                    // the background.
                    if (obj == NULL) scene.envmap = env;
                    break;

                case rasterizer_plugin:
                    if (scene.rasterize != NULL) {
                        cerr << "Error: More than one rasterizer specified.  Line "
                        << line_num << ": "
                        << input_line << endl;
                        return false;
                    }
                    scene.rasterize = (Rasterizer *) plg;
                    break;
            }
            continue;
        }

        // Now look for all the other stuff...  materials, camera, lights, etc.

        ParamReader get(input_line);

        if (get["eye"] && get[camera.eye]) continue;
        if (get["lookat"] && get[camera.lookat]) continue;
        if (get["up"] && get[camera.up]) continue;
        if (get["vpdist"] && get[camera.vpdist]) continue;
        if (get["x_res"] && get[camera.x_res]) continue;
        if (get["y_res"] && get[camera.y_res]) continue;
        if (get["x_win"] && get[camera.x_win]) continue;
        if (get["y_win"] && get[camera.y_win]) continue;
        if (get["ambient"] && get[material.ambient]) continue;
        if (get["diffuse"] && get[material.diffuse]) continue;
        if (get["specular"] && get[material.specular]) continue;
        if (get["emission"] && get[material.emission]) continue;
        if (get["reflectivity"] && get[material.reflectivity]) continue;
        if (get["translucency"] && get[material.translucency]) continue;
        if (get["Phong_exp"] && get[material.Phong_exp]) continue;
        if (get["ref_index"] && get[material.ref_index]) continue;

        // If no object is defined at this point, it's an error.

        if (obj == NULL) {
            cerr << "Error reading scene file; No object defined at line "
            << line_num << ": "
            << input_line << endl;
            return false;
        }

        // Look for an end statement that closes the current aggregate.  This allows us to nest aggregates.

        if (get["end"]) {
            if (agg == NULL) {
                cerr << "Error: end statement found outside an aggregate object at line "
                << line_num << ": "
                << input_line << endl;
                return false;
            }

            // Go back to adding objects to the parent object (if there is one).

            agg->Close(); // Signal the aggregate that it is now complete.
            Object *closed_agg = agg;
            agg = agg->parent;
            if (agg != NULL) {
                material = *(agg->material);
                mat = agg->material;
                shd = agg->shader;
                env = agg->envmap;
                agg->AddChild(closed_agg); // Add the agg that just ended.
            }
            continue;
        }

        // If nothing matched, it's an error.  Print a warning and continue processing.

        cerr << "Warning: Unrecognized or ill-formed command at line "
        << line_num << ": "
        << input_line << endl;
    }

    if (agg != NULL) {
        cerr << "Error: Top-most aggregate object has no 'end' statement." << endl;
        return false;
    }

    cout << "done." << endl;
    return true;
}
Пример #11
0
/*!
  Quick load a plugin, doing all phases {pre,,post}Load.
  \param server The server object to use.
  \param plugins comma separed list of plugins to load as:
  "name1:pluginfile1.so,name2:pluginfile2.so"
*/
int
PluginsManager::quickLoad (Server *server, const string &plugins)
{
  size_t start = 0;
  int ret = 0;
  while (1)
    {
      size_t commaPos = plugins.find (",", start);

      size_t sep = plugins.find (":", start);
      if (sep > commaPos || sep == string::npos)
        {
          server->log (MYSERVER_LOG_MSG_ERROR,
                       _("Invalid plugins data specified"));
          return -1;
        }

      string name = plugins.substr (start, sep - start);
      string file = plugins.substr (sep + 1, commaPos == string::npos
                                    ? string::npos
                                    : commaPos - sep - 1);

      string dir;
      string filename;
      FilesUtility::splitPath (file, dir, filename);

      string xmlDescriptor = dir + "/plugin.xml";
      PluginInfo *pinfo = loadInfo (server, name, xmlDescriptor);

      if (! pinfo)
        {
          server->log (MYSERVER_LOG_MSG_ERROR,
                       _("Cannot find the plugin data, please check "
                         "that the specified name and path are correct"));
          return -1;
        }

      auto_ptr<PluginInfo> pinfoAutoPtr (pinfo);

      ret |= loadFile (server, name, file, pinfo);

      pinfoAutoPtr.release ();

      Plugin *plugin = pinfo->getPlugin ();
      if (! plugin)
        {
          server->log (MYSERVER_LOG_MSG_ERROR,
                       _("Cannot load plugin %s"), file.c_str ());
          return -1;
        }

      ret |= plugin->load (server);
      ret |= plugin->postLoad (server);

      if (commaPos == string::npos)
        break;

      start = commaPos + 1;
    }

  return ret;
}
Пример #12
0
void Simulator::initializeCC3D(){


	try{
		cerr<<"BEFORE initializePotts"<<endl;
		//initializePotts(ps.pottsParseData);
		initializePottsCC3D(ps.pottsCC3DXMLElement);
		


		//initializing parallel utils  - OpenMP
		pUtils->init(potts.getCellFieldG()->getDim());
        potts.setParallelUtils(pUtils); // by default Potts gets pUtls which can have multiple threads
        
        //initializing parallel utils  - OpenMP  - for single CPU runs of selecte modules
        pUtilsSingle->init(potts.getCellFieldG()->getDim());

        
        
		//after pUtils have been initialized we process metadata -  in this function potts may get pUtils limiting it to use single thread
		processMetadataCC3D(ps.metadataCC3DXMLElement);


		cerr<<"AFTER initializePotts"<<endl;
		std::set<std::string> initializedPlugins;
		std::set<std::string> initializedSteppables;

		for(size_t i=0; i <ps.pluginCC3DXMLElementVector.size(); ++i){

			std::string pluginName = ps.pluginCC3DXMLElementVector[i]->getAttribute("Name");
			bool pluginAlreadyRegisteredFlag=false;
			Plugin *plugin = pluginManager.get(pluginName,&pluginAlreadyRegisteredFlag);
			if(!pluginAlreadyRegisteredFlag){
				//Will only process first occurence of a given plugin
				cerr<<"INITIALIZING "<<pluginName<<endl;
				plugin->init(this, ps.pluginCC3DXMLElementVector[i]);
			}
		}

		for(size_t i=0; i <ps.steppableCC3DXMLElementVector.size(); ++i){
			std::string steppableName = ps.steppableCC3DXMLElementVector[i]->getAttribute("Type");
			bool steppableAlreadyRegisteredFlag=false;
			Steppable *steppable = steppableManager.get(steppableName,&steppableAlreadyRegisteredFlag);

			if(!steppableAlreadyRegisteredFlag){
				//Will only process first occurence of a given steppable
				cerr<<"INITIALIZING "<<steppableName<<endl;
				if(ps.steppableCC3DXMLElementVector[i]->findAttribute("Frequency"))
					steppable->frequency=ps.steppableCC3DXMLElementVector[i]->getAttributeAsUInt("Frequency");

				steppable->init(this, ps.steppableCC3DXMLElementVector[i]);
				classRegistry->addStepper(steppableName,steppable);

			} 
		}
		if(ppdCC3DPtr->cellTypeMotilityVector.size()){
			//for(int i =0 ; i < ppdCC3DPtr->cellTypeMotilityVector.size() ;++i ){
			//	cerr<<" GOT THIS CELL TYPE FOR MOTILITY"<<	ppdCC3DPtr->cellTypeMotilityVector[i].typeName<<endl;
			//}

			potts.initializeCellTypeMotility(ppdCC3DPtr->cellTypeMotilityVector);		
		}

	}catch (const BasicException &e) {
		cerr << "ERROR: " << e << endl;
		stringstream errorMessageStream;

		errorMessageStream<<"Exception during initialization/parsing :\n"<<e.getMessage()<<"\n"<<"Location \n"<<"FILE :"<<e.getLocation().getFilename()<<"\n"<<"LINE :"<<e.getLocation().getLine();
		recentErrorMessage=errorMessageStream.str(); 
		cerr<<"THIS IS recentErrorMessage="<<recentErrorMessage<<endl;
		if (!newPlayerFlag){
			throw e;
		}

	}
}
Пример #13
0
/// TODO: This code can be simplified.  Make a PortContainer class.
/// Plugin and Patch can inherit from PortContainer.  We can have a
/// pseudo-PortContainer here to represent the input and output ports
/// Then, all adds/removals will be symetric
/// ^^^: Or, just wrap Plugin and BackendPorts with a class that acts this way
void FxLine::addPlugin(const PluginInfoPtr info, int pos)
{
    int idx = pos + 1;
    int pluginCnt = m_entries.length() - 2;

    // Check for proper position value. TODO: Report error, not fatal
    Q_ASSERT(pos <= pluginCnt);

    // Create the plugin. TODO: Report error, not fatal
    Plugin *plugin = info->createPlugin(48000);
    Q_ASSERT(plugin);

    plugin->activate(Engine::bufferProvider());
    m_parent.add(plugin);

    // Verify number of ports. TODO: Report error, not fatal
    Q_ASSERT(plugin->audioInputCount() == 2);
    Q_ASSERT(plugin->audioOutputCount() == 2);

    // Collect ports.
    Entry entry;
    entry.plugin = plugin;
    collectPorts(plugin, &entry.inputPorts, &entry.outputPorts);
    Q_ASSERT(entry.inputPorts.length() == 2);
    Q_ASSERT(entry.outputPorts.length() == 2);

    /*
    if (m_plugins.length() == 0) {
      // If there are no plugins, we disconnect the backend ports from each
      // other. Then, we connect the plugin in-between the backend ports

      // TODO: Bring back once backend ports have patch?
      // m_inPorts[0]->disconnect(m_outPorts[0]);
      // m_inPorts[1]->disconnect(m_outPorts[1]);

      m_inPorts[0]->connect(pluginIn.at(0));
      m_inPorts[1]->connect(pluginIn.at(1));

      m_outPorts[0]->connect(pluginOut.at(0));
      m_outPorts[1]->connect(pluginOut.at(1));
    }
    else if (pos < m_plugins.length()) {
    */
    // At this point, there is at least one plugin already in the line, and we
    // are trying to insert the new plugin before another one.
    Entry producer = m_entries.value(idx-1);
    Entry consumer = m_entries.value(idx);

    qWarning() << "FX LINE ADD producer port count:" << producer.outputPorts.count();
    for (int i=0; i<producer.outputPorts.count(); ++i) {
        Port *producerPort = producer.outputPorts.at(i);
        Port *consumerPort = consumer.inputPorts.at(i);

        // Work around:
        if (producerPort->parentPatch() == NULL && consumerPort->parentPatch() == NULL) {
            qWarning("Probably disconnecting two backend-ports. Ignoring");
        }
        else {
            producerPort->disconnect(consumerPort);
        }
        qWarning() << "FX: Connecting: " << producerPort->name() << " TO " << entry.inputPorts.at(i)->name();
        qWarning() << "FX: and Connecting: " << consumerPort->name() << " TO " << entry.outputPorts.at(i)->name();
        producerPort->connect(entry.inputPorts.at(i));
        consumerPort->connect(entry.outputPorts.at(i));
    }

    m_entries.insert(idx, entry);
}
Пример #14
0
/**
 * Opens a plugin.
 *
 * The config will be used as is. So be sure to transfer ownership
 * of the config to it, with e.g. ksDup().
 * elektraPluginClose() will delete the config.
 *
 * @return a pointer to a new created plugin or 0 on error
 */
Plugin * elektraPluginOpen (const char * name, KeySet * modules, KeySet * config, Key * errorKey)
{
	Plugin * handle = 0;
	const char * n;

	elektraPluginFactory pluginFactory = 0;

	if (!name || name[0] == '\0')
	{
		ELEKTRA_ADD_WARNING (39, errorKey, "name is null or empty");
		goto err_clup;
	}

	n = name;
	while (*n != '\0')
	{
		if (*n == '/')
			++n;
		else
			break;
	}

	if (*n == '\0')
	{
		ELEKTRA_ADD_WARNING (39, errorKey, "name contained slashes only");
		goto err_clup;
	}

	pluginFactory = elektraModulesLoad (modules, name, errorKey);
	if (pluginFactory == 0)
	{
		/* warning already set by elektraModulesLoad */
		goto err_clup;
	}

	handle = pluginFactory ();
	if (handle == 0)
	{
		ELEKTRA_ADD_WARNING (6, errorKey, name);
		goto err_clup;
	}

	/* init reference counting */
	handle->refcounter = 1;
	handle->config = config;
	config = 0; // for err_clup case

	/* let the plugin initialize itself */
	if (handle->kdbOpen)
	{
		if ((handle->kdbOpen (handle, errorKey)) == -1)
		{
			ELEKTRA_ADD_WARNING (11, errorKey, name);
			elektraPluginClose (handle, errorKey);
			goto err_clup;
		}
	}

#if DEBUG && VERBOSE
	printf ("Finished loading plugin %s\n", name);
#endif
	return handle;

err_clup:
#if DEBUG
	printf ("Failed to load plugin %s\n", name);
#endif
	ksDel (config);
	return 0;
}
Пример #15
0
Plugin *VampEffectsModule::FindPlugin(const wxString & path,
                                      int & output,
                                      bool & hasParameters)
{
   PluginLoader::PluginKey key = path.BeforeLast(wxT('/')).ToUTF8().data();

   Plugin *vp = PluginLoader::getInstance()->loadPlugin(key, 48000); // rate doesn't matter here
   if (!vp)
   {
      return false;
   }

   // We limit the listed plugin outputs to those whose results can
   // readily be displayed in an Audacity label track.
   //
   // - Any output whose features have no values (time instants only),
   //   with or without duration, is fine
   //
   // - Any output whose features have more than one value, or an
   //   unknown or variable number of values, is right out
   //
   // - Any output whose features have exactly one value, with
   //   variable sample rate or with duration, should be OK --
   //   this implies a sparse feature, of which the time and/or
   //   duration are significant aspects worth displaying
   //
   // - An output whose features have exactly one value, with
   //   fixed sample rate and no duration, cannot be usefully
   //   displayed -- the value is the only significant piece of
   //   data there and we have no good value plot

   Plugin::OutputList outputs = vp->getOutputDescriptors();

   output = 0;

   hasParameters = !vp->getParameterDescriptors().empty();

   for (Plugin::OutputList::iterator j = outputs.begin(); j != outputs.end(); ++j)
   {
      if (j->sampleType == Plugin::OutputDescriptor::FixedSampleRate ||
            j->sampleType == Plugin::OutputDescriptor::OneSamplePerStep ||
            !j->hasFixedBinCount ||
            (j->hasFixedBinCount && j->binCount > 1))
      {
         // All of these qualities disqualify (see notes above)

         ++output;
         continue;
      }

      wxString name = wxString::FromUTF8(vp->getName().c_str());

      if (outputs.size() > 1)
      {
         // This is not the plugin's only output.
         // Use "plugin name: output name" as the effect name,
         // unless the output name is the same as the plugin name
         wxString outputName = wxString::FromUTF8(j->name.c_str());
         if (outputName != name)
         {
            name = wxString::Format(wxT("%s: %s"),
                                    name.c_str(), outputName.c_str());
         }
      }

      if (wxString::FromUTF8(key.c_str()) + wxT("/") + name == path)
      {
         return vp;
      }

      ++output;
   }

   delete vp;

   return NULL;
}
Пример #16
0
int main (int argc, char ** argv)
{
	if (argc < 4 || argc > 5 || (argc == 5 && elektraStrCmp (argv[4], "get") != 0))
	{
		fprintf (stderr, "Usage: %s <path> <parent> <plugin> [get]\n", argv[0]);
		return 1;
	}

	typedef enum
	{
		BOTH,
		GET,
		Default = BOTH
	} Direction;

	Direction direction;
	if (argc == 5) direction = GET;

	const char * path = argv[1];
	const char * parent = argv[2];
	const char * pluginname = argv[3];

	KeySet * ks = ksNew (0, KS_END);
	char * infile = elektraFormat ("%s/test.%s.in", path, pluginname);
	char * outfile = elektraFormat ("%s/test.%s.out", path, pluginname);

	{
		Key * getKey = keyNew (parent, KEY_VALUE, infile, KEY_END);

		KeySet * conf = ksNew (0, KS_END);
		KeySet * modules = ksNew (0, KS_END);
		elektraModulesInit (modules, 0);
		Key * errorKey = keyNew ("", KEY_END);
		Plugin * plugin = elektraPluginOpen (pluginname, modules, conf, errorKey);
		keyDel (errorKey);

		plugin->kdbGet (plugin, ks, getKey);

		keyDel (getKey);
		elektraPluginClose (plugin, 0);
		elektraModulesClose (modules, 0);
		ksDel (modules);
	}

	if (ksGetSize (ks) <= 0)
	{
		return 1;
	}

	if (direction == BOTH)
	{
		Key * setKey = keyNew (parent, KEY_VALUE, outfile, KEY_END);

		KeySet * conf = ksNew (0, KS_END);
		KeySet * modules = ksNew (0, KS_END);
		elektraModulesInit (modules, 0);
		Key * errorKey = keyNew ("", KEY_END);
		Plugin * plugin = elektraPluginOpen (pluginname, modules, conf, errorKey);
		keyDel (errorKey);
		plugin->kdbSet (plugin, ks, setKey);

		keyDel (setKey);
		elektraPluginClose (plugin, 0);
		elektraModulesClose (modules, 0);
		ksDel (modules);
	}

	elektraFree (infile);
	elektraFree (outfile);

	ksDel (ks);
	return 0;
}
Пример #17
0
inline Instant FromGameTime(Plugin const& plugin,
                            double const t) {
  return plugin.GameEpoch() + t * Second;
}
Пример #18
0
int CpluffAdapter::loadPluginInfoToManager(const std::string path)
{
    //get plugins information.
    if ((m_cp_plugins = cp_get_plugins_info(m_context, &m_status, nullptr)) == nullptr)
    {
        printf("cp_get_plugins_infor failed\n");
        return FALSE;
    }
    else
    {
        printPluginList();
    }

    for (int i = 0 ; m_cp_plugins[i] != nullptr; i++)
    {
        Plugin *plugin = new Plugin;
        plugin->setValue("Path", m_cp_plugins[i]->plugin_path);
        plugin->setValue("Language", "CPP");
        //printf("add filepath %s\n",m_cp_plugins[i]->plugin_path);
        if (m_cp_plugins[i]->identifier != nullptr)
        {
            plugin->setValue("Id", m_cp_plugins[i]->identifier );
        }
        else
        {
            plugin->setValue("Id", "");
        }

        if (m_cp_plugins[i]->url != nullptr)
        {
            plugin->setValue("Url", m_cp_plugins[i]->url);
        }
        else
        {
            plugin->setValue("Url", "");
        }

        if (m_cp_plugins[i]->name != nullptr)
        {
            plugin->setValue("Name", m_cp_plugins[i]->name);
        }
        else
        {
            plugin->setValue("Name", "");
        }

        if (m_cp_plugins[i]->resourcetype != nullptr)
        {
            plugin->setValue("ResourceType", m_cp_plugins[i]->resourcetype);
        }
        else
        {
            plugin->setValue("ResourceType", "");
        }

        if (m_cp_plugins[i]->version != nullptr)
        {
            plugin->setValue("Version", m_cp_plugins[i]->version);
        }
        else
        {
            plugin->setValue("Version", "");
        }

        bool plugin_compare_flag = true;
        for (unsigned int i = 0 ; i < m_plugins.size(); i++)
        {
            if (*plugin == m_plugins[i])
            {
                delete(plugin);
                plugin_compare_flag = false;
                break;
            }
        }
        if (plugin_compare_flag)
        {
            //Auto plugin detection is disabled
            /*
            try
            {
                boost::thread *t = new boost::thread(boost::bind(&CpluffAdapter::observePluginPath,
                                                     //this, (void *)path.c_str()));
                                                     this, (void *)m_cp_plugins[i]->plugin_path));
                m_thread_g.add_thread(t);
            }
            catch (...)
            {
                printf("thread throw exception\n");
            }
            */
            m_plugins.push_back(*plugin);
            delete(plugin);
        }
    }

    return TRUE;
}
Пример #19
0
inline not_null<Vessel*> GetVessel(Plugin const& plugin,
                                   char const* const vessel_guid) {
  CHECK(plugin.HasVessel(vessel_guid)) << vessel_guid;
  return plugin.GetVessel(vessel_guid);
}
Пример #20
0
void load_plugins( string path, map<string, Command_Rights>& plugins, list<Plugin*>& liste)
{

    void(*sendMsg)(void(*)(const string, const string));
    void(*setColor)(string(*)(const string, const string));
    void(*setRegister)(void(*)(ScheduleDetails));
    void(*setGenerate)(ScheduleDetails(*)(vector<string>));
    void(*setCall)(void(*)(string,vector<string>, string));
    void(*setSay)(void(*)(string));
    void(*setCreateTable)(bool(*)(string));
    void(*setSqlCmd)(bool(*)(string));
    struct dirent* dp;

    DIR* dir = opendir( path.c_str());
    if( !dir)
    {
        cout << "opendir() failure; terminating" << endl;
        return;
    }

    while( (dp = readdir(  dir)) != nullptr)
    {
        if( !strcmp( &dp->d_name[strlen(dp->d_name)-3], ".so") || !strcmp( &dp->d_name[strlen(dp->d_name)-4], ".dll"))
        {
            string name = path;
            name += dp->d_name;

            cout << "Loading: " << name << endl;
            void* lib_handle = dlopen( name.c_str(), RTLD_LAZY);
            
            if( !lib_handle)
            {
               cerr << dlerror() << endl;
               exit(1);
            }

            char* error;
            PluginDetails* info;
            info = reinterpret_cast<PluginDetails*>(dlsym(lib_handle, "exports"));
           
            if( (error = dlerror()) != NULL)
            {
                cerr << error << endl;
                exit(2);
            }
            
            *(void**)(&sendMsg) = dlsym(lib_handle, "set_send_msg");
            if( !sendMsg)
            {
                cerr << dlerror() << endl;
                exit(3);
            }
            sendMsg(send_msg);

            *(void**)(&setColor) = dlsym(lib_handle, "set_add_color");
            if( !setColor)
            {
                cerr << dlerror() << endl;
                exit(3);
            }
            setColor( add_color);

            *(void**)(&setRegister) = dlsym(lib_handle, "set_add_reg_task");
            if( !setRegister)
            {
                cerr << dlerror() << endl;
                exit(3);
            }
            setRegister( register_task);

            *(void**)(&setGenerate) = dlsym(lib_handle, "set_generate_schedule");
            if( !setGenerate)
            {
                cerr << dlerror() << endl;
                exit(3);
            }
            setGenerate( generate_task);

            *(void**)(&setCall) = dlsym(lib_handle, "set_call");
            if( !setCall)
            {
                cerr << dlerror() << endl;
                exit(3);
            }
            setCall( call);

            *(void**)(&setSay) = dlsym(lib_handle, "set_say");
            if( !setSay)
            {
                cerr << dlerror() << endl;
                exit(3);
            }
            setSay( say);

            *(void**)(&setCreateTable) = dlsym(lib_handle, "set_create_table");
            if( !setCreateTable)
            {
                cerr << dlerror() << endl;
                exit(3);
            }
            setCreateTable( create_table);

            *(void**)(&setSqlCmd) = dlsym(lib_handle, "set_sql");
            if( !setSqlCmd)
            {
                cerr << dlerror() << endl;
                exit(3);
            }
            setSqlCmd( sql_command);

            cout << "Plugin info: " << "\nFile Name: " << info->file_name << endl;
            cout << "Class name: " << info->class_name << endl;
            cout << "plugin name: " << info->plugin_name << endl;
            cout << "Command: " << info->command << endl;

            Plugin* pl = info->initFunc();
            pl->set_handle(lib_handle);

            list_commands( info->command, pl, plugins,liste);

        }
    }
}
Пример #21
0
int runPlugin(string myname, string soname, string id,
              string output, int outputNo, string wavname,
              string outfilename, bool useFrames)
{
    PluginLoader *loader = PluginLoader::getInstance();

    PluginLoader::PluginKey key = loader->composePluginKey(soname, id);
    
    SNDFILE *sndfile;
    SF_INFO sfinfo;
    memset(&sfinfo, 0, sizeof(SF_INFO));

    sndfile = sf_open(wavname.c_str(), SFM_READ, &sfinfo);
    if (!sndfile) {
        cerr << myname << ": ERROR: Failed to open input file \""
             << wavname << "\": " << sf_strerror(sndfile) << endl;
        return 1;
    }

    ofstream *out = 0;
    if (outfilename != "") {
        out = new ofstream(outfilename.c_str(), ios::out);
        if (!*out) {
            cerr << myname << ": ERROR: Failed to open output file \""
                 << outfilename << "\" for writing" << endl;
            delete out;
            return 1;
        }
    }

    Plugin *plugin = loader->loadPlugin
        (key, sfinfo.samplerate, PluginLoader::ADAPT_ALL_SAFE);
    if (!plugin) {
        cerr << myname << ": ERROR: Failed to load plugin \"" << id
             << "\" from library \"" << soname << "\"" << endl;
        sf_close(sndfile);
        if (out) {
            out->close();
            delete out;
        }
        return 1;
    }

    cerr << "Running plugin: \"" << plugin->getIdentifier() << "\"..." << endl;

    // Note that the following would be much simpler if we used a
    // PluginBufferingAdapter as well -- i.e. if we had passed
    // PluginLoader::ADAPT_ALL to loader->loadPlugin() above, instead
    // of ADAPT_ALL_SAFE.  Then we could simply specify our own block
    // size, keep the step size equal to the block size, and ignore
    // the plugin's bleatings.  However, there are some issues with
    // using a PluginBufferingAdapter that make the results sometimes
    // technically different from (if effectively the same as) the
    // un-adapted plugin, so we aren't doing that here.  See the
    // PluginBufferingAdapter documentation for details.

    int blockSize = plugin->getPreferredBlockSize();
    int stepSize = plugin->getPreferredStepSize();

    if (blockSize == 0) {
        blockSize = 1024;
    }
    if (stepSize == 0) {
        if (plugin->getInputDomain() == Plugin::FrequencyDomain) {
            stepSize = blockSize/2;
        } else {
            stepSize = blockSize;
        }
    } else if (stepSize > blockSize) {
        cerr << "WARNING: stepSize " << stepSize << " > blockSize " << blockSize << ", resetting blockSize to ";
        if (plugin->getInputDomain() == Plugin::FrequencyDomain) {
            blockSize = stepSize * 2;
        } else {
            blockSize = stepSize;
        }
        cerr << blockSize << endl;
    }
    int overlapSize = blockSize - stepSize;
    sf_count_t currentStep = 0;
    int finalStepsRemaining = max(1, (blockSize / stepSize) - 1); // at end of file, this many part-silent frames needed after we hit EOF

    int channels = sfinfo.channels;

    float *filebuf = new float[blockSize * channels];
    float **plugbuf = new float*[channels];
    for (int c = 0; c < channels; ++c) plugbuf[c] = new float[blockSize + 2];

    cerr << "Using block size = " << blockSize << ", step size = "
              << stepSize << endl;

    // The channel queries here are for informational purposes only --
    // a PluginChannelAdapter is being used automatically behind the
    // scenes, and it will take case of any channel mismatch

    int minch = plugin->getMinChannelCount();
    int maxch = plugin->getMaxChannelCount();
    cerr << "Plugin accepts " << minch << " -> " << maxch << " channel(s)" << endl;
    cerr << "Sound file has " << channels << " (will mix/augment if necessary)" << endl;

    Plugin::OutputList outputs = plugin->getOutputDescriptors();
    Plugin::OutputDescriptor od;
    Plugin::FeatureSet features;

    int returnValue = 1;
    int progress = 0;

    RealTime rt;
    PluginWrapper *wrapper = 0;
    RealTime adjustment = RealTime::zeroTime;

    if (outputs.empty()) {
        cerr << "ERROR: Plugin has no outputs!" << endl;
        goto done;
    }

    if (outputNo < 0) {

        for (size_t oi = 0; oi < outputs.size(); ++oi) {
            if (outputs[oi].identifier == output) {
                outputNo = oi;
                break;
            }
        }

        if (outputNo < 0) {
            cerr << "ERROR: Non-existent output \"" << output << "\" requested" << endl;
            goto done;
        }

    } else {

        if (int(outputs.size()) <= outputNo) {
            cerr << "ERROR: Output " << outputNo << " requested, but plugin has only " << outputs.size() << " output(s)" << endl;
            goto done;
        }        
    }

    od = outputs[outputNo];
    cerr << "Output is: \"" << od.identifier << "\"" << endl;

    if (!plugin->initialise(channels, stepSize, blockSize)) {
        cerr << "ERROR: Plugin initialise (channels = " << channels
             << ", stepSize = " << stepSize << ", blockSize = "
             << blockSize << ") failed." << endl;
        goto done;
    }

    wrapper = dynamic_cast<PluginWrapper *>(plugin);
    if (wrapper) {
        // See documentation for
        // PluginInputDomainAdapter::getTimestampAdjustment
        PluginInputDomainAdapter *ida =
            wrapper->getWrapper<PluginInputDomainAdapter>();
        if (ida) adjustment = ida->getTimestampAdjustment();
    }
    
    // Here we iterate over the frames, avoiding asking the numframes in case it's streaming input.
    do {

        int count;

        if ((blockSize==stepSize) || (currentStep==0)) {
            // read a full fresh block
            if ((count = sf_readf_float(sndfile, filebuf, blockSize)) < 0) {
                cerr << "ERROR: sf_readf_float failed: " << sf_strerror(sndfile) << endl;
                break;
            }
            if (count != blockSize) --finalStepsRemaining;
        } else {
            //  otherwise shunt the existing data down and read the remainder.
            memmove(filebuf, filebuf + (stepSize * channels), overlapSize * channels * sizeof(float));
            if ((count = sf_readf_float(sndfile, filebuf + (overlapSize * channels), stepSize)) < 0) {
                cerr << "ERROR: sf_readf_float failed: " << sf_strerror(sndfile) << endl;
                break;
            }
            if (count != stepSize) --finalStepsRemaining;
            count += overlapSize;
        }

        for (int c = 0; c < channels; ++c) {
            int j = 0;
            while (j < count) {
                plugbuf[c][j] = filebuf[j * sfinfo.channels + c];
                ++j;
            }
            while (j < blockSize) {
                plugbuf[c][j] = 0.0f;
                ++j;
            }
        }

        rt = RealTime::frame2RealTime(currentStep * stepSize, sfinfo.samplerate);

        features = plugin->process(plugbuf, rt);
        
        printFeatures
            (RealTime::realTime2Frame(rt + adjustment, sfinfo.samplerate),
             sfinfo.samplerate, od, outputNo, features, out, useFrames);

        if (sfinfo.frames > 0){
            int pp = progress;
            progress = (int)((float(currentStep * stepSize) / sfinfo.frames) * 100.f + 0.5f);
            if (progress != pp && out) {
                cerr << "\r" << progress << "%";
            }
        }

        ++currentStep;

    } while (finalStepsRemaining > 0);

    if (out) cerr << "\rDone" << endl;

    rt = RealTime::frame2RealTime(currentStep * stepSize, sfinfo.samplerate);

    features = plugin->getRemainingFeatures();
    
    printFeatures(RealTime::realTime2Frame(rt + adjustment, sfinfo.samplerate),
                  sfinfo.samplerate, od, outputNo, features, out, useFrames);

    returnValue = 0;

done:
    delete plugin;
    if (out) {
        out->close();
        delete out;
    }
    sf_close(sndfile);
    return returnValue;
}
Пример #22
0
/* Main function*/
extern "C" ASAPI ASErr PluginMain(char* caller, char* selector, void* message)
{
	ASErr error = kNoErr;
	SPMessageData *msgData = (SPMessageData *)message;
	
	Plugin *plugin = (Plugin *)msgData->globals;
	
	sSPBasic = msgData->basic;
	
	if (strcmp(caller, kSPInterfaceCaller) == 0) 
	{	
		if (strcmp( selector, kSPInterfaceStartupSelector) == 0)
		{
			plugin = AllocatePlugin(msgData->self);
			if (plugin)
			{
				msgData->globals = (void *)plugin;
				error = plugin->StartupPlugin((SPInterfaceMessage *)message);

				if (error != kNoErr)
				{
					// Make sure to delete in case startup failed
					delete plugin;
					plugin = nil;
					msgData->globals = nil;
				}
			}
			else
			{
				error = kOutOfMemoryErr;
			}
		}
		else if (strcmp(selector, kSPInterfaceShutdownSelector) == 0)
		{
			if (plugin)
			{
				error = plugin->ShutdownPlugin((SPInterfaceMessage *)message);				
				delete plugin;
				plugin = nil;
				msgData->globals = nil;
			}
		}
	}
	
	if (plugin)
	{
		if (Plugin::IsReloadMsg(caller, selector))
		{
			// Call this before calling any virtual functions (like Message)
			FixupReload(plugin);
			error = plugin->ReloadPlugin((SPInterfaceMessage *)message);
		}
		else
		{
			// If a load or reload failed because the suites could not be acquired, we released
			// any partially acquired suites and returned an error.  However, SuitePea still might
			// call us, so protect against this situation.
			if (plugin->SuitesAcquired())
			{
				// this is important, the plugin will trigger the Message function
				// when something is happening
				error = plugin->Message(caller, selector, message);
				//std::cout << "Messsage\n";
			}
			else
				error = kNoErr;
		}

		if (error == kUnhandledMsgErr)
		{
			error = kNoErr;
#ifndef NDEBUG
#ifdef MAC_ENV
			fprintf(stderr, "Warning: Unhandled plugin message: caller \"%s\" selector \"%s\"\n", caller, selector);
#else
			char buf[1024];
			
			sprintf(buf+1, "Warning: Unhandled plugin message: caller \"%s\" selector \"%s\"\n", caller, selector);
			OutputDebugStringA(buf+1);
#endif
#endif
		}
	}	

	if (error)
	{
		if (plugin)
			plugin->ReportError(error, caller, selector, message);
		else
			Plugin::DefaultError(msgData->self, error);
	}
	
	return error;
}
Пример #23
0
NodeCreationDialog::NodeCreationDialog(const QString& initialFilter,
                                       QWidget* parent)
    : QDialog(parent)
    , _imp( new NodeCreationDialogPrivate() )
{
    setWindowTitle( tr("Node Creation Tool") );
    setWindowFlags(Qt::Popup);
    setObjectName( QString::fromUtf8("nodeCreationDialog") );
    setAttribute(Qt::WA_DeleteOnClose, false);
    _imp->layout = new QVBoxLayout(this);
    _imp->layout->setContentsMargins(0, 0, 0, 0);


    CompleterLineEdit::PluginsNamesMap pluginsMap;
    QString initialFilterName;
    std::string stdInitialFilter = initialFilter.toStdString();
    int i = 0;
    for (PluginsMap::iterator it = _imp->items.begin(); it != _imp->items.end(); ++it) {
        if ( it->second.empty() ) {
            continue;
        }


        if (it->second.size() == 1) {
            std::pair<QString, QString> idNamePair;
            Plugin* p = ( *it->second.begin() );
            if ( !p->getIsUserCreatable() ) {
                continue;
            }

            idNamePair.second = p->generateUserFriendlyPluginID();

            int indexOfBracket = idNamePair.second.lastIndexOf( QString::fromUtf8("  [") );
            if (indexOfBracket != -1) {
                idNamePair.first = idNamePair.second.left(indexOfBracket);
            }

            int weight = getPluginWeight( p->getPluginID(), p->getMajorVersion() );
            pluginsMap.insert( std::make_pair(weight, idNamePair) );

            if (it->first == stdInitialFilter) {
                initialFilterName = idNamePair.first;
            }
            ++i;
        } else {
            QString bestMajorName;
            for (PluginMajorsOrdered::reverse_iterator it2 = it->second.rbegin(); it2 != it->second.rend(); ++it2) {
                if ( !(*it2)->getIsUserCreatable() ) {
                    continue;
                }
                std::pair<QString, QString> idNamePair;
                if ( it2 == it->second.rbegin() ) {
                    idNamePair.second = (*it2)->generateUserFriendlyPluginID();
                    bestMajorName = idNamePair.second;
                } else {
                    idNamePair.second = (*it2)->generateUserFriendlyPluginIDMajorEncoded();
                }


                int indexOfBracket = idNamePair.second.lastIndexOf( QString::fromUtf8("  [") );
                if (indexOfBracket != -1) {
                    idNamePair.first = idNamePair.second.left(indexOfBracket);
                }

                ++i;

                int weight = getPluginWeight( (*it2)->getPluginID(), (*it2)->getMajorVersion() );
                pluginsMap.insert( std::make_pair(weight, idNamePair) );
            }
            if (it->first == stdInitialFilter) {
                initialFilterName = bestMajorName;
            }
        }
    }

    _imp->textEdit = new CompleterLineEdit(pluginsMap, true, this);
    if ( !initialFilterName.isEmpty() ) {
        _imp->textEdit->setText(initialFilterName);
    }

    QPoint global = QCursor::pos();
    QSize sizeH = sizeHint();
    global.rx() -= sizeH.width() / 2;
    global.ry() -= sizeH.height() / 2;
    move( global.x(), global.y() );

    _imp->layout->addWidget(_imp->textEdit);
    _imp->textEdit->setFocus();
    _imp->textEdit->selectAll();
    QTimer::singleShot( 20, _imp->textEdit, SLOT(showCompleter()) );
}
Пример #24
0
Plugin *
PluginLoader::loadPlugin(const QString &name)
{
    KLibrary *lib = NULL;
    KLibFactory *factory = NULL;
    Plugin *plugin = NULL;
    PluginMap::iterator it;
    bool success = true;

    // if the plugin has already been loaded, increment
    // its reference and return.
    if((it = _plugins.find(name)) != _plugins.end()) {
        plugin = it.value();
        plugin->ref();
        return plugin;
    }

    // use KLibLoader to get a reference to the library
    lib = KLibLoader::self()->library(name);
    if(!lib) {
        kError() << "failed loading plugin library " << name << endl;
        success = false;
    }

    // get the factory from the library
    if(success) {
        factory = lib->factory();
        if(!factory) {
            kError() << "failed to find factory for " << name << endl;
            success = false;
        }
    }

    // use the factory to create the plugin
    if(success) {
        plugin = dynamic_cast<Plugin *>(factory->create((QObject*)0));
        if(!plugin) {
            kError() << "failed to create a plugin object for " << name << endl;
            success = false;
        }
        else {
            // we have to register the plugin here, otherwise, we can get
            // recursive loads
            plugin->setObjectName( name );
            _plugins[name] = plugin;
            _categories[plugin->category()].append(plugin);
        }
    }

    // initialize the plugin
    if(success && plugin) {
        success = plugin->init();
        if(!success) {
            // on failure, delete the plugin. this should cause the
            // library to unload.
            kError() << "failure initializing " << name << endl;
            _categories[plugin->category()].remove(plugin);
            _plugins.remove(name);
            delete plugin;
        }
    }

    // finally, finally connect to the destroyed signal and keep a
    // reference to it
    if(success) {
        plugin->ref();
        connect(plugin, SIGNAL(destroyed(QObject *)), SLOT(slotDestroyed(QObject *)));
    }

    return plugin;
}
Пример #25
0
static void runInteractiveCommand(Core *core, PluginManager *plug_mgr, int &clueless_counter, const string &command)
{
    Console & con = core->con;
    
    if (!command.empty())
    {
        // cut the input into parts
        vector <string> parts;
        cheap_tokenise(command,parts);
        if(parts.size() == 0)
        {
            clueless_counter ++;
            return;
        }
        string first = parts[0];
        parts.erase(parts.begin());

        if (first[0] == '#') return;

        cerr << "Invoking: " << command << endl;
        
        // let's see what we actually got
        if(first=="help" || first == "?" || first == "man")
        {
            if(!parts.size())
            {
                con.print("This is the DFHack console. You can type commands in and manage DFHack plugins from it.\n"
                          "Some basic editing capabilities are included (single-line text editing).\n"
                          "The console also has a command history - you can navigate it with Up and Down keys.\n"
                          "On Windows, you may have to resize your console window. The appropriate menu is accessible\n"
                          "by clicking on the program icon in the top bar of the window.\n\n"
                          "Basic commands:\n"
                          "  help|?|man            - This text.\n"
                          "  help COMMAND          - Usage help for the given command.\n"
                          "  ls|dir [PLUGIN]       - List available commands. Optionally for single plugin.\n"
                          "  cls                   - Clear the console.\n"
                          "  fpause                - Force DF to pause.\n"
                          "  die                   - Force DF to close immediately\n"
                          "  keybinding            - Modify bindings of commands to keys\n"
                          "Plugin management (useful for developers):\n"
                          //"  belongs COMMAND       - Tell which plugin a command belongs to.\n"
                          "  plug [PLUGIN|v]       - List plugin state and description.\n"
                          "  load PLUGIN|all       - Load a plugin by name or load all possible plugins.\n"
                          "  unload PLUGIN|all     - Unload a plugin or all loaded plugins.\n"
                          "  reload PLUGIN|all     - Reload a plugin or all loaded plugins.\n"
                         );
            }
            else if (parts.size() == 1)
            {
                Plugin *plug = plug_mgr->getPluginByCommand(parts[0]);
                if (plug) {
                    for (size_t j = 0; j < plug->size();j++)
                    {
                        const PluginCommand & pcmd = (plug->operator[](j));
                        if (pcmd.name != parts[0])
                            continue;

                        if (pcmd.isHotkeyCommand())
                            con.color(Console::COLOR_CYAN);
                        con.print("%s: %s\n",pcmd.name.c_str(), pcmd.description.c_str());
                        con.reset_color();
                        if (!pcmd.usage.empty())
                            con << "Usage:\n" << pcmd.usage << flush;
                        return;
                    }
                }
                con.printerr("Unknown command: %s\n", parts[0].c_str());
            }
            else
            {
                con.printerr("not implemented yet\n");
            }
        }
        else if( first == "load" )
        {
            if(parts.size())
            {
                string & plugname = parts[0];
                if(plugname == "all")
                {
                    for(size_t i = 0; i < plug_mgr->size();i++)
                    {
                        Plugin * plug = (plug_mgr->operator[](i));
                        plug->load();
                    }
                }
                else
                {
                    Plugin * plug = plug_mgr->getPluginByName(plugname);
                    if(!plug)
                    {
                        con.printerr("No such plugin\n");
                    }
                    else
                    {
                        plug->load();
                    }
                }
            }
        }
        else if( first == "reload" )
        {
            if(parts.size())
            {
                string & plugname = parts[0];
                if(plugname == "all")
                {
                    for(size_t i = 0; i < plug_mgr->size();i++)
                    {
                        Plugin * plug = (plug_mgr->operator[](i));
                        plug->reload();
                    }
                }
                else
                {
                    Plugin * plug = plug_mgr->getPluginByName(plugname);
                    if(!plug)
                    {
                        con.printerr("No such plugin\n");
                    }
                    else
                    {
                        plug->reload();
                    }
                }
            }
        }
        else if( first == "unload" )
        {
            if(parts.size())
            {
                string & plugname = parts[0];
                if(plugname == "all")
                {
                    for(size_t i = 0; i < plug_mgr->size();i++)
                    {
                        Plugin * plug = (plug_mgr->operator[](i));
                        plug->unload();
                    }
                }
                else
                {
                    Plugin * plug = plug_mgr->getPluginByName(plugname);
                    if(!plug)
                    {
                        con.printerr("No such plugin\n");
                    }
                    else
                    {
                        plug->unload();
                    }
                }
            }
        }
        else if(first == "ls" || first == "dir")
        {
            if(parts.size())
            {
                string & plugname = parts[0];
                const Plugin * plug = plug_mgr->getPluginByName(plugname);
                if(!plug)
                {
                    con.printerr("There's no plugin called %s!\n",plugname.c_str());
                }
                else for (size_t j = 0; j < plug->size();j++)
                {
                    const PluginCommand & pcmd = (plug->operator[](j));
                    if (pcmd.isHotkeyCommand())
                        con.color(Console::COLOR_CYAN);
                    con.print("  %-22s - %s\n",pcmd.name.c_str(), pcmd.description.c_str());
                    con.reset_color();
                }
            }
            else
            {
                con.print(
                "builtin:\n"
                "  help|?|man            - This text or help specific to a plugin.\n"
                "  ls [PLUGIN]           - List available commands. Optionally for single plugin.\n"
                "  cls                   - Clear the console.\n"
                "  fpause                - Force DF to pause.\n"
                "  die                   - Force DF to close immediately\n"
                "  keybinding            - Modify bindings of commands to keys\n"
                "  belongs COMMAND       - Tell which plugin a command belongs to.\n"
                "  script FILENAME       - Run the commands specified in a file.\n"
                "  plug [PLUGIN|v]       - List plugin state and detailed description.\n"
                "  load PLUGIN|all       - Load a plugin by name or load all possible plugins.\n"
                "  unload PLUGIN|all     - Unload a plugin or all loaded plugins.\n"
                "  reload PLUGIN|all     - Reload a plugin or all loaded plugins.\n"
                "\n"
                "plugins:\n"
                );
                std::set <sortable> out;
                for(size_t i = 0; i < plug_mgr->size();i++)
                {
                    const Plugin * plug = (plug_mgr->operator[](i));
                    if(!plug->size())
                        continue;
                    for (size_t j = 0; j < plug->size();j++)
                    {
                        const PluginCommand & pcmd = (plug->operator[](j));
                        out.insert(sortable(pcmd.isHotkeyCommand(),pcmd.name,pcmd.description));
                    }
                }
                for(auto iter = out.begin();iter != out.end();iter++)
                {
                    if ((*iter).recolor)
                        con.color(Console::COLOR_CYAN);
                    con.print("  %-22s- %s\n",(*iter).name.c_str(), (*iter).description.c_str());
                    con.reset_color();
                }
            }
        }
        else if(first == "plug")
        {
            for(size_t i = 0; i < plug_mgr->size();i++)
            {
                const Plugin * plug = (plug_mgr->operator[](i));
                if(!plug->size())
                    continue;
                con.print("%s\n", plug->getName().c_str());
            }
        }
        else if(first == "keybinding")
        {
            if (parts.size() >= 3 && (parts[0] == "set" || parts[0] == "add"))
            {
                std::string keystr = parts[1];
                if (parts[0] == "set")
                    core->ClearKeyBindings(keystr);
                for (int i = parts.size()-1; i >= 2; i--) 
                {
                    if (!core->AddKeyBinding(keystr, parts[i])) {
                        con.printerr("Invalid key spec: %s\n", keystr.c_str());
                        break;
                    }
                }
            }
            else if (parts.size() >= 2 && parts[0] == "clear")
            {
                for (size_t i = 1; i < parts.size(); i++)
                {
                    if (!core->ClearKeyBindings(parts[i])) {
                        con.printerr("Invalid key spec: %s\n", parts[i].c_str());
                        break;
                    }
                }
            }
            else if (parts.size() == 2 && parts[0] == "list")
            {
                std::vector<std::string> list = core->ListKeyBindings(parts[1]);
                if (list.empty())
                    con << "No bindings." << endl;
                for (size_t i = 0; i < list.size(); i++)
                    con << "  " << list[i] << endl;
            }
            else
            {
                con << "Usage:" << endl
                    << "  keybinding list <key>" << endl
                    << "  keybinding clear <key> <key>..." << endl
                    << "  keybinding set <key> \"cmdline\" \"cmdline\"..." << endl
                    << "  keybinding add <key> \"cmdline\" \"cmdline\"..." << endl
                    << "Later adds, and earlier items within one command have priority." << endl;
            }
        }
        else if(first == "fpause")
        {
            World * w = core->getWorld();
            w->SetPauseState(true);
            con.print("The game was forced to pause!");
        }
        else if(first == "cls")
        {
            con.clear();
        }
        else if(first == "die")
        {
            _exit(666);
        }
        else if(first == "script")
        {
            if(parts.size() == 1)
            {
                loadScriptFile(core, plug_mgr, parts[0]);
            }
            else
            {
                con << "Usage:" << endl
                    << "  script <filename>" << endl;
            }
        }
        else
        {
            command_result res = plug_mgr->InvokeCommand(first, parts);
            if(res == CR_NOT_IMPLEMENTED)
            {
                con.printerr("%s is not a recognized command.\n", first.c_str());
                clueless_counter ++;
            }
        }
    }
}
Пример #26
0
// Called in the plugin's thread just before the init function
static void initPluginCallback(const Plugin& plugin)
{
  string name = plugin.name();
  std::transform(name.begin(), name.end(), name.begin(), ::tolower);
  gLogService.createThreadLog(name);
}
Пример #27
0
    void WritePlugin(YAML::Emitter& out, const Plugin& plugin, const Game& game) {
        out << YAML::BeginMap;

        out << YAML::Key << "name"
            << YAML::Value << plugin.Name();

        out << YAML::Key << "isActive";
        if (game.IsActive(plugin.Name()))
            out << YAML::Value << true;
        else
            out << YAML::Value << false;

        if (plugin.Crc() != 0) {
            out << YAML::Key << "crc"
                << YAML::Value << IntToHexString(plugin.Crc());
        }

        if (!plugin.Version().empty()) {
            out << YAML::Key << "version"
                << YAML::Value << boost::locale::translate("Version").str() + ": " + plugin.Version();
        }

        std::set<Tag> tags = plugin.Tags();
        std::set<Tag> tagsAdd, tagsRemove;
        if (!tags.empty()) {
            for (std::set<Tag>::const_iterator it = tags.begin(), endit = tags.end(); it != endit; ++it) {
                if (it->IsAddition())
                    tagsAdd.insert(*it);
                else
                    tagsRemove.insert(*it);
            }
            if (!tagsAdd.empty()) {
                out << YAML::Key << "tagsAdd"
                    << YAML::Value << tagsAdd;
            }
            if (!tagsRemove.empty()) {
                out << YAML::Key << "tagsRemove"
                    << YAML::Value << tagsRemove;
            }
        }

        std::list<Message> messages = plugin.Messages();
        std::set<PluginDirtyInfo> dirtyInfo = plugin.DirtyInfo();
        for (std::set<PluginDirtyInfo>::const_iterator it = dirtyInfo.begin(), endit = dirtyInfo.end(); it != endit; ++it) {
            boost::format f;
            if (it->ITMs() > 0 && it->UDRs() > 0 && it->DeletedNavmeshes() > 0)
                f = boost::format(boost::locale::translate("Contains %1% ITM records, %2% UDR records and %3% deleted navmeshes. Clean with %4%.")) % it->ITMs() % it->UDRs() % it->DeletedNavmeshes() % it->CleaningUtility();
            else if (it->ITMs() == 0 && it->UDRs() == 0 && it->DeletedNavmeshes() == 0)
                f = boost::format(boost::locale::translate("Clean with %1%.")) % it->CleaningUtility();


            else if (it->ITMs() == 0 && it->UDRs() > 0 && it->DeletedNavmeshes() > 0)
                f = boost::format(boost::locale::translate("Contains %1% UDR records and %2% deleted navmeshes. Clean with %3%.")) % it->UDRs() % it->DeletedNavmeshes() % it->CleaningUtility();
            else if (it->ITMs() == 0 && it->UDRs() == 0 && it->DeletedNavmeshes() > 0)
                f = boost::format(boost::locale::translate("Contains %1% deleted navmeshes. Clean with %2%.")) % it->DeletedNavmeshes() % it->CleaningUtility();
            else if (it->ITMs() == 0 && it->UDRs() > 0 && it->DeletedNavmeshes() == 0)
                f = boost::format(boost::locale::translate("Contains %1% UDR records. Clean with %2%.")) % it->UDRs() % it->CleaningUtility();

            else if (it->ITMs() > 0 && it->UDRs() == 0 && it->DeletedNavmeshes() > 0)
                f = boost::format(boost::locale::translate("Contains %1% ITM records and %2% deleted navmeshes. Clean with %3%.")) % it->ITMs() % it->DeletedNavmeshes() % it->CleaningUtility();
            else if (it->ITMs() > 0 && it->UDRs() == 0 && it->DeletedNavmeshes() == 0)
                f = boost::format(boost::locale::translate("Contains %1% ITM records. Clean with %2%.")) % it->ITMs() % it->CleaningUtility();

            else if (it->ITMs() > 0 && it->UDRs() > 0 && it->DeletedNavmeshes() == 0)
                f = boost::format(boost::locale::translate("Contains %1% ITM records and %2% UDR records. Clean with %3%.")) % it->ITMs() % it->UDRs() % it->CleaningUtility();

            messages.push_back(loot::Message(loot::Message::warn, f.str()));
        }

        if (!messages.empty()) {
            out << YAML::Key << "messages"
                << YAML::Value << YAML::BeginSeq;
            for (std::list<Message>::const_iterator it = messages.begin(), endit = messages.end(); it != endit; ++it) {
                WriteMessage(out, *it);
            }
            out << YAML::EndSeq;
        }

        out << YAML::EndMap;
    }
Пример #28
0
wxArrayString VampEffectsModule::FindPlugins(PluginManagerInterface & WXUNUSED(pm))
{
   wxArrayString names;

   PluginLoader *loader = PluginLoader::getInstance();

   PluginLoader::PluginKeyList keys = loader->listPlugins();

   for (PluginLoader::PluginKeyList::iterator i = keys.begin(); i != keys.end(); ++i)
   {
      Plugin *vp = PluginLoader::getInstance()->loadPlugin(*i, 48000); // rate doesn't matter here
      if (!vp)
      {
         continue;
      }

      // We limit the listed plugin outputs to those whose results can
      // readily be displayed in an Audacity label track.
      //
      // - Any output whose features have no values (time instants only),
      //   with or without duration, is fine
      //
      // - Any output whose features have more than one value, or an
      //   unknown or variable number of values, is right out
      //
      // - Any output whose features have exactly one value, with
      //   variable sample rate or with duration, should be OK --
      //   this implies a sparse feature, of which the time and/or
      //   duration are significant aspects worth displaying
      //
      // - An output whose features have exactly one value, with
      //   fixed sample rate and no duration, cannot be usefully
      //   displayed -- the value is the only significant piece of
      //   data there and we have no good value plot

      Plugin::OutputList outputs = vp->getOutputDescriptors();

      int output = 0;

      for (Plugin::OutputList::iterator j = outputs.begin(); j != outputs.end(); ++j)
      {
         if (j->sampleType == Plugin::OutputDescriptor::FixedSampleRate ||
               j->sampleType == Plugin::OutputDescriptor::OneSamplePerStep ||
               !j->hasFixedBinCount ||
               (j->hasFixedBinCount && j->binCount > 1))
         {
            // All of these qualities disqualify (see notes above)

            ++output;
            continue;
         }

         wxString name = wxString::FromUTF8(vp->getName().c_str());

         if (outputs.size() > 1)
         {
            // This is not the plugin's only output.
            // Use "plugin name: output name" as the effect name,
            // unless the output name is the same as the plugin name
            wxString outputName = wxString::FromUTF8(j->name.c_str());
            if (outputName != name)
            {
               name = wxString::Format(wxT("%s: %s"),
                                       name.c_str(), outputName.c_str());
            }
         }

         wxString path = wxString::FromUTF8(i->c_str()) + wxT("/") + name;
         names.Add(path);

         ++output;
      }

      delete vp;
   }

   return names;
}
Пример #29
0
bool PluginManager::CanInvokeHotkey(const std::string &command, df::viewscreen *top)
{
    Plugin *plugin = getPluginByCommand(command);
    return plugin ? plugin->can_invoke_hotkey(command, top) : true;
}
Пример #30
0
Plugin *
PluginLoader::Impl::loadPlugin(PluginKey key,
                               float inputSampleRate, int adapterFlags)
{
    string libname, identifier;
    if (!decomposePluginKey(key, libname, identifier)) {
        std::cerr << "Vamp::HostExt::PluginLoader: Invalid plugin key \""
                  << key << "\" in loadPlugin" << std::endl;
        return 0;
    }
        
    string fullPath = getLibraryPathForPlugin(key);
    if (fullPath == "") return 0;
    
    void *handle = loadLibrary(fullPath);
    if (!handle) return 0;
    
    VampGetPluginDescriptorFunction fn =
        (VampGetPluginDescriptorFunction)lookupInLibrary
        (handle, "vampGetPluginDescriptor");

    if (!fn) {
        unloadLibrary(handle);
        return 0;
    }

    int index = 0;
    const VampPluginDescriptor *descriptor = 0;

    while ((descriptor = fn(VAMP_API_VERSION, index))) {

        if (string(descriptor->identifier) == identifier) {

            Vamp::PluginHostAdapter *plugin =
                new Vamp::PluginHostAdapter(descriptor, inputSampleRate);

            Plugin *adapter = new PluginDeletionNotifyAdapter(plugin, this);

            m_pluginLibraryHandleMap[adapter] = handle;

            if (adapterFlags & ADAPT_INPUT_DOMAIN) {
                if (adapter->getInputDomain() == Plugin::FrequencyDomain) {
                    adapter = new PluginInputDomainAdapter(adapter);
                }
            }

            if (adapterFlags & ADAPT_BUFFER_SIZE) {
                adapter = new PluginBufferingAdapter(adapter);
            }

            if (adapterFlags & ADAPT_CHANNEL_COUNT) {
                adapter = new PluginChannelAdapter(adapter);
            }

            return adapter;
        }

        ++index;
    }

    cerr << "Vamp::HostExt::PluginLoader: Plugin \""
         << identifier << "\" not found in library \""
         << fullPath << "\"" << endl;

    return 0;
}