Beispiel #1
0
int main(int argc, char *argv[]) {
	
	// First check for special commands
	if (argc >= 2) {
		if (argv[1] == std::string("--help")) {
			printHelpMessage(std::cout, true);
			exit(EXIT_SUCCESS);
		}
	}
	
	// Enter interactive mode if less than one argument is provided
	//  (the first argument is the name of the command)
	if (argc <= 1) {
		interactiveMode();
	}
	else {
		
		// Join all arguments, ignoring spaces
		// EDIT: Ignore the first argument. Is value is 'bin/eval-test'
		std::string input = "";
		for (int i = 1; i < argc; i++) {
			input += argv[i];
		}
		
		commandLineMode(input);
	}
}
void processArgs(int numInputArgs, char *strings[]){
    if(numInputArgs < 2){
        printUsage(strings[0]);
    }
    int curLength = 0, i = 0, j = 0;
    // TODO - check for unknown arguments

    for(i = 0; i < numInputArgs; i++){
        if(strings[i][0] == '-'){
            curLength = strlen(strings[i]);
            for(j = 0; j < sizeof(simpleArgs) / sizeof(char); j++){
                if(findInString(simpleArgs[j], strings[i], strlen(strings[i])) > 0){
                    if(simpleArgs[j] == 'h'){
                        printHelpMessage(strings[0]);
                    }
                    mapper.setSimpleArg(simpleArgs[j], true);
                } else if(!mapper.getSimpleArg(simpleArgs[j])){  // don't unset
                    mapper.setSimpleArg(simpleArgs[j], false);
                }
            }
            for(j = 0; j < sizeof(compoundArgs) / sizeof(char); j++){
                // disallow compound args in clusters
                if(findInString(compoundArgs[j], strings[i], strlen(strings[i])) != -1){
                    if(curLength > 2 || i+1 == numInputArgs){
                        printUsage(strings[0]);
                    } else {
                        mapper.setCompoundArg(compoundArgs[j], strings[i+1]);
                    }
                }
            }
        }
    }
}
Beispiel #3
0
int main(int argc, char *argv[]){
  if(argc <= 1){
    printHelpMessage();
    return 0;
  }

  if(!strcmp(argv[1], "add") && argc == 4){
    addNewSource(argv[2], argv[3]);
  }

  return 0;
}
Beispiel #4
0
int main(int argc, char **argv) {

  if (argc < 2) {
    printHelpMessage();
    return -1;
  }

  MP4Container_t *container = new_mp4_container(argv[1]);

  AVCCAtom_t *avc = get_video_info(container);
  if (avc == NULL) {
    printf("FAILED: Didn't find the avcC atom\n");
    return -1;
  }

  printf("\n avcC atom @ %d - length: %d", avc->position, avc->length);
  print_buffer_data(avc->bytes, avc->size);
  printf("\n");

  for (size_t i = 0; i < avc->number_of_sps_nalus; i++) {
    SPS_t *sps = avc->sps_array[i];
    printf(" SPS #%ld - size: %d", i + 1, sps->size);
    print_buffer_data(sps->bytes, sps->size);
    printf("\n");
  }

  for (size_t i = 0; i < avc->number_of_pps_nalus; i++) {
    PPS_t *pps = avc->pps_array[i];
    printf(" PPS #%ld - size %d", i + 1, pps->size);
    print_buffer_data(pps->bytes, pps->size);
    printf("\n");
  }

  printf(" version: %d\n", avc->version);
  printf(" profile: %d\n", avc->profile);
  printf(" compatibility: %d\n", avc->compatibility);
  printf(" level: %d\n", avc->level);

  printf(" reserved: %d\n           ", avc->reserved);
  print_byte(avc->reserved);
  printf("\n");

  printf(" nalu_length_minus_one: %d\n", avc->nalu_length_minus_one);

  printf(" reserved: ");
  print_byte(avc->reserved_after_length_minus_one);
  printf("\n");

  printf(" number_of_sps_nalus: %d\n", avc->number_of_sps_nalus);
  printf(" number_of_pps_nalus: %d\n", avc->number_of_pps_nalus);

  close_mp4_container(container);
}
Beispiel #5
0
void cloptparser::CLOptParser::parse() {
    // Nothing to parse, return without doing anything
    if(0 >= argc)
        return;

    int mandatoryOptionsCount = 0;
    int shortNameOptionsCount = 0;
    int longNameOptionsCount = 0;
    bool parsingError = false;
    std::string errorMsg;

    for(int i=1; i<argc && !parsingError; i++) {
        if(boost::starts_with(argv[i], "--")) {
            // Full name options
            std::string opt = std::string(argv[i]);
            std::string optName = std::string(argv[i]).substr(2, opt.find("=") - 2);
            std::string optValue = std::string(argv[i]).substr(opt.find("=") + 1);

            BOOST_LOG_TRIVIAL(debug) << "Long Name Attribute: " <<
                                     optName <<
                                     " Got Value: " << optValue;

            try {
                setValueByName(optName, optValue);
                longNameOptionsCount++;
            } catch(cloptparser::OptionNotFoundException ex) {
                errorMsg = ex.what();
                BOOST_LOG_TRIVIAL(error) << errorMsg;
                parsingError = true;
            }
        } else if(boost::starts_with(argv[i], "-")) {
            // Short name options
            std::string opt = std::string(argv[i]);
            std::string optName = std::string(argv[i]).substr(1);
            std::string optValue = std::string(argv[++i]);

            BOOST_LOG_TRIVIAL(debug) << "Short Name Attribute: " <<
                                        optName <<
                                        " Got Value: " << optValue;

            try {
                setValueByName(optName, optValue);
                shortNameOptionsCount++;

                // Decrease the iteration index since the current value
                // is another option
                if(!currentOptionNeedsRValue(optName))
                    i--;
            } catch(cloptparser::OptionNotFoundException ex) {
                errorMsg = ex.what();
                BOOST_LOG_TRIVIAL(error) << errorMsg;
                parsingError = true;
            }
        } else {
            if(mandatoryOptionsCount <= mandatoryOptions.size() - 1) {
                mandatoryOptions[mandatoryOptionsCount]->setValue(argv[i]);
                BOOST_LOG_TRIVIAL(debug) << "Mandatory Attribute: " <<
                                            mandatoryOptions[mandatoryOptionsCount]->LongName() <<
                                            " Got Value: " << argv[i];
            }

            mandatoryOptionsCount++;
        }
    }

    if(mandatoryOptionsCount != mandatoryOptions.size() && !parsingError) {
        parsingError = true;
        errorMsg = "Invalid number of mandatory values supplied";
    }

    if(parsingError) {
        std::cerr << "Error: " << errorMsg << std::endl;
        printHelpMessage();
        return;
    }
}
Beispiel #6
0
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int argc = __argc;
    char **argv = __argv;
#else
int main(int argc, char *argv[])
{
#endif
    int seed = time(NULL);
    bool verifyexit = false;
    bool check_mods = false;
    std::string dump;
    dump_mode dmode = dump_mode::TSV;
    std::vector<std::string> opts;
    std::string world; /** if set try to load first save in this world on startup */

    // Set default file paths
#ifdef PREFIX
#define Q(STR) #STR
#define QUOTE(STR) Q(STR)
    PATH_INFO::init_base_path(std::string(QUOTE(PREFIX)));
#else
    PATH_INFO::init_base_path("");
#endif

#if (defined USE_HOME_DIR || defined USE_XDG_DIR)
    PATH_INFO::init_user_dir();
#else
    PATH_INFO::init_user_dir("./");
#endif
    PATH_INFO::set_standard_filenames();

    MAP_SHARING::setDefaults();
    {
        const char *section_default = nullptr;
        const char *section_map_sharing = "Map sharing";
        const char *section_user_directory = "User directories";
        const std::array<arg_handler, 12> first_pass_arguments = {{
            {
                "--seed", "<string of letters and or numbers>",
                "Sets the random number generator's seed value",
                section_default,
                [&seed](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    const unsigned char *hash_input = (const unsigned char *) params[0];
                    seed = djb2_hash(hash_input);
                    return 1;
                }
            },
            {
                "--jsonverify", nullptr,
                "Checks the cdda json files",
                section_default,
                [&verifyexit](int, const char **) -> int {
                    verifyexit = true;
                    return 0;
                }
            },
            {
                "--check-mods", "[mods...]",
                "Checks the json files belonging to cdda mods",
                section_default,
                [&check_mods,&opts]( int n, const char *params[] ) -> int {
                    check_mods = true;
                    test_mode = true;
                    for( int i = 0; i < n; ++i ) {
                        opts.emplace_back( params[ i ] );
                    }
                    return 0;
                }
            },
            {
                "--dump-stats", "<what> [mode = TSV] [opts...]",
                "Dumps item stats",
                section_default,
                [&dump,&dmode,&opts](int n, const char *params[]) -> int {
                    if( n < 1 ) {
                        return -1;
                    }
                    test_mode = true;
                    dump = params[ 0 ];
                    for( int i = 2; i < n; ++i ) {
                        opts.emplace_back( params[ i ] );
                    }
                    if( n >= 2 ) {
                        if( !strcmp( params[ 1 ], "TSV" ) ) {
                            dmode = dump_mode::TSV;
                            return 0;
                        } else if( !strcmp( params[ 1 ], "HTML" ) ) {
                            dmode = dump_mode::HTML;
                            return 0;
                        } else {
                            return -1;
                        }
                    }
                    return 0;
                }
            },
            {
                "--world", "<name>",
                "Load world",
                section_default,
                [&world](int n, const char *params[]) -> int {
                    if( n < 1 ) {
                        return -1;
                    }
                    world = params[0];
                    return 1;
                }
            },
            {
                "--basepath", "<path>",
                "Base path for all game data subdirectories",
                section_default,
                [](int num_args, const char **params) {
                    if (num_args < 1) return -1;
                    PATH_INFO::init_base_path(params[0]);
                    PATH_INFO::set_standard_filenames();
                    return 1;
                }
            },
            {
                "--shared", nullptr,
                "Activates the map-sharing mode",
                section_map_sharing,
                [](int, const char **) -> int {
                    MAP_SHARING::setSharing(true);
                    MAP_SHARING::setCompetitive(true);
                    MAP_SHARING::setWorldmenu(false);
                    return 0;
                }
            },
            {
                "--username", "<name>",
                "Instructs map-sharing code to use this name for your character.",
                section_map_sharing,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    MAP_SHARING::setUsername(params[0]);
                    return 1;
                }
            },
            {
                "--addadmin", "<username>",
                "Instructs map-sharing code to use this name for your character and give you "
                    "access to the cheat functions.",
                section_map_sharing,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    MAP_SHARING::addAdmin(params[0]);
                    return 1;
                }
            },
            {
                "--adddebugger", "<username>",
                "Informs map-sharing code that you're running inside a debugger",
                section_map_sharing,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    MAP_SHARING::addDebugger(params[0]);
                    return 1;
                }
            },
            {
                "--competitive", nullptr,
                "Instructs map-sharing code to disable access to the in-game cheat functions",
                section_map_sharing,
                [](int, const char **) -> int {
                    MAP_SHARING::setCompetitive(true);
                    return 0;
                }
            },
            {
                "--userdir", "<path>",
                "Base path for user-overrides to files from the ./data directory and named below",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::init_user_dir(params[0]);
                    PATH_INFO::set_standard_filenames();
                    return 1;
                }
            }
        }};

        // The following arguments are dependent on one or more of the previous flags and are run
        // in a second pass.
        const std::array<arg_handler, 9> second_pass_arguments = {{
            {
                "--worldmenu", nullptr,
                "Enables the world menu in the map-sharing code",
                section_map_sharing,
                [](int, const char **) -> int {
                    MAP_SHARING::setWorldmenu(true);
                    return true;
                }
            },
            {
                "--datadir", "<directory name>",
                "Sub directory from which game data is loaded",
                nullptr,
                [](int num_args, const char **params) -> int {
                      if (num_args < 1) return -1;
                      PATH_INFO::update_pathname("datadir", params[0]);
                      PATH_INFO::update_datadir();
                      return 1;
                }
            },
            {
                "--savedir", "<directory name>",
                "Subdirectory for game saves",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("savedir", params[0]);
                    return 1;
                }
            },
            {
                "--configdir", "<directory name>",
                "Subdirectory for game configuration",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("config_dir", params[0]);
                    PATH_INFO::update_config_dir();
                    return 1;
                }
            },
            {
                "--memorialdir", "<directory name>",
                "Subdirectory for memorials",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("memorialdir", params[0]);
                    return 1;
                }
            },
            {
                "--optionfile", "<filename>",
                "Name of the options file within the configdir",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("options", params[0]);
                    return 1;
                }
            },
            {
                "--keymapfile", "<filename>",
                "Name of the keymap file within the configdir",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("keymap", params[0]);
                    return 1;
                }
            },
            {
                "--autopickupfile", "<filename>",
                "Name of the autopickup options file within the configdir",
                nullptr,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("autopickup", params[0]);
                    return 1;
                }
            },
            {
                "--motdfile", "<filename>",
                "Name of the message of the day file within the motd directory",
                nullptr,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("motd", params[0]);
                    return 1;
                }
            },
        }};

        // Process CLI arguments.
        const size_t num_first_pass_arguments =
            sizeof(first_pass_arguments) / sizeof(first_pass_arguments[0]);
        const size_t num_second_pass_arguments =
            sizeof(second_pass_arguments) / sizeof(second_pass_arguments[0]);
        int saved_argc = --argc; // skip program name
        const char **saved_argv = (const char **)++argv;
        while (argc) {
            if(!strcmp(argv[0], "--help")) {
                printHelpMessage(first_pass_arguments.data(), num_first_pass_arguments,
                    second_pass_arguments.data(), num_second_pass_arguments);
                return 0;
            } else {
                bool arg_handled = false;
                for (size_t i = 0; i < num_first_pass_arguments; ++i) {
                    auto &arg_handler = first_pass_arguments[i];
                    if (!strcmp(argv[0], arg_handler.flag)) {
                        argc--;
                        argv++;
                        int args_consumed = arg_handler.handler(argc, (const char **)argv);
                        if (args_consumed < 0) {
                            printf("Failed parsing parameter '%s'\n", *(argv - 1));
                            exit(1);
                        }
                        argc -= args_consumed;
                        argv += args_consumed;
                        arg_handled = true;
                        break;
                    }
                }
                // Skip other options.
                if (!arg_handled) {
                    --argc;
                    ++argv;
                }
            }
        }
        while (saved_argc) {
            bool arg_handled = false;
            for (size_t i = 0; i < num_second_pass_arguments; ++i) {
                auto &arg_handler = second_pass_arguments[i];
                if (!strcmp(saved_argv[0], arg_handler.flag)) {
                    --saved_argc;
                    ++saved_argv;
                    int args_consumed = arg_handler.handler(saved_argc, saved_argv);
                    if (args_consumed < 0) {
                        printf("Failed parsing parameter '%s'\n", *(argv - 1));
                        exit(1);
                    }
                    saved_argc -= args_consumed;
                    saved_argv += args_consumed;
                    arg_handled = true;
                    break;
                }
            }
            // Ingore unknown options.
            if (!arg_handled) {
                --saved_argc;
                ++saved_argv;
            }
        }
    }

    if (!assure_dir_exist(FILENAMES["user_dir"].c_str())) {
        printf("Can't open or create %s. Check permissions.\n",
               FILENAMES["user_dir"].c_str());
        exit(1);
    }

    setupDebug();

/**
 * OS X does not populate locale env vars correctly (they usually default to
 * "C") so don't bother trying to set the locale based on them.
 */
#if (!defined MACOSX)
    if (setlocale(LC_ALL, "") == NULL) {
        DebugLog(D_WARNING, D_MAIN) << "Error while setlocale(LC_ALL, '').";
    } else {
#endif
        try {
            std::locale::global( std::locale( "" ) );
        } catch( const std::exception& ) {
            // if user default locale retrieval isn't implemented by system
            try{
                // default to basic C locale
                std::locale::global( std::locale::classic() );
            } catch( const std::exception &err ) {
                debugmsg( "%s", err.what() );
                exit_handler(-999);
            }
        }
#if (!defined MACOSX)
    }
#endif

    get_options().init();
    get_options().load();
    set_language();

    // in test mode don't initialize curses to avoid escape sequences being inserted into output stream
    if( !test_mode ) {
        try {
			catacurses::init_interface();
        } catch( const std::exception &err ) {
            // can't use any curses function as it has not been initialized
            std::cerr << "Error while initializing the interface: " << err.what() << std::endl;
            DebugLog( D_ERROR, DC_ALL ) << "Error while initializing the interface: " << err.what() << "\n";
            return 1;
        }
    }

    srand(seed);

    g = new game;
    // First load and initialize everything that does not
    // depend on the mods.
    try {
        g->load_static_data();
        if (verifyexit) {
            exit_handler(0);
        }
        if( !dump.empty() ) {
            init_colors();
            exit( g->dump_stats( dump, dmode, opts ) ? 0 : 1 );
        }
        if( check_mods ) {
            init_colors();
            loading_ui ui( false );
            exit( g->check_mod_data( opts, ui ) && !test_dirty ? 0 : 1 );
        }
    } catch( const std::exception &err ) {
        debugmsg( "%s", err.what() );
        exit_handler(-999);
    }

    // Now we do the actual game.

    g->init_ui();

    curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone

#if (!(defined _WIN32 || defined WINDOWS))
    struct sigaction sigIntHandler;
    sigIntHandler.sa_handler = exit_handler;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;
    sigaction(SIGINT, &sigIntHandler, NULL);
#endif

#ifdef LOCALIZE
    std::string lang = "";
#if (defined _WIN32 || defined WINDOWS)
    lang = getLangFromLCID( GetUserDefaultLCID() );
#else
    const char *v = setlocale( LC_ALL, NULL );
    if( v != NULL ) {
        lang = v;

        if( lang == "C" ) {
            lang = "en";
        }
    }
#endif
    if( get_option<std::string>( "USE_LANG" ).empty() && ( lang.empty() || !isValidLanguage( lang ) ) ) {
        select_language();
        set_language();
    }
#endif

    while( true ) {
        if( !world.empty() ) {
            if( !g->load( world ) ) {
                break;
            }
            world.clear(); // ensure quit returns to opening screen

        } else {
            main_menu menu;
            if( !menu.opening_screen() ) {
                break;
            }
        }

        while( !g->do_turn() );
    };


    exit_handler(-999);
    return 0;
}
Beispiel #7
0
int interactiveMode() {
	
	const std::string INPUT_LINE = "Enter a calculation: ";
	const std::string INPUT_LINE_END = "";
	const std::string OUTPUT_LINE = "\033[1;93m > ";
	const std::string OUTPUT_LINE_END = "\033[0m";
	
	// Used for debugging when displaying the error message
	const int INPUT_LINE_LENGTH = 21;
	
	try {
		
		// Detect when the user presses CTRL+C on their keyboard
		signal(SIGINT, sigint);
		
		std::cout << INPUT_LINE;
		std::string input = "";
		while (getline(std::cin, input)) {
			
			std::cout << INPUT_LINE_END;
			
			// Detect special commands
			if (input == "") {
				// No text entered
				// Act the same way as Bash, and just show another empty line
			}
			else if ( input == "help" ) {
				printHelpMessage(std::cout, true);
				// It looks better with an additional blank line after the message.
				std::cout << std::endl;
			}
			else if ( input == "exit" || input == "quit") {
				exit(EXIT_SUCCESS);
			}
			else {
				// No special command entered. Parse the text that was entered as usual.
				int result = parseString<int>(input);
				std::cout << OUTPUT_LINE << result << OUTPUT_LINE_END << std::endl;
			}
			
			// And all over again
			std::cout << INPUT_LINE;
		}
	
	} catch (ParseError& e) {
		e.print(std::cerr, true, INPUT_LINE_LENGTH);
		exit (e.getID());
	} catch (MathError& e) {
		e.print(std::cerr, true, INPUT_LINE_LENGTH);
		exit (e.getID());
	} catch (Error& e) {
		e.print(std::cerr, true);
		exit (e.getID());
	} catch (...) {
		unknownError();
		exit(EXIT_FAILURE);
	}
	
	// Technically, this line should never execute unless we change the way
	//  the above while loop works.
	exit(EXIT_SUCCESS);
}
Beispiel #8
0
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int argc = __argc;
    char **argv = __argv;
#else
int main(int argc, char *argv[])
{
#endif
    int seed = time(NULL);
    bool verifyexit = false;
    bool check_all_mods = false;

    // Set default file paths
#ifdef PREFIX
#define Q(STR) #STR
#define QUOTE(STR) Q(STR)
    PATH_INFO::init_base_path(std::string(QUOTE(PREFIX)));
#else
    PATH_INFO::init_base_path("");
#endif

#if (defined USE_HOME_DIR || defined USE_XDG_DIR)
    PATH_INFO::init_user_dir();
#else
    PATH_INFO::init_user_dir("./");
#endif
    PATH_INFO::set_standard_filenames();

    MAP_SHARING::setDefaults();
    {
        const char *section_default = nullptr;
        const char *section_map_sharing = "Map sharing";
        const char *section_user_directory = "User directories";
        const arg_handler first_pass_arguments[] = {
            {
                "--seed", "<string of letters and or numbers>",
                "Sets the random number generator's seed value",
                section_default,
                [&seed](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    const unsigned char *hash_input = (const unsigned char *) params[0];
                    seed = djb2_hash(hash_input);
                    return 1;
                }
            },
            {
                "--jsonverify", nullptr,
                "Checks the cdda json files",
                section_default,
                [&verifyexit](int, const char **) -> int {
                    verifyexit = true;
                    return 0;
                }
            },
            {
                "--check-mods", nullptr,
                "Checks the json files belonging to cdda mods",
                section_default,
                [&check_all_mods](int, const char **) -> int {
                    check_all_mods = true;
                    return 0;
                }
            },
            {
                "--basepath", "<path>",
                "Base path for all game data subdirectories",
                section_default,
                [](int num_args, const char **params) {
                    if (num_args < 1) return -1;
                    PATH_INFO::init_base_path(params[0]);
                    PATH_INFO::set_standard_filenames();
                    return 1;
                }
            },
            {
                "--shared", nullptr,
                "Activates the map-sharing mode",
                section_map_sharing,
                [](int, const char **) -> int {
                    MAP_SHARING::setSharing(true);
                    MAP_SHARING::setCompetitive(true);
                    MAP_SHARING::setWorldmenu(false);
                    return 0;
                }
            },
            {
                "--username", "<name>",
                "Instructs map-sharing code to use this name for your character.",
                section_map_sharing,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    MAP_SHARING::setUsername(params[0]);
                    return 1;
                }
            },
            {
                "--addadmin", "<username>",
                "Instructs map-sharing code to use this name for your character and give you "
                    "access to the cheat functions.",
                section_map_sharing,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    MAP_SHARING::addAdmin(params[0]);
                    return 1;
                }
            },
            {
                "--adddebugger", "<username>",
                "Informs map-sharing code that you're running inside a debugger",
                section_map_sharing,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    MAP_SHARING::addDebugger(params[0]);
                    return 1;
                }
            },
            {
                "--competitive", nullptr,
                "Instructs map-sharing code to disable access to the in-game cheat functions",
                section_map_sharing,
                [](int, const char **) -> int {
                    MAP_SHARING::setCompetitive(true);
                    return 0;
                }
            },
            {
                "--userdir", "<path>",
                "Base path for user-overrides to files from the ./data directory and named below",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::init_user_dir(params[0]);
                    PATH_INFO::set_standard_filenames();
                    return 1;
                }
            }
        };

        // The following arguments are dependent on one or more of the previous flags and are run
        // in a second pass.
        const arg_handler second_pass_arguments[] = {
            {
                "--worldmenu", nullptr,
                "Enables the world menu in the map-sharing code",
                section_map_sharing,
                [](int, const char **) -> int {
                    MAP_SHARING::setWorldmenu(true);
                    return true;
                }
            },
            {
                "--datadir", "<directory name>",
                "Sub directory from which game data is loaded",
                nullptr,
                [](int num_args, const char **params) -> int {
                      if (num_args < 1) return -1;
                      PATH_INFO::update_pathname("datadir", params[0]);
                      PATH_INFO::update_datadir();
                      return 1;
                }
            },
            {
                "--savedir", "<directory name>",
                "Subdirectory for game saves",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("savedir", params[0]);
                    return 1;
                }
            },
            {
                "--configdir", "<directory name>",
                "Subdirectory for game configuration",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("config_dir", params[0]);
                    PATH_INFO::update_config_dir();
                    return 1;
                }
            },
            {
                "--memorialdir", "<directory name>",
                "Subdirectory for memorials",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("memorialdir", params[0]);
                    return 1;
                }
            },
            {
                "--optionfile", "<filename>",
                "Name of the options file within the configdir",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("options", params[0]);
                    return 1;
                }
            },
            {
                "--keymapfile", "<filename>",
                "Name of the keymap file within the configdir",
                section_user_directory,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("keymap", params[0]);
                    return 1;
                }
            },
            {
                "--autopickupfile", "<filename>",
                "Name of the autopickup options file within the configdir",
                nullptr,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("autopickup", params[0]);
                    return 1;
                }
            },
            {
                "--motdfile", "<filename>",
                "Name of the message of the day file within the motd directory",
                nullptr,
                [](int num_args, const char **params) -> int {
                    if (num_args < 1) return -1;
                    PATH_INFO::update_pathname("motd", params[0]);
                    return 1;
                }
            },
        };

        // Process CLI arguments.
        const size_t num_first_pass_arguments =
            sizeof(first_pass_arguments) / sizeof(first_pass_arguments[0]);
        const size_t num_second_pass_arguments =
            sizeof(second_pass_arguments) / sizeof(second_pass_arguments[0]);
        int saved_argc = --argc; // skip program name
        const char **saved_argv = (const char **)++argv;
        while (argc) {
            if(!strcmp(argv[0], "--help")) {
                printHelpMessage(first_pass_arguments, num_first_pass_arguments,
                    second_pass_arguments, num_second_pass_arguments);
                return 0;
            } else {
                bool arg_handled = false;
                for (size_t i = 0; i < num_first_pass_arguments; ++i) {
                    auto &arg_handler = first_pass_arguments[i];
                    if (!strcmp(argv[0], arg_handler.flag)) {
                        argc--;
                        argv++;
                        int args_consumed = arg_handler.handler(argc, (const char **)argv);
                        if (args_consumed < 0) {
                            printf("Failed parsing parameter '%s'\n", *(argv - 1));
                            exit(1);
                        }
                        argc -= args_consumed;
                        argv += args_consumed;
                        arg_handled = true;
                        break;
                    }
                }
                // Skip other options.
                if (!arg_handled) {
                    --argc;
                    ++argv;
                }
            }
        }
        while (saved_argc) {
            bool arg_handled = false;
            for (size_t i = 0; i < num_second_pass_arguments; ++i) {
                auto &arg_handler = second_pass_arguments[i];
                if (!strcmp(saved_argv[0], arg_handler.flag)) {
                    --saved_argc;
                    ++saved_argv;
                    int args_consumed = arg_handler.handler(saved_argc, saved_argv);
                    if (args_consumed < 0) {
                        printf("Failed parsing parameter '%s'\n", *(argv - 1));
                        exit(1);
                    }
                    saved_argc -= args_consumed;
                    saved_argv += args_consumed;
                    arg_handled = true;
                    break;
                }
            }
            // Ingore unknown options.
            if (!arg_handled) {
                --saved_argc;
                ++saved_argv;
            }
        }
    }

    if (!assure_dir_exist(FILENAMES["user_dir"].c_str())) {
        printf("Can't open or create %s. Check permissions.\n",
               FILENAMES["user_dir"].c_str());
        exit(1);
    }

    setupDebug();

    if (setlocale(LC_ALL, "") == NULL) {
        DebugLog(D_WARNING, D_MAIN) << "Error while setlocale(LC_ALL, '').";
    }

    // Options strings loaded with system locale
    get_options().init();
    get_options().load();

    set_language(true);

    if (initscr() == NULL) { // Initialize ncurses
        DebugLog( D_ERROR, DC_ALL ) << "initscr failed!";
        return 1;
    }
    init_interface();
    noecho();  // Don't echo keypresses
    cbreak();  // C-style breaks (e.g. ^C to SIGINT)
    keypad(stdscr, true); // Numpad is numbers
#if !(defined TILES || defined _WIN32 || defined WINDOWS)
    // For tiles or windows, this is handled already in initscr().
    init_colors();
#endif
    // curs_set(0); // Invisible cursor
    set_escdelay(10); // Make escape actually responsive

    std::srand(seed);

    g = new game;
    // First load and initialize everything that does not
    // depend on the mods.
    try {
        g->load_static_data();
        if (verifyexit) {
            if(g->game_error()) {
                exit_handler(-999);
            }
            exit_handler(0);
        }
        if (check_all_mods) {
            // Here we load all the mods and check their
            // consistency (both is done in check_all_mod_data).
            g->init_ui();
            popup_nowait("checking all mods");
            g->check_all_mod_data();
            if(g->game_error()) {
                exit_handler(-999);
            }
            // At this stage, the mods (and core game data)
            // are find and we could start playing, but this
            // is only for verifying that stage, so we exit.
            exit_handler(0);
        }
    } catch( const std::exception &err ) {
        debugmsg( "%s", err.what() );
        exit_handler(-999);
    }

    // Now we do the actual game.

    g->init_ui();
    if(g->game_error()) {
        exit_handler(-999);
    }

    curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone

#if (!(defined _WIN32 || defined WINDOWS))
    struct sigaction sigIntHandler;
    sigIntHandler.sa_handler = exit_handler;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;
    sigaction(SIGINT, &sigIntHandler, NULL);
#endif

    bool quit_game = false;
    do {
        if(!g->opening_screen()) {
            quit_game = true;
        }
        while (!quit_game && !g->do_turn()) ;
        if (g->game_quit() || g->game_error()) {
            quit_game = true;
        }
    } while (!quit_game);


    exit_handler(-999);

    return 0;
}
Beispiel #9
0
void keyboardCallback( unsigned char key, int x, int y ){
  switch( key ){
    case 27: // The 'esc' key
    case 'q':
#ifdef FREEGLUT
      glutLeaveMainLoop( );
#else
      exit( 0 );
#endif
      break;
    case 'a':
    // move the left teapot (B) along it's positive y-axis
    // Please implement this feature.

    teapotTranslation_B[0] -= translationDelta;
    break;
    case 'd':
    // move the left teapot (B) along it's negative y-axis
    // Please implement this feature.

    teapotTranslation_B[0] += translationDelta;
    break;
    case 'w':
    // move the left teapot (B) along it's positive x-axis
    // Please implement this feature.

    teapotTranslation_B[1] += translationDelta;
    break;
    case 's':
    // move the left teapot (B) along it's negative x-axis
    // Please implement this feature.

    teapotTranslation_B[1] -= translationDelta;
    break;
    case 'v':
    // positively scale the right teapot (A)
    // Please implement this feature.

    teapotScale_A[0] += 0.05;
    teapotScale_A[1] += 0.05;
    teapotScale_A[2] += 0.05;
    break;
    case 'b':
    // negatively scale the right teapot (A)
    // Please implement this feature.

    teapotScale_A[0] -= 0.05;
    teapotScale_A[1] -= 0.05;
    teapotScale_A[2] -= 0.05;
    break;
    case 'o':
      isPerspective = !isPerspective;
      updateProjection(
                       glutGet(GLUT_WINDOW_WIDTH),
                       glutGet(GLUT_WINDOW_HEIGHT)
                      );
      printf("Using perspective projection? %s\n",
             (isPerspective ? "Yes" : "No"));
      break;
    case 'p':
      useGLPerspective = !useGLPerspective;
      updateProjection(
                       glutGet(GLUT_WINDOW_WIDTH),
                       glutGet(GLUT_WINDOW_HEIGHT)
                      );
      printf("Using OpenGL's perspective functions? %s\n",
             (useGLPerspective ? "Yes" : "No"));
      break;
    case '+':
      rotationDelta += 1.0;
      printf( "Rotation delta set to %g\n", rotationDelta );
      break;
    case '-':
      rotationDelta -= 1.0;
      printf( "Rotation delta set to %g\n", rotationDelta );
      break;
    case 'g':
      useGLLookAt = !useGLLookAt;
      printf("Using OpenGL's gluLookAt? %s\n",
             (useGLLookAt ? "Yes" : "No"));
      break;
    case 'h':
      printHelpMessage( );
      break;
    case 'r':
      initEyePosition( );
      initUpVector( );
      initDeltas( );
      initToggles( );
      initTeapotTransforms( );
      printf("Eye position, up vector and rotation delta reset.\n");
      break;
    case 'e':
      camZ = camZ + 0.2;
      break;
    case 'c':
      camZ = camZ - 0.2;
      break;
    default:
      fprintf( stderr, "You pushed '%c' (%d).\n", key, key );
      break;
  }
  glutPostRedisplay( );
}
Beispiel #10
0
App::App(int &argc, char **argv)
    : QApplication(argc, argv)
    , _invocation(argv[0])
    , _gui(false)
    , _interactive(false)
{
    // Enforce singleton property
    if (_instance) {
        throw std::runtime_error("Only one instance of App allowed.");
    }

    // Remember if we are done
    bool done = false;

    // Set the singleton instance to this
    _instance = this;

    // Set the application properties
    setApplicationName(APPLICATION_NAME);
    setApplicationVersion(APPLICATION_VERSION_STRING);
    setOrganizationName(APPLICATION_VENDOR_NAME);
    setOrganizationDomain(APPLICATION_VENDOR_URL);

    // Configure the logging mechanism
    log4cxx::LoggerPtr rootlogger = log4cxx::Logger::getRootLogger();
    rootlogger->addAppender(new log4cxx::ConsoleAppender(new log4cxx::PatternLayout("[%-5p] %m%n")));

    // Parse the commandline
    int idx = 1;
    while (idx < argc) {
        QString arg(argv[idx]);
        if (matches_option(arg, "help", 0) || matches_option(arg, "h") || matches_option(arg, "?", 0)) {
            printHelpMessage();
            std::exit(0);
        } else if (matches_option(arg, "version", 0)) {
            printVersionMessage();
            std::exit(0);
        } else if (matches_option(arg, "version-triplet")) {
            printVersionTripletMessage();
            std::exit(0);
        } else if (matches_option(arg, "prefset")) {
            // Verify that there is another argument
            if ((idx + 1) >= argc) {
                LOG4CXX_FATAL(_logger, "Option \"" << arg << "\" requires a parameter.");
                std::exit(1);
            }

            // Increment the index
            idx++;

            // Get the next parameter
            std::string param(argv[idx]);

            // Determine if there is an equals sign
            // If there is, set the preference;
            // Otherwise, remove the preference
            size_t eqidx = param.find('=');
            if (eqidx != std::string::npos) {
                std::string key = param.substr(0, eqidx);
                std::string val = param.substr(eqidx + 1);
                setPreference(key, val);
            } else {
                unsetPreference(param);
            }
            done = true;
        } else if (matches_option(arg, "prefdel")) {
            // Verify that there is another argument
            if ((idx + 1) >= argc) {
                LOG4CXX_FATAL(_logger, "Option \"" << arg << "\" requires a parameter.");
                std::exit(1);
            }

            // Increment the index
            idx++;

            // Get the next parameter
            std::string param(argv[idx]);

            // Remove the preference
            unsetPreference(param);
            done = true;
        } else if (matches_option(arg, "preflist")) {
            printAllPreferences();
            done = true;
        } else if (matches_option(arg, "prefget")) {
            // Verify that there is another argument
            if ((idx + 1) >= argc) {
                LOG4CXX_FATAL(_logger, "Option \"" << arg << "\" requires a parameter.");
                std::exit(1);
            }

            // Increment the index
            idx++;

            // Get the next parameter
            std::string param(argv[idx]);

            // Print the preference
            printPreference(param);
            done = true;
        } else if (matches_option(arg, "loglevel")) {
            // Verify that there is another argument
            if ((idx + 1) >= argc) {
                LOG4CXX_FATAL(_logger, "Option \"" << arg << "\" requires a parameter.");
                std::exit(1);
            }

            // Increment the index
            idx++;

            // Get the next parameter
            std::string param(argv[idx]);

            // Determine if there is an equals sign and act accordingly
            size_t eqidx = param.find('=');
            if (eqidx != std::string::npos) {
                std::string logger = param.substr(0, eqidx);
                std::string level  = param.substr(eqidx + 1);
                setLogLevel(logger, level);
            } else {
                setLogLevel("", param);
            }
        } else if (matches_option(arg, "appid") || matches_option(arg, "application-identifier")) {
            printApplicationIdentifier();
            std::exit(0);
        } else if (matches_option(arg, "gui")) {
            if (_interactive) {
                LOG4CXX_FATAL(_logger, "Cannot specify both \"--gui\" and \"--interactive\" simultaneously.");
                std::exit(1);
            }
            if (_gui) {
                LOG4CXX_WARN(_logger, "Option \"" << arg << "\" already specified. Ignoring.");
            }
            _gui = true;
        } else if (matches_option(arg, "interactive")) {
            if (_gui) {
                LOG4CXX_FATAL(_logger, "Cannot specify both \"--gui\" and \"--interactive\" simultaneously.");
                std::exit(1);
            }
            if (_interactive) {
                LOG4CXX_WARN(_logger, "Option \"" << arg << "\" already specified. Ignoring.");
            }
            _interactive = true;
        } else {
            LOG4CXX_WARN(_logger, "Unrecognized option: \"" << arg << "\". Ignoring");
        }
        idx++;
    }

    initGUI();
}
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    a.setApplicationName("Svg Creater");
    a.setApplicationVersion("0.0.1");

    QStringList args = a.arguments();

    QRegExp rxArgHelp("--help");
    QRegExp rxArgH("-h");
    QRegExp rxArgVersion("--version");
    QRegExp rxArgV("-v");


    bool isHelp(false), isVer(false);
    QStringList filePaths;

    for(int i(1); i < args.size(); ++i)
    {
        if (rxArgHelp.indexIn(args.at(i)) != -1  ||
                rxArgH.indexIn(args.at(i)) != -1)
        {
            isHelp = true;
        }
        else if (rxArgVersion.indexIn(args.at(i)) != -1  ||
                 rxArgV.indexIn(args.at(i)) != -1)
        {
            isVer = true;
        }
        else
        {
            if(QFile::exists(args.at(i)))
            {
                filePaths.append(args.at(i));
            }
        }

    }

    if(isHelp)
    {
        printHelpMessage();
        return 0;
    }
    else if(isVer)
    {
        printVersion();
        return 0;
    }

    QTranslator appTranslator;
    QString translationsPath("/usr/share/easypaint/translations/");
    QString appLanguage = DataSingleton::Instance()->getAppLanguage();
    if(appLanguage == "system")
    {
        appTranslator.load(translationsPath + "easypaint_" + QLocale::system().name());
    }
    else
    {
        appTranslator.load(translationsPath + appLanguage);
    }
    a.installTranslator(&appTranslator);

    MainWindow w(filePaths);
    w.show();

    return a.exec();
}
Beispiel #12
0
int doTheRealWork(int argc, char **argv) {

  MinVR::VRDataIndex *index = new MinVR::VRDataIndex;

  // These will be extracted from argv.
  int nth = 0;

  // Extracting...
  switch(argc) {

  case 1:
    printHelpMessage();
    return EXIT_SUCCESS;
    
  case 2:
    if (argv[1][0] == '-') {
      printHelpMessage();
      return EXIT_SUCCESS;
    }
    throw std::runtime_error("Need a data name.  (Try --usage.)");
    break;

  case 3:
    // Don't really need to do anything here except avoid throwing error.
    break;
    
  case 4:
    // If there is a fourth arg, hope it's an integer.
    sscanf(argv[3], "%d", &nth);
    break;
    
  default:
    throw std::runtime_error("Too many arguments");
    break;
  }

  index->processXMLFile(argv[1], std::string("/"));

  MinVR::VRCORETYPE_ID tp = index->getType(argv[2]);

  // std::cout << "datumName:" << datumName << " N:" << nth << " tp:" << tp << std::endl;

  // Now print out the values, according to the data type.
  switch(tp) {

  case MinVR::VRCORETYPE_INT: 
    std::cout << (MinVR::VRInt)index->getValue(argv[2]);
    break;

  case MinVR::VRCORETYPE_FLOAT: 
    std::cout << (MinVR::VRFloat)index->getValue(argv[2]);
    break;

  case MinVR::VRCORETYPE_STRING:
    std::cout << (MinVR::VRString)index->getValue(argv[2]);
    break;

  case MinVR::VRCORETYPE_INTARRAY: {
    MinVR::VRIntArray ia = index->getValue(argv[2]);
    if (nth >= (int)ia.size())
      throw std::runtime_error("N too large for array");
    std::cout << ia[nth];
    break;
  }
    
  case MinVR::VRCORETYPE_FLOATARRAY: {
    MinVR::VRFloatArray ia = index->getValue(argv[2]);
    if (nth >= (int)ia.size())
      throw std::runtime_error("N too large for array");
    std::cout << ia[nth];
    break;
  }

  case MinVR::VRCORETYPE_STRINGARRAY: {
    MinVR::VRStringArray ia = index->getValue(argv[2]);
    if (nth >= (int)ia.size())
      throw std::runtime_error("N too large for array");
    std::cout << ia[nth];
    break;
  }

  case MinVR::VRCORETYPE_CONTAINER:
    std::cout << index->serialize(argv[2]);
    break;
    
  default:
    throw std::runtime_error("Not supported for that type.");
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}