void Run() { /*infostream<<"wrapDegrees(100.0) = "<<wrapDegrees(100.0)<<std::endl; infostream<<"wrapDegrees(720.5) = "<<wrapDegrees(720.5)<<std::endl; infostream<<"wrapDegrees(-0.5) = "<<wrapDegrees(-0.5)<<std::endl;*/ assert(fabs(wrapDegrees(100.0) - 100.0) < 0.001); assert(fabs(wrapDegrees(720.5) - 0.5) < 0.001); assert(fabs(wrapDegrees(-0.5) - (-0.5)) < 0.001); assert(fabs(wrapDegrees(-365.5) - (-5.5)) < 0.001); assert(lowercase("Foo bAR") == "foo bar"); assert(is_yes("YeS") == true); assert(is_yes("") == false); assert(is_yes("FAlse") == false); }
void TestUtilities::testIsYes() { UASSERT(is_yes("YeS") == true); UASSERT(is_yes("") == false); UASSERT(is_yes("FAlse") == false); UASSERT(is_yes("-1") == true); UASSERT(is_yes("0") == false); UASSERT(is_yes("1") == true); UASSERT(is_yes("2") == true); }
/* returns: 0 for success * WRONG_VALUE if node->val is none of 'yes','y','no','n' * <0 for error */ static int stack_push_if_yes(struct param_node *node, struct val_node **head, char *opt_name) { int rc; if (((rc=is_yes(node->val, 0)) == 1) || (node->flags & PARAMETER_SET)) { rc = stack_push(head, opt_name); } else if (rc == -1) rc = WRONG_VALUE; free(node->val); node->val = NULL; return rc; }
// is_yes(arg) int ModApiUtil::l_is_yes(lua_State *L) { NO_MAP_LOCK_REQUIRED; lua_getglobal(L, "tostring"); // function to be called lua_pushvalue(L, 1); // 1st argument lua_call(L, 1, 1); // execute function std::string str(lua_tostring(L, -1)); // get result lua_pop(L, 1); bool yes = is_yes(str); lua_pushboolean(L, yes); return 1; }
static int get_enable_filename_crypto(struct ecryptfs_ctx *ctx, struct param_node *node, struct val_node **head, void **foo) { int yn, rc = 0; if (((yn=is_yes(node->val, 0)) > 0) || (node->flags & PARAMETER_SET)) { int i; struct val_node *val_node; for (i = 0; i < filename_crypto_fnek_sig_param_node.num_transitions; i++) filename_crypto_fnek_sig_param_node.tl[i].next_token = node->tl[0].next_token; node->tl[0].next_token = &filename_crypto_fnek_sig_param_node; val_node = (*head); while (val_node) { if (strncmp(val_node->val, "ecryptfs_sig=", 13) == 0) { rc = asprintf(&filename_crypto_fnek_sig_param_node.suggested_val, "%s", &((char *)val_node->val)[13]); if (rc == -1) { rc = -ENOMEM; syslog(LOG_ERR, "%s: No memory whilst " "attempting to write [%s]\n", __FUNCTION__, &((char *)val_node->val)[13]); goto out_free; } rc = 0; break; } val_node = val_node->next; } } else if (node->val) { if (yn < 0) rc = WRONG_VALUE; } else /* default: no */; out_free: if (node->val) { free(node->val); node->val = NULL; } return rc; }
void logging_init(void) { pthread_mutex_init( &logging_mutex, NULL ); pthread_mutex_lock( &logging_mutex ); if( is_yes( config_get("logging.enabled") ) ) { logging_threshold = logging_name_to_value( loglevel_map, config_get("logging.log_level") ) ; logging_file_name = strdup( config_get("logging.log_file") ); logging_enabled = 1; } pthread_mutex_unlock( &logging_mutex ); }
void FontEngine::readSettings() { m_default_size[FM_Standard] = m_settings->getU16("font_size"); m_default_size[FM_Fallback] = m_settings->getU16("fallback_font_size"); m_default_size[FM_Mono] = m_settings->getU16("mono_font_size"); if (is_yes(_("needs_fallback_font"))) { m_currentMode = FM_Fallback; } else { m_currentMode = FM_Standard; } m_default_size[FM_Simple] = m_settings->getU16("font_size"); m_default_size[FM_SimpleMono] = m_settings->getU16("mono_font_size"); cleanCache(); updateFontCache(); updateSkin(); }
void FontEngine::readSettings() { #if USE_FREETYPE if (g_settings->getBool("freetype")) { m_default_size[FM_Standard] = m_settings->getU16("font_size"); m_default_size[FM_Fallback] = m_settings->getU16("fallback_font_size"); m_default_size[FM_Mono] = m_settings->getU16("mono_font_size"); if (is_yes(gettext("needs_fallback_font"))) { m_currentMode = FM_Fallback; } else { m_currentMode = FM_Standard; } } #endif m_default_size[FM_Simple] = m_settings->getU16("font_size"); m_default_size[FM_SimpleMono] = m_settings->getU16("mono_font_size"); cleanCache(); updateFontCache(); updateSkin(); }
FontEngine::FontEngine(Settings* main_settings, gui::IGUIEnvironment* env) : m_settings(main_settings), m_env(env), m_font_cache(), m_currentMode(FM_Standard), m_lastMode(), m_lastSize(0), m_lastFont(NULL) { for (unsigned int i = 0; i < FM_MaxMode; i++) { m_default_size[i] = (FontMode) FONT_SIZE_UNSPECIFIED; } assert(m_settings != NULL); // pre-condition assert(m_env != NULL); // pre-condition assert(m_env->getSkin() != NULL); // pre-condition m_currentMode = FM_Simple; #if USE_FREETYPE if (g_settings->getBool("freetype")) { m_default_size[FM_Standard] = m_settings->getU16("font_size"); m_default_size[FM_Fallback] = m_settings->getU16("fallback_font_size"); m_default_size[FM_Mono] = m_settings->getU16("mono_font_size"); if (is_yes(gettext("needs_fallback_font"))) { m_currentMode = FM_Fallback; } else { m_currentMode = FM_Standard; } } // having freetype but not using it is quite a strange case so we need to do // special handling for it if (m_currentMode == FM_Simple) { std::stringstream fontsize; fontsize << DEFAULT_FONT_SIZE; m_settings->setDefault("font_size", fontsize.str()); m_settings->setDefault("mono_font_size", fontsize.str()); } #endif m_default_size[FM_Simple] = m_settings->getU16("font_size"); m_default_size[FM_SimpleMono] = m_settings->getU16("mono_font_size"); updateSkin(); if (m_currentMode == FM_Standard) { m_settings->registerChangedCallback("font_size", font_setting_changed, NULL); m_settings->registerChangedCallback("font_path", font_setting_changed, NULL); m_settings->registerChangedCallback("font_shadow", font_setting_changed, NULL); m_settings->registerChangedCallback("font_shadow_alpha", font_setting_changed, NULL); } else if (m_currentMode == FM_Fallback) { m_settings->registerChangedCallback("fallback_font_size", font_setting_changed, NULL); m_settings->registerChangedCallback("fallback_font_path", font_setting_changed, NULL); m_settings->registerChangedCallback("fallback_font_shadow", font_setting_changed, NULL); m_settings->registerChangedCallback("fallback_font_shadow_alpha", font_setting_changed, NULL); } m_settings->registerChangedCallback("mono_font_path", font_setting_changed, NULL); m_settings->registerChangedCallback("mono_font_size", font_setting_changed, NULL); m_settings->registerChangedCallback("screen_dpi", font_setting_changed, NULL); m_settings->registerChangedCallback("gui_scaling", font_setting_changed, NULL); }
void FontEngine::initFont(unsigned int basesize, FontMode mode) { std::string font_config_prefix; if (mode == FM_Unspecified) { mode = m_currentMode; } switch (mode) { case FM_Standard: font_config_prefix = ""; break; case FM_Fallback: font_config_prefix = "fallback_"; break; case FM_Mono: font_config_prefix = "mono_"; if (m_currentMode == FM_Simple) mode = FM_SimpleMono; break; case FM_Simple: /* Fallthrough */ case FM_SimpleMono: /* Fallthrough */ default: font_config_prefix = ""; } if (m_font_cache[mode].find(basesize) != m_font_cache[mode].end()) return; if ((mode == FM_Simple) || (mode == FM_SimpleMono)) { initSimpleFont(basesize, mode); return; } #if USE_FREETYPE else { if (! is_yes(m_settings->get("freetype"))) { return; } unsigned int size = floor( porting::getDisplayDensity() * m_settings->getFloat("gui_scaling") * basesize); u32 font_shadow = 0; u32 font_shadow_alpha = 0; try { font_shadow = g_settings->getU16(font_config_prefix + "font_shadow"); } catch (SettingNotFoundException&) {} try { font_shadow_alpha = g_settings->getU16(font_config_prefix + "font_shadow_alpha"); } catch (SettingNotFoundException&) {} std::string font_path = g_settings->get(font_config_prefix + "font_path"); irr::gui::IGUIFont* font = gui::CGUITTFont::createTTFont(m_env, font_path.c_str(), size, true, true, font_shadow, font_shadow_alpha); if (font != NULL) { m_font_cache[mode][basesize] = font; } else { errorstream << "FontEngine: failed to load freetype font: " << font_path << std::endl; } } #endif }
int main(int argc, char *argv[]) { int retval = 0; /* Initialization */ log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION); log_add_output_all_levs(&main_dstream_no_stderr_log_out); log_register_thread("main"); /* Parse command line */ // List all allowed options std::map<std::string, ValueSpec> allowed_options; allowed_options.insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG, _("Show allowed options")))); allowed_options.insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG, _("Show version information")))); allowed_options.insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING, _("Load configuration from specified file")))); allowed_options.insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING, _("Set network port (UDP)")))); allowed_options.insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG, _("Disable unit tests")))); allowed_options.insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG, _("Enable unit tests")))); allowed_options.insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING, _("Same as --world (deprecated)")))); allowed_options.insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING, _("Set world path (implies local game) ('list' lists all)")))); allowed_options.insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING, _("Set world by name (implies local game)")))); allowed_options.insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG, _("Print more information to console")))); allowed_options.insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG, _("Print even more information to console")))); allowed_options.insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG, _("Print enormous amounts of information to log and console")))); allowed_options.insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING, _("Set logfile path ('' = no logging)")))); allowed_options.insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING, _("Set gameid (\"--gameid list\" prints available ones)")))); allowed_options.insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING, _("Migrate from current map backend to another (Only works when using minetestserver or with --server)")))); #ifndef SERVER allowed_options.insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG, _("Show available video modes")))); allowed_options.insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG, _("Run speed tests")))); allowed_options.insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING, _("Address to connect to. ('' = local game)")))); allowed_options.insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG, _("Enable random user input, for testing")))); allowed_options.insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG, _("Run dedicated server")))); allowed_options.insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING, _("Set player name")))); allowed_options.insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING, _("Set password")))); allowed_options.insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG, _("Disable main menu")))); #endif Settings cmd_args; bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options); if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1")) { dstream<<_("Allowed options:")<<std::endl; for(std::map<std::string, ValueSpec>::iterator i = allowed_options.begin(); i != allowed_options.end(); ++i) { std::ostringstream os1(std::ios::binary); os1<<" --"<<i->first; if(i->second.type == VALUETYPE_FLAG) {} else os1<<_(" <value>"); dstream<<padStringRight(os1.str(), 24); if(i->second.help != NULL) dstream<<i->second.help; dstream<<std::endl; } return cmd_args.getFlag("help") ? 0 : 1; } if(cmd_args.getFlag("version")) { #ifdef SERVER dstream<<"minetestserver "<<minetest_version_hash<<std::endl; #else dstream<<"Minetest "<<minetest_version_hash<<std::endl; dstream<<"Using Irrlicht "<<IRRLICHT_SDK_VERSION<<std::endl; #endif dstream<<"Build info: "<<minetest_build_info<<std::endl; return 0; } /* Low-level initialization */ // If trace is enabled, enable logging of certain things if(cmd_args.getFlag("trace")){ dstream<<_("Enabling trace level debug output")<<std::endl; log_trace_level_enabled = true; dout_con_ptr = &verbosestream; // this is somewhat old crap socket_enable_debug_output = true; // socket doesn't use log.h } // In certain cases, output info level on stderr if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") || cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests")) log_add_output(&main_stderr_log_out, LMT_INFO); // In certain cases, output verbose level on stderr if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace")) log_add_output(&main_stderr_log_out, LMT_VERBOSE); porting::signal_handler_init(); bool &kill = *porting::signal_handler_killstatus(); porting::initializePaths(); // Create user data directory fs::CreateDir(porting::path_user); infostream<<"path_share = "<<porting::path_share<<std::endl; infostream<<"path_user = "******"gameid") && cmd_args.get("gameid") == "list") { std::set<std::string> gameids = getAvailableGameIds(); for(std::set<std::string>::const_iterator i = gameids.begin(); i != gameids.end(); i++) dstream<<(*i)<<std::endl; return 0; } // List worlds if requested if(cmd_args.exists("world") && cmd_args.get("world") == "list"){ dstream<<_("Available worlds:")<<std::endl; std::vector<WorldSpec> worldspecs = getAvailableWorlds(); print_worldspecs(worldspecs, dstream); return 0; } // Print startup message infostream<<PROJECT_NAME<< " "<<_("with")<<" SER_FMT_VER_HIGHEST_READ="<<(int)SER_FMT_VER_HIGHEST_READ <<", "<<minetest_build_info <<std::endl; /* Basic initialization */ // Initialize default settings set_default_settings(g_settings); // Initialize sockets sockets_init(); atexit(sockets_cleanup); /* Read config file */ // Path of configuration file in use g_settings_path = ""; if(cmd_args.exists("config")) { bool r = g_settings->readConfigFile(cmd_args.get("config").c_str()); if(r == false) { errorstream<<"Could not read configuration from \"" <<cmd_args.get("config")<<"\""<<std::endl; return 1; } g_settings_path = cmd_args.get("config"); } else { std::vector<std::string> filenames; filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf"); // Legacy configuration file location filenames.push_back(porting::path_user + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf"); #if RUN_IN_PLACE // Try also from a lower level (to aid having the same configuration // for many RUN_IN_PLACE installs) filenames.push_back(porting::path_user + DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf"); #endif for(u32 i=0; i<filenames.size(); i++) { bool r = g_settings->readConfigFile(filenames[i].c_str()); if(r) { g_settings_path = filenames[i]; break; } } // If no path found, use the first one (menu creates the file) if(g_settings_path == "") g_settings_path = filenames[0]; } // Initialize debug streams #define DEBUGFILE "debug.txt" #if RUN_IN_PLACE std::string logfile = DEBUGFILE; #else std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE; #endif if(cmd_args.exists("logfile")) logfile = cmd_args.get("logfile"); log_remove_output(&main_dstream_no_stderr_log_out); int loglevel = g_settings->getS32("debug_log_level"); if (loglevel == 0) //no logging logfile = ""; else if (loglevel > 0 && loglevel <= LMT_NUM_VALUES) log_add_output_maxlev(&main_dstream_no_stderr_log_out, (LogMessageLevel)(loglevel - 1)); if(logfile != "") debugstreams_init(false, logfile.c_str()); else debugstreams_init(false, NULL); infostream<<"logfile = "<<logfile<<std::endl; // Initialize random seed srand(time(0)); mysrand(time(0)); // Initialize HTTP fetcher httpfetch_init(g_settings->getS32("curl_parallel_limit")); /* Run unit tests */ if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false) || cmd_args.getFlag("enable-unittests") == true) { run_tests(); } #ifdef _MSC_VER init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),g_settings->get("language"),argc,argv); #else init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),g_settings->get("language")); #endif /* Game parameters */ // Port u16 port = 30000; if(cmd_args.exists("port")) port = cmd_args.getU16("port"); else if(g_settings->exists("port")) port = g_settings->getU16("port"); if(port == 0) port = 30000; // World directory std::string commanded_world = ""; if(cmd_args.exists("world")) commanded_world = cmd_args.get("world"); else if(cmd_args.exists("map-dir")) commanded_world = cmd_args.get("map-dir"); else if(cmd_args.exists("nonopt0")) // First nameless argument commanded_world = cmd_args.get("nonopt0"); else if(g_settings->exists("map-dir")) commanded_world = g_settings->get("map-dir"); // World name std::string commanded_worldname = ""; if(cmd_args.exists("worldname")) commanded_worldname = cmd_args.get("worldname"); // Strip world.mt from commanded_world { std::string worldmt = "world.mt"; if(commanded_world.size() > worldmt.size() && commanded_world.substr(commanded_world.size()-worldmt.size()) == worldmt){ dstream<<_("Supplied world.mt file - stripping it off.")<<std::endl; commanded_world = commanded_world.substr( 0, commanded_world.size()-worldmt.size()); } } // If a world name was specified, convert it to a path if(commanded_worldname != ""){ // Get information about available worlds std::vector<WorldSpec> worldspecs = getAvailableWorlds(); bool found = false; for(u32 i=0; i<worldspecs.size(); i++){ std::string name = worldspecs[i].name; if(name == commanded_worldname){ if(commanded_world != ""){ dstream<<_("--worldname takes precedence over previously " "selected world.")<<std::endl; } commanded_world = worldspecs[i].path; found = true; break; } } if(!found){ dstream<<_("World")<<" '"<<commanded_worldname<<_("' not " "available. Available worlds:")<<std::endl; print_worldspecs(worldspecs, dstream); return 1; } } // Gamespec SubgameSpec commanded_gamespec; if(cmd_args.exists("gameid")){ std::string gameid = cmd_args.get("gameid"); commanded_gamespec = findSubgame(gameid); if(!commanded_gamespec.isValid()){ errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl; return 1; } } /* Run dedicated server if asked to or no other option */ #ifdef SERVER bool run_dedicated_server = true; #else bool run_dedicated_server = cmd_args.getFlag("server"); #endif g_settings->set("server_dedicated", run_dedicated_server ? "true" : "false"); if(run_dedicated_server) { DSTACK("Dedicated server branch"); // Create time getter if built with Irrlicht #ifndef SERVER g_timegetter = new SimpleTimeGetter(); #endif // World directory std::string world_path; verbosestream<<_("Determining world path")<<std::endl; bool is_legacy_world = false; // If a world was commanded, use it if(commanded_world != ""){ world_path = commanded_world; infostream<<"Using commanded world path ["<<world_path<<"]" <<std::endl; } // No world was specified; try to select it automatically else { // Get information about available worlds std::vector<WorldSpec> worldspecs = getAvailableWorlds(); // If a world name was specified, select it if(commanded_worldname != ""){ world_path = ""; for(u32 i=0; i<worldspecs.size(); i++){ std::string name = worldspecs[i].name; if(name == commanded_worldname){ world_path = worldspecs[i].path; break; } } if(world_path == ""){ dstream<<_("World")<<" '"<<commanded_worldname<<"' "<<_("not " "available. Available worlds:")<<std::endl; print_worldspecs(worldspecs, dstream); return 1; } } // If there is only a single world, use it if(worldspecs.size() == 1){ world_path = worldspecs[0].path; dstream<<_("Automatically selecting world at")<<" [" <<world_path<<"]"<<std::endl; // If there are multiple worlds, list them } else if(worldspecs.size() > 1){ dstream<<_("Multiple worlds are available.")<<std::endl; dstream<<_("Please select one using --worldname <name>" " or --world <path>")<<std::endl; print_worldspecs(worldspecs, dstream); return 1; // If there are no worlds, automatically create a new one } else { // This is the ultimate default world path world_path = porting::path_user + DIR_DELIM + "worlds" + DIR_DELIM + "world"; infostream<<"Creating default world at [" <<world_path<<"]"<<std::endl; } } if(world_path == ""){ errorstream<<"No world path specified or found."<<std::endl; return 1; } verbosestream<<_("Using world path")<<" ["<<world_path<<"]"<<std::endl; // We need a gamespec. SubgameSpec gamespec; verbosestream<<_("Determining gameid/gamespec")<<std::endl; // If world doesn't exist if(!getWorldExists(world_path)) { // Try to take gamespec from command line if(commanded_gamespec.isValid()){ gamespec = commanded_gamespec; infostream<<"Using commanded gameid ["<<gamespec.id<<"]"<<std::endl; } // Otherwise we will be using "minetest" else{ gamespec = findSubgame(g_settings->get("default_game")); infostream<<"Using default gameid ["<<gamespec.id<<"]"<<std::endl; } } // World exists else { std::string world_gameid = getWorldGameId(world_path, is_legacy_world); // If commanded to use a gameid, do so if(commanded_gamespec.isValid()){ gamespec = commanded_gamespec; if(commanded_gamespec.id != world_gameid){ errorstream<<"WARNING: Using commanded gameid [" <<gamespec.id<<"]"<<" instead of world gameid [" <<world_gameid<<"]"<<std::endl; } } else{ // If world contains an embedded game, use it; // Otherwise find world from local system. gamespec = findWorldSubgame(world_path); infostream<<"Using world gameid ["<<gamespec.id<<"]"<<std::endl; } } if(!gamespec.isValid()){ errorstream<<"Subgame ["<<gamespec.id<<"] could not be found." <<std::endl; return 1; } verbosestream<<_("Using gameid")<<" ["<<gamespec.id<<"]"<<std::endl; // Bind address std::string bind_str = g_settings->get("bind_address"); Address bind_addr(0,0,0,0, port); if (g_settings->getBool("ipv6_server")) { bind_addr.setAddress((IPv6AddressBytes*) NULL); } try { bind_addr.Resolve(bind_str.c_str()); } catch (ResolveError &e) { infostream << "Resolving bind address \"" << bind_str << "\" failed: " << e.what() << " -- Listening on all addresses." << std::endl; } if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) { errorstream << "Unable to listen on " << bind_addr.serializeString() << L" because IPv6 is disabled" << std::endl; return 1; } // Create server Server server(world_path, gamespec, false, bind_addr.isIPv6()); // Database migration if (cmd_args.exists("migrate")) { std::string migrate_to = cmd_args.get("migrate"); Settings world_mt; bool success = world_mt.readConfigFile((world_path + DIR_DELIM + "world.mt").c_str()); if (!success) { errorstream << "Cannot read world.mt" << std::endl; return 1; } if (!world_mt.exists("backend")) { errorstream << "Please specify your current backend in world.mt file:" << std::endl << " backend = {sqlite3|leveldb|redis|dummy}" << std::endl; return 1; } std::string backend = world_mt.get("backend"); Database *new_db; if (backend == migrate_to) { errorstream << "Cannot migrate: new backend is same as the old one" << std::endl; return 1; } if (migrate_to == "sqlite3") new_db = new Database_SQLite3(&(ServerMap&)server.getMap(), world_path); #if USE_LEVELDB else if (migrate_to == "leveldb") new_db = new Database_LevelDB(&(ServerMap&)server.getMap(), world_path); #endif #if USE_REDIS else if (migrate_to == "redis") new_db = new Database_Redis(&(ServerMap&)server.getMap(), world_path); #endif else { errorstream << "Migration to " << migrate_to << " is not supported" << std::endl; return 1; } std::list<v3s16> blocks; ServerMap &old_map = ((ServerMap&)server.getMap()); old_map.listAllLoadableBlocks(blocks); int count = 0; new_db->beginSave(); for (std::list<v3s16>::iterator i = blocks.begin(); i != blocks.end(); ++i) { MapBlock *block = old_map.loadBlock(*i); new_db->saveBlock(block); MapSector *sector = old_map.getSectorNoGenerate(v2s16(i->X, i->Z)); sector->deleteBlock(block); ++count; if (count % 500 == 0) actionstream << "Migrated " << count << " blocks " << (100.0 * count / blocks.size()) << "% completed" << std::endl; } new_db->endSave(); delete new_db; actionstream << "Successfully migrated " << count << " blocks" << std::endl; world_mt.set("backend", migrate_to); if(!world_mt.updateConfigFile((world_path + DIR_DELIM + "world.mt").c_str())) errorstream<<"Failed to update world.mt!"<<std::endl; else actionstream<<"world.mt updated"<<std::endl; return 0; } server.start(bind_addr); // Run server dedicated_server_loop(server, kill); return 0; } #ifndef SERVER // Exclude from dedicated server build /* More parameters */ std::string address = g_settings->get("address"); if(commanded_world != "") address = ""; else if(cmd_args.exists("address")) address = cmd_args.get("address"); std::string playername = g_settings->get("name"); if(cmd_args.exists("name")) playername = cmd_args.get("name"); bool skip_main_menu = cmd_args.getFlag("go"); /* Device initialization */ // Resolution selection bool fullscreen = g_settings->getBool("fullscreen"); u16 screenW = g_settings->getU16("screenW"); u16 screenH = g_settings->getU16("screenH"); // bpp, fsaa, vsync bool vsync = g_settings->getBool("vsync"); u16 bits = g_settings->getU16("fullscreen_bpp"); u16 fsaa = g_settings->getU16("fsaa"); // Determine driver video::E_DRIVER_TYPE driverType; std::string driverstring = g_settings->get("video_driver"); if(driverstring == "null") driverType = video::EDT_NULL; else if(driverstring == "software") driverType = video::EDT_SOFTWARE; else if(driverstring == "burningsvideo") driverType = video::EDT_BURNINGSVIDEO; else if(driverstring == "direct3d8") driverType = video::EDT_DIRECT3D8; else if(driverstring == "direct3d9") driverType = video::EDT_DIRECT3D9; else if(driverstring == "opengl") driverType = video::EDT_OPENGL; #ifdef _IRR_COMPILE_WITH_OGLES1_ else if(driverstring == "ogles1") driverType = video::EDT_OGLES1; #endif #ifdef _IRR_COMPILE_WITH_OGLES2_ else if(driverstring == "ogles2") driverType = video::EDT_OGLES2; #endif else { errorstream<<"WARNING: Invalid video_driver specified; defaulting " "to opengl"<<std::endl; driverType = video::EDT_OPENGL; } /* List video modes if requested */ MyEventReceiver receiver; if(cmd_args.getFlag("videomodes")){ IrrlichtDevice *nulldevice; SIrrlichtCreationParameters params = SIrrlichtCreationParameters(); params.DriverType = video::EDT_NULL; params.WindowSize = core::dimension2d<u32>(640, 480); params.Bits = 24; params.AntiAlias = fsaa; params.Fullscreen = false; params.Stencilbuffer = false; params.Vsync = vsync; params.EventReceiver = &receiver; params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu"); nulldevice = createDeviceEx(params); if(nulldevice == 0) return 1; dstream<<_("Available video modes (WxHxD):")<<std::endl; video::IVideoModeList *videomode_list = nulldevice->getVideoModeList(); if(videomode_list == 0){ nulldevice->drop(); return 1; } s32 videomode_count = videomode_list->getVideoModeCount(); core::dimension2d<u32> videomode_res; s32 videomode_depth; for (s32 i = 0; i < videomode_count; ++i){ videomode_res = videomode_list->getVideoModeResolution(i); videomode_depth = videomode_list->getVideoModeDepth(i); dstream<<videomode_res.Width<<"x"<<videomode_res.Height <<"x"<<videomode_depth<<std::endl; } dstream<<_("Active video mode (WxHxD):")<<std::endl; videomode_res = videomode_list->getDesktopResolution(); videomode_depth = videomode_list->getDesktopDepth(); dstream<<videomode_res.Width<<"x"<<videomode_res.Height <<"x"<<videomode_depth<<std::endl; nulldevice->drop(); return 0; } /* Create device and exit if creation failed */ IrrlichtDevice *device; SIrrlichtCreationParameters params = SIrrlichtCreationParameters(); params.DriverType = driverType; params.WindowSize = core::dimension2d<u32>(screenW, screenH); params.Bits = bits; params.AntiAlias = fsaa; params.Fullscreen = fullscreen; params.Stencilbuffer = false; params.Vsync = vsync; params.EventReceiver = &receiver; params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu"); device = createDeviceEx(params); if (device == 0) return 1; // could not create selected driver. /* Continue initialization */ video::IVideoDriver* driver = device->getVideoDriver(); /* This changes the minimum allowed number of vertices in a VBO. Default is 500. */ //driver->setMinHardwareBufferVertexCount(50); // Create time getter g_timegetter = new IrrlichtTimeGetter(device); // Create game callback for menus g_gamecallback = new MainGameCallback(device); /* Speed tests (done after irrlicht is loaded to get timer) */ if(cmd_args.getFlag("speedtests")) { dstream<<"Running speed tests"<<std::endl; SpeedTests(); device->drop(); return 0; } device->setResizable(true); bool random_input = g_settings->getBool("random_input") || cmd_args.getFlag("random-input"); InputHandler *input = NULL; if(random_input) { input = new RandomInputHandler(); } else { input = new RealInputHandler(device, &receiver); } scene::ISceneManager* smgr = device->getSceneManager(); guienv = device->getGUIEnvironment(); gui::IGUISkin* skin = guienv->getSkin(); std::string font_path = g_settings->get("font_path"); gui::IGUIFont *font; #if USE_FREETYPE bool use_freetype = g_settings->getBool("freetype"); if (use_freetype) { std::string fallback; if (is_yes(gettext("needs_fallback_font"))) fallback = "fallback_"; u16 font_size = g_settings->getU16(fallback + "font_size"); font_path = g_settings->get(fallback + "font_path"); u32 font_shadow = g_settings->getU16(fallback + "font_shadow"); u32 font_shadow_alpha = g_settings->getU16(fallback + "font_shadow_alpha"); font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size, true, true, font_shadow, font_shadow_alpha); } else { font = guienv->getFont(font_path.c_str()); } #else font = guienv->getFont(font_path.c_str()); #endif if(font) skin->setFont(font); else errorstream<<"WARNING: Font file was not found." " Using default font."<<std::endl; // If font was not found, this will get us one font = skin->getFont(); assert(font); u32 text_height = font->getDimension(L"Hello, world!").Height; infostream<<"text_height="<<text_height<<std::endl; //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0)); skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255)); //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0)); //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0)); skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0)); skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0)); skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50)); skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255)); #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2 // Irrlicht 1.8 input colours skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128)); skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49)); #endif // Create the menu clouds if (!g_menucloudsmgr) g_menucloudsmgr = smgr->createNewSceneManager(); if (!g_menuclouds) g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(), g_menucloudsmgr, -1, rand(), 100); g_menuclouds->update(v2f(0, 0), video::SColor(255,200,200,255)); scene::ICameraSceneNode* camera; camera = g_menucloudsmgr->addCameraSceneNode(0, v3f(0,0,0), v3f(0, 60, 100)); camera->setFarValue(10000); /* GUI stuff */ ChatBackend chat_backend; /* If an error occurs, this is set to something and the menu-game loop is restarted. It is then displayed before the menu. */ std::wstring error_message = L""; // The password entered during the menu screen, std::string password; bool first_loop = true; /* Menu-game loop */ while(device->run() && kill == false) { // Set the window caption wchar_t* text = wgettext("Main Menu"); device->setWindowCaption((std::wstring(L"Minetest [")+text+L"]").c_str()); delete[] text; // This is used for catching disconnects try { /* Clear everything from the GUIEnvironment */ guienv->clear(); /* We need some kind of a root node to be able to add custom gui elements directly on the screen. Otherwise they won't be automatically drawn. */ guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000)); SubgameSpec gamespec; WorldSpec worldspec; bool simple_singleplayer_mode = false; // These are set up based on the menu and other things std::string current_playername = "inv£lid"; std::string current_password = ""; std::string current_address = "does-not-exist"; int current_port = 0; /* Out-of-game menu loop. Loop quits when menu returns proper parameters. */ while(kill == false) { // If skip_main_menu, only go through here once if(skip_main_menu && !first_loop){ kill = true; break; } first_loop = false; // Cursor can be non-visible when coming from the game device->getCursorControl()->setVisible(true); // Some stuff are left to scene manager when coming from the game // (map at least?) smgr->clear(); // Initialize menu data MainMenuData menudata; menudata.address = address; menudata.name = playername; menudata.port = itos(port); menudata.errormessage = wide_to_narrow(error_message); error_message = L""; if(cmd_args.exists("password")) menudata.password = cmd_args.get("password"); driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map")); menudata.enable_public = g_settings->getBool("server_announce"); std::vector<WorldSpec> worldspecs = getAvailableWorlds(); // If a world was commanded, append and select it if(commanded_world != ""){ std::string gameid = getWorldGameId(commanded_world, true); std::string name = _("[--world parameter]"); if(gameid == ""){ gameid = g_settings->get("default_game"); name += " [new]"; } //TODO find within worldspecs and set config } if(skip_main_menu == false) { video::IVideoDriver* driver = device->getVideoDriver(); infostream<<"Waiting for other menus"<<std::endl; while(device->run() && kill == false) { if(noMenuActive()) break; driver->beginScene(true, true, video::SColor(255,128,128,128)); guienv->drawAll(); driver->endScene(); // On some computers framerate doesn't seem to be // automatically limited sleep_ms(25); } infostream<<"Waited for other menus"<<std::endl; GUIEngine* temp = new GUIEngine(device, guiroot, &g_menumgr,smgr,&menudata,kill); delete temp; //once finished you'll never end up here smgr->clear(); } if(menudata.errormessage != ""){ error_message = narrow_to_wide(menudata.errormessage); continue; } //update worldspecs (necessary as new world may have been created) worldspecs = getAvailableWorlds(); if (menudata.name == "") menudata.name = std::string("Guest") + itos(myrand_range(1000,9999)); else playername = menudata.name; password = translatePassword(playername, narrow_to_wide(menudata.password)); //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl; address = menudata.address; int newport = stoi(menudata.port); if(newport != 0) port = newport; simple_singleplayer_mode = menudata.simple_singleplayer_mode; // Save settings g_settings->set("name", playername); if((menudata.selected_world >= 0) && (menudata.selected_world < (int)worldspecs.size())) g_settings->set("selected_world_path", worldspecs[menudata.selected_world].path); // Break out of menu-game loop to shut down cleanly if(device->run() == false || kill == true) break; current_playername = playername; current_password = password; current_address = address; current_port = port; // If using simple singleplayer mode, override if(simple_singleplayer_mode){ current_playername = "singleplayer"; current_password = ""; current_address = ""; current_port = myrand_range(49152, 65535); } else if (address != "") { ServerListSpec server; server["name"] = menudata.servername; server["address"] = menudata.address; server["port"] = menudata.port; server["description"] = menudata.serverdescription; ServerList::insert(server); } // Set world path to selected one if ((menudata.selected_world >= 0) && (menudata.selected_world < (int)worldspecs.size())) { worldspec = worldspecs[menudata.selected_world]; infostream<<"Selected world: "<<worldspec.name <<" ["<<worldspec.path<<"]"<<std::endl; } // If local game if(current_address == "") { if(menudata.selected_world == -1){ error_message = wgettext("No world selected and no address " "provided. Nothing to do."); errorstream<<wide_to_narrow(error_message)<<std::endl; continue; } // Load gamespec for required game gamespec = findWorldSubgame(worldspec.path); if(!gamespec.isValid() && !commanded_gamespec.isValid()){ error_message = wgettext("Could not find or load game \"") + narrow_to_wide(worldspec.gameid) + L"\""; errorstream<<wide_to_narrow(error_message)<<std::endl; continue; } if(commanded_gamespec.isValid() && commanded_gamespec.id != worldspec.gameid){ errorstream<<"WARNING: Overriding gamespec from \"" <<worldspec.gameid<<"\" to \"" <<commanded_gamespec.id<<"\""<<std::endl; gamespec = commanded_gamespec; } if(!gamespec.isValid()){ error_message = wgettext("Invalid gamespec."); error_message += L" (world_gameid=" +narrow_to_wide(worldspec.gameid)+L")"; errorstream<<wide_to_narrow(error_message)<<std::endl; continue; } } // Continue to game break; } // Break out of menu-game loop to shut down cleanly if(device->run() == false || kill == true) { if(g_settings_path != "") { g_settings->updateConfigFile( g_settings_path.c_str()); } break; } /* Run game */ the_game( kill, random_input, input, device, font, worldspec.path, current_playername, current_password, current_address, current_port, error_message, chat_backend, gamespec, simple_singleplayer_mode ); smgr->clear(); } //try catch(con::PeerNotFoundException &e) { error_message = wgettext("Connection error (timed out?)"); errorstream<<wide_to_narrow(error_message)<<std::endl; } #ifdef NDEBUG catch(std::exception &e) { std::string narrow_message = "Some exception: \""; narrow_message += e.what(); narrow_message += "\""; errorstream<<narrow_message<<std::endl; error_message = narrow_to_wide(narrow_message); } #endif // If no main menu, show error and exit if(skip_main_menu) { if(error_message != L""){ verbosestream<<"error_message = " <<wide_to_narrow(error_message)<<std::endl; retval = 1; } break; } } // Menu-game loop g_menuclouds->drop(); g_menucloudsmgr->drop(); delete input; /* In the end, delete the Irrlicht device. */ device->drop(); #if USE_FREETYPE if (use_freetype) font->drop(); #endif #endif // !SERVER // Update configuration file if(g_settings_path != "") g_settings->updateConfigFile(g_settings_path.c_str()); // Print modified quicktune values { bool header_printed = false; std::vector<std::string> names = getQuicktuneNames(); for(u32 i=0; i<names.size(); i++){ QuicktuneValue val = getQuicktuneValue(names[i]); if(!val.modified) continue; if(!header_printed){ dstream<<"Modified quicktune values:"<<std::endl; header_printed = true; } dstream<<names[i]<<" = "<<val.getString()<<std::endl; } } // Stop httpfetch thread (if started) httpfetch_cleanup(); END_DEBUG_EXCEPTION_HANDLER(errorstream) debugstreams_deinit(); return retval; }
static int load_config_file(DaemonConfig *c) { int r = -1; AvahiIniFile *f; AvahiIniFileGroup *g; assert(c); if (!(f = avahi_ini_file_load(c->config_file ? c->config_file : AVAHI_CONFIG_FILE))) goto finish; for (g = f->groups; g; g = g->groups_next) { if (strcasecmp(g->name, "server") == 0) { AvahiIniFilePair *p; for (p = g->pairs; p; p = p->pairs_next) { if (strcasecmp(p->key, "host-name") == 0) { avahi_free(c->server_config.host_name); c->server_config.host_name = avahi_strdup(p->value); } else if (strcasecmp(p->key, "domain-name") == 0) { avahi_free(c->server_config.domain_name); c->server_config.domain_name = avahi_strdup(p->value); } else if (strcasecmp(p->key, "browse-domains") == 0) { char **e, **t; e = avahi_split_csv(p->value); for (t = e; *t; t++) { char cleaned[AVAHI_DOMAIN_NAME_MAX]; if (!avahi_normalize_name(*t, cleaned, sizeof(cleaned))) { avahi_log_error("Invalid domain name \"%s\" for key \"%s\" in group \"%s\"\n", *t, p->key, g->name); avahi_strfreev(e); goto finish; } c->server_config.browse_domains = avahi_string_list_add(c->server_config.browse_domains, cleaned); } avahi_strfreev(e); c->server_config.browse_domains = filter_duplicate_domains(c->server_config.browse_domains); } else if (strcasecmp(p->key, "use-ipv4") == 0) c->server_config.use_ipv4 = is_yes(p->value); else if (strcasecmp(p->key, "use-ipv6") == 0) c->server_config.use_ipv6 = is_yes(p->value); else if (strcasecmp(p->key, "check-response-ttl") == 0) c->server_config.check_response_ttl = is_yes(p->value); else if (strcasecmp(p->key, "allow-point-to-point") == 0) c->server_config.allow_point_to_point = is_yes(p->value); else if (strcasecmp(p->key, "use-iff-running") == 0) c->server_config.use_iff_running = is_yes(p->value); else if (strcasecmp(p->key, "disallow-other-stacks") == 0) c->server_config.disallow_other_stacks = is_yes(p->value); else if (strcasecmp(p->key, "host-name-from-machine-id") == 0) { if (*(p->value) == 'y' || *(p->value) == 'Y') { char *machine_id = get_machine_id(); if (machine_id != NULL) { avahi_free(c->server_config.host_name); c->server_config.host_name = machine_id; } } } #ifdef HAVE_DBUS else if (strcasecmp(p->key, "enable-dbus") == 0) { if (*(p->value) == 'w' || *(p->value) == 'W') { c->fail_on_missing_dbus = 0; c->enable_dbus = 1; } else if (*(p->value) == 'y' || *(p->value) == 'Y') { c->fail_on_missing_dbus = 1; c->enable_dbus = 1; } else { c->enable_dbus = 0; } } #endif else if (strcasecmp(p->key, "allow-interfaces") == 0) { char **e, **t; avahi_string_list_free(c->server_config.allow_interfaces); c->server_config.allow_interfaces = NULL; e = avahi_split_csv(p->value); for (t = e; *t; t++) c->server_config.allow_interfaces = avahi_string_list_add(c->server_config.allow_interfaces, *t); avahi_strfreev(e); } else if (strcasecmp(p->key, "deny-interfaces") == 0) { char **e, **t; avahi_string_list_free(c->server_config.deny_interfaces); c->server_config.deny_interfaces = NULL; e = avahi_split_csv(p->value); for (t = e; *t; t++) c->server_config.deny_interfaces = avahi_string_list_add(c->server_config.deny_interfaces, *t); avahi_strfreev(e); } else if (strcasecmp(p->key, "ratelimit-interval-usec") == 0) { AvahiUsec k; if (parse_usec(p->value, &k) < 0) { avahi_log_error("Invalid ratelimit-interval-usec setting %s", p->value); goto finish; } c->server_config.ratelimit_interval = k; } else if (strcasecmp(p->key, "ratelimit-burst") == 0) { unsigned k; if (parse_unsigned(p->value, &k) < 0) { avahi_log_error("Invalid ratelimit-burst setting %s", p->value); goto finish; } c->server_config.ratelimit_burst = k; } else if (strcasecmp(p->key, "cache-entries-max") == 0) { unsigned k; if (parse_unsigned(p->value, &k) < 0) { avahi_log_error("Invalid cache-entries-max setting %s", p->value); goto finish; } c->server_config.n_cache_entries_max = k; #ifdef HAVE_DBUS } else if (strcasecmp(p->key, "clients-max") == 0) { unsigned k; if (parse_unsigned(p->value, &k) < 0) { avahi_log_error("Invalid clients-max setting %s", p->value); goto finish; } c->n_clients_max = k; } else if (strcasecmp(p->key, "objects-per-client-max") == 0) { unsigned k; if (parse_unsigned(p->value, &k) < 0) { avahi_log_error("Invalid objects-per-client-max setting %s", p->value); goto finish; } c->n_objects_per_client_max = k; } else if (strcasecmp(p->key, "entries-per-entry-group-max") == 0) { unsigned k; if (parse_unsigned(p->value, &k) < 0) { avahi_log_error("Invalid entries-per-entry-group-max setting %s", p->value); goto finish; } c->n_entries_per_entry_group_max = k; #endif } else { avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name); goto finish; } } } else if (strcasecmp(g->name, "publish") == 0) { AvahiIniFilePair *p; for (p = g->pairs; p; p = p->pairs_next) { if (strcasecmp(p->key, "publish-addresses") == 0) c->server_config.publish_addresses = is_yes(p->value); else if (strcasecmp(p->key, "publish-hinfo") == 0) c->server_config.publish_hinfo = is_yes(p->value); else if (strcasecmp(p->key, "publish-workstation") == 0) c->server_config.publish_workstation = is_yes(p->value); else if (strcasecmp(p->key, "publish-domain") == 0) c->server_config.publish_domain = is_yes(p->value); else if (strcasecmp(p->key, "publish-resolv-conf-dns-servers") == 0) c->publish_resolv_conf = is_yes(p->value); else if (strcasecmp(p->key, "disable-publishing") == 0) c->server_config.disable_publishing = is_yes(p->value); else if (strcasecmp(p->key, "disable-user-service-publishing") == 0) c->disable_user_service_publishing = is_yes(p->value); else if (strcasecmp(p->key, "add-service-cookie") == 0) c->server_config.add_service_cookie = is_yes(p->value); else if (strcasecmp(p->key, "publish-dns-servers") == 0) { avahi_strfreev(c->publish_dns_servers); c->publish_dns_servers = avahi_split_csv(p->value); } else if (strcasecmp(p->key, "publish-a-on-ipv6") == 0) c->server_config.publish_a_on_ipv6 = is_yes(p->value); else if (strcasecmp(p->key, "publish-aaaa-on-ipv4") == 0) c->server_config.publish_aaaa_on_ipv4 = is_yes(p->value); else { avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name); goto finish; } } } else if (strcasecmp(g->name, "wide-area") == 0) { AvahiIniFilePair *p; for (p = g->pairs; p; p = p->pairs_next) { if (strcasecmp(p->key, "enable-wide-area") == 0) c->server_config.enable_wide_area = is_yes(p->value); else { avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name); goto finish; } } } else if (strcasecmp(g->name, "reflector") == 0) { AvahiIniFilePair *p; for (p = g->pairs; p; p = p->pairs_next) { if (strcasecmp(p->key, "enable-reflector") == 0) c->server_config.enable_reflector = is_yes(p->value); else if (strcasecmp(p->key, "reflect-ipv") == 0) c->server_config.reflect_ipv = is_yes(p->value); else { avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name); goto finish; } } } else if (strcasecmp(g->name, "rlimits") == 0) { AvahiIniFilePair *p; for (p = g->pairs; p; p = p->pairs_next) { if (strcasecmp(p->key, "rlimit-as") == 0) { c->rlimit_as_set = 1; c->rlimit_as = atoi(p->value); } else if (strcasecmp(p->key, "rlimit-core") == 0) { c->rlimit_core_set = 1; c->rlimit_core = atoi(p->value); } else if (strcasecmp(p->key, "rlimit-data") == 0) { c->rlimit_data_set = 1; c->rlimit_data = atoi(p->value); } else if (strcasecmp(p->key, "rlimit-fsize") == 0) { c->rlimit_fsize_set = 1; c->rlimit_fsize = atoi(p->value); } else if (strcasecmp(p->key, "rlimit-nofile") == 0) { c->rlimit_nofile_set = 1; c->rlimit_nofile = atoi(p->value); } else if (strcasecmp(p->key, "rlimit-stack") == 0) { c->rlimit_stack_set = 1; c->rlimit_stack = atoi(p->value); } else if (strcasecmp(p->key, "rlimit-nproc") == 0) { #ifdef RLIMIT_NPROC c->rlimit_nproc_set = 1; c->rlimit_nproc = atoi(p->value); #else avahi_log_error("Ignoring configuration key \"%s\" in group \"%s\"\n", p->key, g->name); #endif } else { avahi_log_error("Invalid configuration key \"%s\" in group \"%s\"\n", p->key, g->name); goto finish; } } } else { avahi_log_error("Invalid configuration file group \"%s\".\n", g->name); goto finish; } } r = 0; finish: if (f) avahi_ini_file_free(f); return r; }
void GUITable::setTable(const TableOptions &options, const TableColumns &columns, std::vector<std::string> &content) { clear(); // Naming conventions: // i is always a row index, 0-based // j is always a column index, 0-based // k is another index, for example an option index // Handle a stupid error case... (issue #1187) if (columns.empty()) { TableColumn text_column; text_column.type = "text"; TableColumns new_columns; new_columns.push_back(text_column); setTable(options, new_columns, content); return; } // Handle table options video::SColor default_color(255, 255, 255, 255); s32 opendepth = 0; for (size_t k = 0; k < options.size(); ++k) { const std::string &name = options[k].name; const std::string &value = options[k].value; if (name == "color") parseColorString(value, m_color, false); else if (name == "background") parseColorString(value, m_background, false); else if (name == "border") m_border = is_yes(value); else if (name == "highlight") parseColorString(value, m_highlight, false); else if (name == "highlight_text") parseColorString(value, m_highlight_text, false); else if (name == "opendepth") opendepth = stoi(value); else errorstream<<"Invalid table option: \""<<name<<"\"" <<" (value=\""<<value<<"\")"<<std::endl; } // Get number of columns and rows // note: error case columns.size() == 0 was handled above s32 colcount = columns.size(); assert(colcount >= 1); // rowcount = ceil(cellcount / colcount) but use integer arithmetic s32 rowcount = (content.size() + colcount - 1) / colcount; assert(rowcount >= 0); // Append empty strings to content if there is an incomplete row s32 cellcount = rowcount * colcount; while (content.size() < (u32) cellcount) content.push_back(""); // Create temporary rows (for processing columns) struct TempRow { // Current horizontal position (may different between rows due // to indent/tree columns, or text/image columns with width<0) s32 x; // Tree indentation level s32 indent; // Next cell: Index into m_strings or m_images s32 content_index; // Next cell: Width in pixels s32 content_width; // Vector of completed cells in this row std::vector<Cell> cells; // Stores colors and how long they last (maximum column index) std::vector<std::pair<video::SColor, s32> > colors; TempRow(): x(0), indent(0), content_index(0), content_width(0) {} }; TempRow *rows = new TempRow[rowcount]; // Get em width. Pedantically speaking, the width of "M" is not // necessarily the same as the em width, but whatever, close enough. s32 em = 6; if (m_font) em = m_font->getDimension(L"M").Width; s32 default_tooltip_index = allocString(""); std::map<s32, s32> active_image_indices; // Process content in column-major order for (s32 j = 0; j < colcount; ++j) { // Check column type ColumnType columntype = COLUMN_TYPE_TEXT; if (columns[j].type == "text") columntype = COLUMN_TYPE_TEXT; else if (columns[j].type == "image") columntype = COLUMN_TYPE_IMAGE; else if (columns[j].type == "color") columntype = COLUMN_TYPE_COLOR; else if (columns[j].type == "indent") columntype = COLUMN_TYPE_INDENT; else if (columns[j].type == "tree") columntype = COLUMN_TYPE_TREE; else errorstream<<"Invalid table column type: \"" <<columns[j].type<<"\""<<std::endl; // Process column options s32 padding = myround(0.5 * em); s32 tooltip_index = default_tooltip_index; s32 align = 0; s32 width = 0; s32 span = colcount; if (columntype == COLUMN_TYPE_INDENT) { padding = 0; // default indent padding } if (columntype == COLUMN_TYPE_INDENT || columntype == COLUMN_TYPE_TREE) { width = myround(em * 1.5); // default indent width } for (size_t k = 0; k < columns[j].options.size(); ++k) { const std::string &name = columns[j].options[k].name; const std::string &value = columns[j].options[k].value; if (name == "padding") padding = myround(stof(value) * em); else if (name == "tooltip") tooltip_index = allocString(value); else if (name == "align" && value == "left") align = 0; else if (name == "align" && value == "center") align = 1; else if (name == "align" && value == "right") align = 2; else if (name == "align" && value == "inline") align = 3; else if (name == "width") width = myround(stof(value) * em); else if (name == "span" && columntype == COLUMN_TYPE_COLOR) span = stoi(value); else if (columntype == COLUMN_TYPE_IMAGE && !name.empty() && string_allowed(name, "0123456789")) { s32 content_index = allocImage(value); active_image_indices.insert(std::make_pair( stoi(name), content_index)); } else { errorstream<<"Invalid table column option: \""<<name<<"\"" <<" (value=\""<<value<<"\")"<<std::endl; } } // If current column type can use information from "color" columns, // find out which of those is currently active if (columntype == COLUMN_TYPE_TEXT) { for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; while (!row->colors.empty() && row->colors.back().second < j) row->colors.pop_back(); } } // Make template for new cells Cell newcell; memset(&newcell, 0, sizeof newcell); newcell.content_type = columntype; newcell.tooltip_index = tooltip_index; newcell.reported_column = j+1; if (columntype == COLUMN_TYPE_TEXT) { // Find right edge of column s32 xmax = 0; for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; row->content_index = allocString(content[i * colcount + j]); const core::stringw &text = m_strings[row->content_index]; row->content_width = m_font ? m_font->getDimension(text.c_str()).Width : 0; row->content_width = MYMAX(row->content_width, width); s32 row_xmax = row->x + padding + row->content_width; xmax = MYMAX(xmax, row_xmax); } // Add a new cell (of text type) to each row for (s32 i = 0; i < rowcount; ++i) { newcell.xmin = rows[i].x + padding; alignContent(&newcell, xmax, rows[i].content_width, align); newcell.content_index = rows[i].content_index; newcell.color_defined = !rows[i].colors.empty(); if (newcell.color_defined) newcell.color = rows[i].colors.back().first; rows[i].cells.push_back(newcell); rows[i].x = newcell.xmax; } } else if (columntype == COLUMN_TYPE_IMAGE) { // Find right edge of column s32 xmax = 0; for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; row->content_index = -1; // Find content_index. Image indices are defined in // column options so check active_image_indices. s32 image_index = stoi(content[i * colcount + j]); std::map<s32, s32>::iterator image_iter = active_image_indices.find(image_index); if (image_iter != active_image_indices.end()) row->content_index = image_iter->second; // Get texture object (might be NULL) video::ITexture *image = NULL; if (row->content_index >= 0) image = m_images[row->content_index]; // Get content width and update xmax row->content_width = image ? image->getOriginalSize().Width : 0; row->content_width = MYMAX(row->content_width, width); s32 row_xmax = row->x + padding + row->content_width; xmax = MYMAX(xmax, row_xmax); } // Add a new cell (of image type) to each row for (s32 i = 0; i < rowcount; ++i) { newcell.xmin = rows[i].x + padding; alignContent(&newcell, xmax, rows[i].content_width, align); newcell.content_index = rows[i].content_index; rows[i].cells.push_back(newcell); rows[i].x = newcell.xmax; } active_image_indices.clear(); } else if (columntype == COLUMN_TYPE_COLOR) { for (s32 i = 0; i < rowcount; ++i) { video::SColor cellcolor(255, 255, 255, 255); if (parseColorString(content[i * colcount + j], cellcolor, true)) rows[i].colors.push_back(std::make_pair(cellcolor, j+span)); } } else if (columntype == COLUMN_TYPE_INDENT || columntype == COLUMN_TYPE_TREE) { // For column type "tree", reserve additional space for +/- // Also enable special processing for treeview-type tables s32 content_width = 0; if (columntype == COLUMN_TYPE_TREE) { content_width = m_font ? m_font->getDimension(L"+").Width : 0; m_has_tree_column = true; } // Add a new cell (of indent or tree type) to each row for (s32 i = 0; i < rowcount; ++i) { TempRow *row = &rows[i]; s32 indentlevel = stoi(content[i * colcount + j]); indentlevel = MYMAX(indentlevel, 0); if (columntype == COLUMN_TYPE_TREE) row->indent = indentlevel; newcell.xmin = row->x + padding; newcell.xpos = newcell.xmin + indentlevel * width; newcell.xmax = newcell.xpos + content_width; newcell.content_index = 0; newcell.color_defined = !rows[i].colors.empty(); if (newcell.color_defined) newcell.color = rows[i].colors.back().first; row->cells.push_back(newcell); row->x = newcell.xmax; } } } // Copy temporary rows to not so temporary rows if (rowcount >= 1) { m_rows.resize(rowcount); for (s32 i = 0; i < rowcount; ++i) { Row *row = &m_rows[i]; row->cellcount = rows[i].cells.size(); row->cells = new Cell[row->cellcount]; memcpy((void*) row->cells, (void*) &rows[i].cells[0], row->cellcount * sizeof(Cell)); row->indent = rows[i].indent; row->visible_index = i; m_visible_rows.push_back(i); } } if (m_has_tree_column) { // Treeview: convert tree to indent cells on leaf rows for (s32 i = 0; i < rowcount; ++i) { if (i == rowcount-1 || m_rows[i].indent >= m_rows[i+1].indent) for (s32 j = 0; j < m_rows[i].cellcount; ++j) if (m_rows[i].cells[j].content_type == COLUMN_TYPE_TREE) m_rows[i].cells[j].content_type = COLUMN_TYPE_INDENT; } // Treeview: close rows according to opendepth option std::set<s32> opened_trees; for (s32 i = 0; i < rowcount; ++i) if (m_rows[i].indent < opendepth) opened_trees.insert(i); setOpenedTrees(opened_trees); } // Delete temporary information used only during setTable() delete[] rows; allocationComplete(); // Clamp scroll bar position updateScrollBar(); }
bool Settings::getBool(const std::string &name) const { return is_yes(get(name)); }
void remote_connect_init( void ) { dns_service_t *found_service = NULL; char *remote_service_name = NULL; char *client_name = NULL; net_response_t *response = NULL; net_ctx_t *ctx; int use_ipv4, use_ipv6; uint32_t initiator = 0, ssrc = 0; char *p1 = NULL; char *p2 = NULL; int remote_port_number = 0; if( ! config_is_set( "remote.connect" ) ) { logging_printf(LOGGING_WARN, "remote_connect_init: Called with no remote.connect value\n"); return; } remote_service_name = (char *) strdup( config_string_get("remote.connect") ); logging_printf(LOGGING_DEBUG, "remote_connect_init: Looking for [%s]\n", remote_service_name); p1 = remote_service_name; p2 = p1 + strlen( remote_service_name ); /* Work backwards to find a colon ':' */ /* If a ']' character is found first, we'll assume this is going to be an direct connect address */ while( p2 > p1 ) { if( *p2 == ']' ) break; if( *p2 == ':' ) break; p2--; } /* If no colon ':' or ']' was found, we'll assume this is a service name to be located */ if( p2 == p1 ) { use_ipv4 = is_yes( config_string_get("service.ipv4") ) ; use_ipv6 = is_yes( config_string_get("service.ipv6") ) ; if( dns_discover_services( use_ipv4, use_ipv6 ) <= 0 ) { logging_printf(LOGGING_WARN, "remote_connect_init: No services available\n"); free( remote_service_name ); return; } found_service = dns_discover_by_name( remote_service_name ); goto make_remote_connection; } else { /* If there is a colon ':', split the string to determine the port number */ if( *p2 == ':' ) { *p2='\0'; p2++; remote_port_number = atoi( p2 ); p2 = remote_service_name + strlen( remote_service_name ) - 1; } /* If there is a ']', work forwards from the start of the string to remove the '[' */ if ( *p2 == ']' ) { *p2='\0'; while( p1 < p2 ) { if( *p1 == '[' ) break; p1++; } } if( p1 == p2 ) { p1 = remote_service_name; } else { *p1='\0'; p1++; } if( remote_port_number == 0 ) { logging_printf( LOGGING_ERROR, "remote_connect_init: No port number specified\n"); free( remote_service_name ); return; } logging_printf( LOGGING_DEBUG, "remote_connect_init: connect_string=>%s<\n", config_string_get("remote.connect") ); logging_printf( LOGGING_DEBUG, "remote_connect_init: connect_address=>%s<, connect_port=%d\n", p1, remote_port_number ); dns_discover_add( config_string_get("remote.connect"), p1, remote_port_number ); found_service = dns_discover_by_name( config_string_get("remote.connect") ); } make_remote_connection: free( remote_service_name ); if( ! found_service ) { logging_printf(LOGGING_WARN, "remote_connect_init: No service found: %s\n", remote_service_name ); return; } logging_printf( LOGGING_DEBUG, "remote_connect_init: Found name=\"%s\" address=[%s]:%d\n", found_service->name, found_service->ip_address, found_service->port); ssrc = random_number(); initiator = random_number(); client_name = config_string_get("service.name"); if( !client_name ) { client_name = "RaveloxMIDIClient"; } response = net_response_inv( ssrc, initiator, client_name ); if( response ) { ctx = net_ctx_register( ssrc, initiator, found_service->ip_address, found_service->port, found_service->name ); if( ! ctx ) { logging_printf( LOGGING_ERROR, "remote_connect_init: Unable to create socket context\n"); } else { ctx->send_ssrc = ssrc; ctx->status = NET_CTX_STATUS_FIRST_INV; logging_printf( LOGGING_DEBUG, "remote_connect_init: Sending INV request to [%s]:%d\n", ctx->ip_address, ctx->control_port ); net_ctx_send( ctx, response->buffer, response->len , USE_CONTROL_PORT ); } } net_response_destroy( &response ); }
int client::upload() { char file_name[BUFFSIZE] = {0}; if(m_cmd.size() < 2) { do { cout << "file name: "; cout.flush(); cin.getline(file_name, BUFFSIZE - 1); }while(file_name[0] == '\0'); } else { strncpy(file_name, m_cmd[1], BUFFSIZE); } // Check file's existance in local. if(-1 == access(file_name, F_OK) ) { cout << "no such file" << endl; return -1; } int res = 0; if( -1 == send_file_info(file_name) ) { ;// Send info error. } char pack_type = acceptable(); if( is_pack_type(PT_FEXIST, pack_type) ) { while( 1 ) { char choice[BUFFSIZE] = {0}; cout << "file exist in remote, " << "do you want to cover it ? [yes | no]" << " >> "; cout.flush(); cin.getline(choice, BUFFSIZE - 1); // Default choice is "yes". if('\0' == choice[0]) { strcpy(choice, "yes"); } if( is_no(choice) ) { reply(PT_NOCOVER); return 0; } else if( is_yes(choice) ) { reply(PT_COVER); break; } else { cout << "input error" << endl; } } } res = send_file(file_name); return res; }