/**
Configures hardware for the particular hardware platform:
- Ports: sets direction, interrupts, pullup/pulldown resistors etc.
- Holds radio in reset (active-low)
*/
void halInit()
{
    //
    // Enable the floating-point unit.
    //
    FPUEnable();
    //
    // Configure the floating-point unit to perform lazy stacking of the
    // floating-point state.
    //
    FPULazyStackingEnable();

	oscInit();
	portInit();
	halUartInit();

    //Point the function pointers to doNothing() so that they don't trigger a restart
    debugConsoleIsr = &doNothing;
    buttonIsr = &doNothing;
    clearLeds();
    displayVersion();
#ifdef AF_VERBOSE
        printf("* AF_VERBOSE *\r\n");
#endif
}
NestedCommandLineApp::NestedCommandLineApp(
    std::string programName,
    std::string version,
    std::string programHeading,
    std::string programHelpFooter,
    InitFunction initFunction)
    : programName_(std::move(programName)),
      programHeading_(std::move(programHeading)),
      programHelpFooter_(std::move(programHelpFooter)),
      version_(std::move(version)),
      initFunction_(std::move(initFunction)),
      globalOptions_("Global options") {
  addCommand(
      kHelpCommand.str(),
      "[command]",
      "Display help (globally or for a given command)",
      "Displays help (globally or for a given command).",
      [this](
          const po::variables_map& vm, const std::vector<std::string>& args) {
        displayHelp(vm, args);
      });
  builtinCommands_.insert(kHelpCommand);

  addCommand(
      kVersionCommand.str(),
      "[command]",
      "Display version information",
      "Displays version information.",
      [this](const po::variables_map&, const std::vector<std::string>&) {
        displayVersion();
      });
  builtinCommands_.insert(kVersionCommand);

  globalOptions_.add_options()(
      kHelpCommand.str().c_str(),
      "Display help (globally or for a given command)")(
      kVersionCommand.str().c_str(), "Display version information");
}
Example #3
0
File: main.cpp Project: Imari/Dagon
inline
bool shouldStartApp(int argc, char* argv[])
{
#define MATCHES_OPT(str, short, long) \
    strcmp(str, short)==0 || strcmp(str, long)==0
    
    if (argc > 1) {
        const char* const firstArg = argv[1];
        if (MATCHES_OPT(firstArg, "-h", "--help")) {
          displayHelp(argv[0]);
          return false;
        }
        
        if (MATCHES_OPT(firstArg, "-v", "--version")) {
          displayVersion();
          return false;
        }
        
    }
    return true;
    
#undef MATCHES_OPT
}
Example #4
0
/*********************************************************************
** METHOD  :
** PURPOSE :
** INPUT   :
** OUTPUT  :
** RETURN  :
** REMARKS :
*********************************************************************/
IProperties* Tool::run (IProperties* input)
{
    /** We keep the input parameters. */
    setInput (input);

    if (getInput()->get(STR_VERSION) != 0)
    {
    	displayVersion(cout);
        return _output;
    }

    /** We define one dispatcher. */
    if (_input->getInt(STR_NB_CORES) == 1)
    {
        setDispatcher (new SerialDispatcher ());
    }
    else
    {
        setDispatcher (new Dispatcher (_input->getInt(STR_NB_CORES)) );
    }

    /** We may have some pre processing. */
    preExecute ();

    /** We execute the actual job. */
    {
        //TIME_INFO (_timeInfo, _name);
        execute ();
    }

    /** We may have some post processing. */
    postExecute ();

    /** We return the output properties. */
    return _output;
}
Example #5
0
int main (int argc, char **argv)
{
   int           opt;
   int           temp_int;
   int           option_index = 0;
   
   bool          bOptionHelp = false;
        
   /* Create application instance */
   //   QApplication::setStyle( new QWindowsStyle );
   QApplication qapp (argc, argv);

   /* Print the version number */
   displayVersion();

   // create the data location manager (with user data under ~/.showeq
   DataLocationMgr dataLocMgr(".showeq");

   /* Initialize the parameters with default values */
   QFileInfo configFileDefInfo = dataLocMgr.findExistingFile(".", "seqdef.xml",
							     true, false);
   
   if (!configFileDefInfo.exists())
   {
     fprintf(stderr, 
	     "Fatal: Couldn't find seqdef.xml!\n"
	     "\tDid you remember to do 'make install'\n");
     exit(-1);
   }

   QString configFileDef = configFileDefInfo.absFilePath();

   QFileInfo configFileInfo = dataLocMgr.findWriteFile(".", "showeq.xml",
						       true, true);

   // deal with funky border case since we may be running setuid
   QString configFile;
   if (configFileInfo.dir() != QDir::root())
     configFile = configFileInfo.absFilePath();
   else
     configFile = QFileInfo(dataLocMgr.userDataDir(".").absPath(),
			    "showeq.xml").absFilePath();

   // scan command line arguments for a specified config file
   int i = 1;
   while (i < argc)
   {
      if ((argv[i][0] == '-') && (argv[i][1] == 'o'))
         configFile = argv[i + 1];

      i ++;
   }

   /* NOTE: See preferencefile.cpp for info on how to use prefrences class */
   printf("Using config file '%s'\n", (const char*)configFile);
   pSEQPrefs = new XMLPreferences(configFileDef, configFile);

   showeq_params = new ShowEQParams;

   QString section;

   section = "Interface";
   /* Allow map depth filtering */
   showeq_params->retarded_coords  = pSEQPrefs->getPrefBool("RetardedCoords", section, 0);
   showeq_params->systime_spawntime = pSEQPrefs->getPrefBool("SystimeSpawntime", section, false);
   showeq_params->pvp = pSEQPrefs->getPrefBool("PvPTeamColoring", section, false);
   showeq_params->deitypvp = pSEQPrefs->getPrefBool("DeityPvPTeamColoring", section, false);
   showeq_params->keep_selected_visible = pSEQPrefs->getPrefBool("KeepSelected", section, true);

   section = "Misc";
   showeq_params->fast_machine = pSEQPrefs->getPrefBool("FastMachine", section, true);
   showeq_params->createUnknownSpawns = pSEQPrefs->getPrefBool("CreateUnknownSpawns", section, true);

   showeq_params->walkpathrecord = pSEQPrefs->getPrefBool("WalkPathRecording", section, false);
   showeq_params->walkpathlength = pSEQPrefs->getPrefInt("WalkPathLength", section, 25);
   /* Tells SEQ whether or not to display casting messages (Turn this off if you're on a big raid) */

   section = "SpawnList";
   showeq_params->showRealName = pSEQPrefs->getPrefBool("ShowRealName", section, false);

   /* Different files for different kinds of raw data */

   section = "SaveState";
   showeq_params->saveZoneState = 
     pSEQPrefs->getPrefBool("ZoneState", section, 1);
   showeq_params->savePlayerState = 
     pSEQPrefs->getPrefBool("PlayerState", section, 1);
   showeq_params->saveSpawns = pSEQPrefs->getPrefBool("Spawns", section, false);
   showeq_params->saveSpawnsFrequency = 
     pSEQPrefs->getPrefInt("SpawnsFrequency", section, (120 * 1000));
   showeq_params->restorePlayerState = false;
   showeq_params->restoreZoneState = false;
   showeq_params->restoreSpawns = false;
   showeq_params->saveRestoreBaseFilename = dataLocMgr.findWriteFile("tmp", pSEQPrefs->getPrefString("BaseFilename", section, "last")).absFilePath();

   /* Parse the commandline for commandline parameters */
   while ((opt = getopt_long( argc,
                              argv,
                              OPTION_LIST,
                              option_list,
                              &option_index
                             ))               != -1
          )
   {
      switch (opt)
      {
         /* Set the request to use a despawn list based off the spawn alert list. */

         /* Set the interface */
         case 'i':
         {            
	   pSEQPrefs->setPrefString("Device", "Network", optarg, 
				    XMLPreferences::Runtime);
	   break;
         }


         /* Set pcap thread to realtime */
         case 'r':
         {  
	   pSEQPrefs->setPrefBool("RealTimeThread", "Network", true, 
				  XMLPreferences::Runtime);
				  
            break;
         }


         /* Set the spawn filter file */
         case 'f':
         {
	   pSEQPrefs->setPrefString("FilterFile", "Filters", optarg, 
				    XMLPreferences::Runtime);
            
	   break;
         }


         /* Packet playback mode */
         case 'j':
         {            
            if (optarg)
               pSEQPrefs->setPrefString("Filename", "VPacket", optarg, 
					XMLPreferences::Runtime);

	    pSEQPrefs->setPrefBool("Playback", "VPacket", true, 
				   XMLPreferences::Runtime);
	    pSEQPrefs->setPrefBool("Record", "VPacket", false, 
				   XMLPreferences::Runtime);
            
            break;
         }

         /* Packet record mode */
         case 'g':
         {
            if (optarg)
               pSEQPrefs->setPrefString("Filename", "VPacket", optarg, 
					XMLPreferences::Runtime);

	    pSEQPrefs->setPrefBool("Playback", "VPacket", false, 
				   XMLPreferences::Runtime);
	    pSEQPrefs->setPrefBool("Record", "VPacket", true, 
				   XMLPreferences::Runtime);
            
            break;
         }


         /* Config file was already taken care of, ignore */
         case 'o':
            break;


         /* Make filter case sensitive */
         case 'C':
         {
	   pSEQPrefs->setPrefBool("IsCaseSensitive", "Filters", true,
				  XMLPreferences::Runtime);
	   break;
         }

         /* Use retarded coordinate system yxz */
         case 'c':
         {
            showeq_params->retarded_coords = 1;
            break;
         }


         /* Fast machine updates.. framerate vs packet based */
         case 'F':
         {
            showeq_params->fast_machine = 1;
            break;
         }


         /* Show unknown spawns */
         case 'K':
         {
            showeq_params->createUnknownSpawns = 1;
            break;
         }


         /* Select spawn on 'Consider' */
         case 'S':
         {
	   pSEQPrefs->setPrefBool("SelectOnCon", "Interface", true,
				  XMLPreferences::Runtime);
	   break;
         }


         /* Select spawn on 'Target' */
         case 'e':
         {
	   pSEQPrefs->setPrefBool("SelectOnTarget", "Interface", true, 
				  XMLPreferences::Runtime);
	   break;
         }


         /* Show net info */
         case 'N':
         {
	   pSEQPrefs->getPrefBool("ShowNetStats", section, true, 
				  XMLPreferences::Runtime);
	   break;
         }


         /* 't'rack pathing for mobs */
         case 't':
         {
            showeq_params->walkpathrecord = 1;
            break;
         }


         /* Maximum spawn path tracking length  */
         case 'L':
         {
            showeq_params->walkpathlength = atoi(optarg);
            break;
         }

         
         /* Log spawns! */
         case 'x':
         {
	   pSEQPrefs->setPrefBool("LogSpawns", "Misc", true, 
				  XMLPreferences::Runtime);
	   break;
         }


         /* Display the version info... */
         case 'V':
         case 'v':
         {
  	   exit(0);
	   break;
         }

         /* Don't autodetect character settings */
         case 'W':
         {
	   pSEQPrefs->getPrefBool("AutoDetectCharSettings", "Defaults", 
				  false, XMLPreferences::Runtime);
	   break;
         }


         /* Set default player level */
         case 'X':
         {
            temp_int = atoi(optarg);
            
            if (temp_int < 1 || temp_int > 70)
            {
               printf ("Invalid default level.  Valid range is 1 - 70.\n");
               exit(0);
            }

	    pSEQPrefs->setPrefInt("DefaultLevel", "Defaults", temp_int,
				  XMLPreferences::Runtime);
            break;
         }


         /* Set default player race */
         case 'Y':
         {
            temp_int = atoi(optarg);
            
            if ((temp_int < 1 || temp_int > 12) && 
		(temp_int != 128) &&
		(temp_int != 130) &&
		(temp_int != 26) &&
		(temp_int != 330))
            {
               printf ("Invalid default race, please use showeq -h to list valid race options.\n");
               exit(0);
            }
            
	    pSEQPrefs->setPrefInt("DefaultRace", "Defaults", temp_int,
				  XMLPreferences::Runtime);

            break;
         }


         /* Set default player class */
         case 'Z':
         {
            temp_int = atoi(optarg);
            
            if (temp_int < 1 || temp_int > 16)
            {
               printf ("Invalid default class, please use showeq -h to list valid class options.\n");
               exit(0);
            }

	    pSEQPrefs->setPrefInt("DefaultClass", "Defaults", temp_int);
            break;
         }

         /* IP address to track */
         case IPADDR_OPTION:
         {
	   pSEQPrefs->setPrefString("IP", "Network", optarg, 
				    XMLPreferences::Runtime);

	   break;
         }


         /* MAC address to track for those on DHCP */
         case MACADDR_OPTION:
         {
	   pSEQPrefs->setPrefString("MAC", "Network", optarg, 
				    XMLPreferences::Runtime);

	   break;
         }


         /* Filename for logging all packets */
         case GLOBAL_LOG_FILENAME_OPTION:
         {
	   pSEQPrefs->setPrefString("GlobalLogFilename", "PacketLogging", 
				    optarg, XMLPreferences::Runtime);
	   break;
         }


         /* Filename for logging world change packets */
         case WORLD_LOG_FILENAME_OPTION:
         {
	   pSEQPrefs->setPrefString("WorldLogFilename", "PacketLogging", 
				    optarg, XMLPreferences::Runtime);
	   break;
         }

         /* Filename for logging zone change packets */
         case ZONE_LOG_FILENAME_OPTION:
         {
	   pSEQPrefs->setPrefString("ZoneLogFilename", "PacketLogging", 
				    optarg, XMLPreferences::Runtime);
	   break;
         }


         /* Filename for logging unknown zone change packets */
         case UNKNOWN_LOG_FILENAME_OPTION:
         {
	   pSEQPrefs->setPrefString("UnknownZoneLogFilename", 
				    "PacketLogging", optarg, 
				    XMLPreferences::Runtime);
	   break;
         }


         /* Log everything */
         case GLOBAL_LOG_OPTION:
         {
	   pSEQPrefs->setPrefBool("LogAllPackets", "PacketLogging", true,
				  XMLPreferences::Runtime);
	   break;
         }


         /* Log all zone change packets */
         case ZONE_LOG_OPTION:
         {
	   pSEQPrefs->setPrefBool("LogZonePackets", "PacketLogging", true,
				  XMLPreferences::Runtime);
	   break;
         }


         /* Log only unfamiliar zone change packets */
         case UNKNOWN_ZONE_LOG_OPTION:
         {
	   pSEQPrefs->setPrefBool("LogUnknownZonePackets", "PacketLogging", true,
				  XMLPreferences::Runtime);
	   break;
         }


         case PLAYBACK_SPEED_OPTION:
         {
	   pSEQPrefs->setPrefInt("PlaybackRate", "VPacket", atoi(optarg), 
				 XMLPreferences::Runtime);
            break;
         }


         /* Enable logging of raw packets... */
         case RAW_LOG_OPTION:
         {
	   pSEQPrefs->setPrefBool("LogRawPackets", "PacketLogging", true,
				  XMLPreferences::Runtime);
	   break;
         }

         /* Display spawntime in UNIX time (time_t) instead of hh:mm format */
         case SYSTIME_SPAWNTIME_OPTION:
         { 
            showeq_params->systime_spawntime = 1;
            break;
         }

         case SPAWNLOG_FILENAME_OPTION:
         {
	   pSEQPrefs->setPrefString("SpawnLogFilename", "Misc", optarg,
				  XMLPreferences::Runtime);
	   break;
         }
         
         case ITEMDB_DATA_FILENAME_OPTION:
	   {
	     pSEQPrefs->setPrefString("DataDBFilename", "ItemDB", optarg,
				      XMLPreferences::Runtime);
	     break;
         }
         
         case ITEMDB_RAW_FILENAME_OPTION:
         {
	     pSEQPrefs->setPrefString("RawDataDBFilename", "ItemDB", optarg,
				      XMLPreferences::Runtime);
            break;
         }

         case ITEMDB_DATABASES_ENABLED:
         {
	   pSEQPrefs->setPrefInt("DatabasesEnabled", "ItemDB", atoi(optarg),
				 XMLPreferences::Runtime);
	   break;
         }
	 
         case ITEMDB_DISABLE:
	 {
	   pSEQPrefs->setPrefBool("Enabled", "ItemDB", false, 
				 XMLPreferences::Runtime);
	   break;
	 }

         case ITEMDB_ENABLE:
	 {
	   pSEQPrefs->setPrefBool("Enabled", "ItemDB", true, 
				 XMLPreferences::Runtime);
	   break;
	 }

         case RESTORE_PLAYER_STATE:
	 {
	   showeq_params->restorePlayerState = true;
	   break;
	 }
         case RESTORE_ZONE_STATE:
	 {
	   showeq_params->restoreZoneState = true;
	   break;
	 }
         case RESTORE_SPAWNS:
	 {
	   showeq_params->restoreSpawns = true;
	   break;
	 }
         case RESTORE_ALL:
	 {
	   showeq_params->restorePlayerState = true;
	   showeq_params->restoreZoneState = true;
	   showeq_params->restoreSpawns = true;
	   break;
	 }


         /* Spit out the help */
         case 'h': /* Fall through */
         default:
         {
            bOptionHelp = true;
            break;
         }
      }
   }

   if (bOptionHelp)
   {
     displayOptions(argv[0]);
     exit (0);
   }

   /* Set up individual files for logging selected packet types based on
      a common filename base.   The types to log were found by following
      where pre_worked was a precondition for further analysis.
   */

   int ret;

   // just to add a scope to better control when the main interface gets 
   // destroyed
   if  (1)
   {
     /* The main interface widget */
     EQInterface intf(&dataLocMgr, 0, "interface");
     qapp.setMainWidget (&intf);
   
     /* Start the main loop */
     ret = qapp.exec ();
   }

   // delete the preferences data
   delete pSEQPrefs;

   // delete the showeq_params data
   delete showeq_params;

   return ret;
}
void NestedCommandLineApp::doRun(const std::vector<std::string>& args) {
  if (programName_.empty()) {
    programName_ = guessProgramName();
  }

  bool not_clean = false;
  std::vector<std::string> cleanArgs;
  std::vector<std::string> endArgs;

  for (auto& na : args) {
    if (na == "--") {
      not_clean = true;
    } else if (not_clean) {
      endArgs.push_back(na);
    } else {
      cleanArgs.push_back(na);
    }
  }

  auto parsed = parseNestedCommandLine(cleanArgs, globalOptions_);
  po::variables_map vm;
  po::store(parsed.options, vm);
  if (vm.count(kHelpCommand.str())) {
    std::vector<std::string> helpArgs;
    if (parsed.command) {
      helpArgs.push_back(*parsed.command);
    }
    displayHelp(vm, helpArgs);
    return;
  }

  if (vm.count(kVersionCommand.str())) {
    displayVersion();
    return;
  }

  if (!parsed.command) {
    throw ProgramExit(
        1,
        folly::sformat(
            "Command not specified. Run '{} {}' for help.",
            programName_,
            kHelpCommand));
  }

  auto& p = findCommand(*parsed.command);
  auto& cmd = p.first;
  auto& info = p.second;

  auto cmdOptions =
      po::command_line_parser(parsed.rest).options(info.options).run();

  po::store(cmdOptions, vm);
  po::notify(vm);

  auto cmdArgs =
      po::collect_unrecognized(cmdOptions.options, po::include_positional);

  cmdArgs.insert(cmdArgs.end(), endArgs.begin(), endArgs.end());

  if (initFunction_) {
    initFunction_(cmd, vm, cmdArgs);
  }

  info.command(vm, cmdArgs);
}
Example #7
0
// Main
int main(int argc, char *argv[])
{
    // We must save it here because QApplication constructor may change it
    bool isOneArg = (argc == 2);

#ifdef Q_OS_MAC
    // On macOS 10.12 Sierra, Apple changed the behaviour of CFPreferencesSetValue() https://bugreports.qt.io/browse/QTBUG-56344
    // Due to this, we have to move from native plist to IniFormat
    macMigratePlists();
#endif

#ifndef DISABLE_GUI
    migrateRSS();
#endif

    // Create Application
    QString appId = QLatin1String("qBittorrent-") + Utils::Misc::getUserIDString();
    QScopedPointer<Application> app(new Application(appId, argc, argv));

    const QBtCommandLineParameters params = parseCommandLine();

    if (!params.unknownParameter.isEmpty()) {
        displayBadArgMessage(QObject::tr("%1 is an unknown command line parameter.", "--random-parameter is an unknown command line parameter.")
                             .arg(params.unknownParameter));
        return EXIT_FAILURE;
    }

#ifndef Q_OS_WIN
    if (params.showVersion) {
        if (isOneArg) {
            displayVersion();
            return EXIT_SUCCESS;
        }
        else {
            displayBadArgMessage(QObject::tr("%1 must be the single command line parameter.")
                                 .arg(QLatin1String("-v (or --version)")));
            return EXIT_FAILURE;
        }
    }
#endif

    if (params.showHelp) {
        if (isOneArg) {
            displayUsage(argv[0]);
            return EXIT_SUCCESS;
        }
        else {
            displayBadArgMessage(QObject::tr("%1 must be the single command line parameter.")
                                 .arg(QLatin1String("-h (or --help)")));
            return EXIT_FAILURE;
        }
    }

    if ((params.webUiPort > 0) && (params.webUiPort <= 65535)) {
        Preferences::instance()->setWebUiPort(params.webUiPort);
    }
    else {
        displayBadArgMessage(QObject::tr("%1 must specify the correct port (1 to 65535).")
                             .arg(QLatin1String("--webui-port")));
        return EXIT_FAILURE;
    }

    // Set environment variable
    if (!qputenv("QBITTORRENT", QBT_VERSION))
        std::cerr << "Couldn't set environment variable...\n";

#ifndef DISABLE_GUI
    if (!userAgreesWithLegalNotice())
        return EXIT_SUCCESS;
#else
    if (!params.shouldDaemonize
        && isatty(fileno(stdin))
        && isatty(fileno(stdout))
        && !userAgreesWithLegalNotice())
        return EXIT_SUCCESS;
#endif

    // Check if qBittorrent is already running for this user
    if (app->isRunning()) {
#ifdef DISABLE_GUI
        if (params.shouldDaemonize) {
            displayBadArgMessage(QObject::tr("You cannot use %1: qBittorrent is already running for this user.")
                                 .arg(QLatin1String("-d (or --daemon)")));
            return EXIT_FAILURE;
        }
        else
#endif
        qDebug("qBittorrent is already running for this user.");

        Utils::Misc::msleep(300);
        app->sendParams(params.torrents);

        return EXIT_SUCCESS;
    }

#if defined(Q_OS_WIN)
    // This affects only Windows apparently and Qt5.
    // When QNetworkAccessManager is instantiated it regularly starts polling
    // the network interfaces to see what's available and their status.
    // This polling creates jitter and high ping with wifi interfaces.
    // So here we disable it for lack of better measure.
    // It will also spew this message in the console: QObject::startTimer: Timers cannot have negative intervals
    // For more info see:
    // 1. https://github.com/qbittorrent/qBittorrent/issues/4209
    // 2. https://bugreports.qt.io/browse/QTBUG-40332
    // 3. https://bugreports.qt.io/browse/QTBUG-46015

    qputenv("QT_BEARER_POLL_TIMEOUT", QByteArray::number(-1));
#endif

#if defined(Q_OS_MAC)
{
    // Since Apple made difficult for users to set PATH, we set here for convenience.
    // Users are supposed to install Homebrew Python for search function.
    // For more info see issue #5571.
    QByteArray path = "/usr/local/bin:";
    path += qgetenv("PATH");
    qputenv("PATH", path.constData());
}
#endif

#ifndef DISABLE_GUI
    if (!upgrade()) return EXIT_FAILURE;
#else
    if (!upgrade(!params.shouldDaemonize
                 && isatty(fileno(stdin))
                 && isatty(fileno(stdout)))) return EXIT_FAILURE;
#endif

#ifdef DISABLE_GUI
    if (params.shouldDaemonize) {
        app.reset(); // Destroy current application
        if ((daemon(1, 0) == 0)) {
            app.reset(new Application(appId, argc, argv));
            if (app->isRunning()) {
                // Another instance had time to start.
                return EXIT_FAILURE;
            }
        }
        else {
            qCritical("Something went wrong while daemonizing, exiting...");
            return EXIT_FAILURE;
        }
    }
#else
    if (!params.noSplash)
        showSplashScreen();
#endif

#if defined(Q_OS_UNIX) || defined(STACKTRACE_WIN)
    signal(SIGINT, sigNormalHandler);
    signal(SIGTERM, sigNormalHandler);
    signal(SIGABRT, sigAbnormalHandler);
    signal(SIGSEGV, sigAbnormalHandler);
#endif

    return app->exec(params.torrents);
}
Example #8
0
///////////////////////////////////
// and here the fun begins...
int
main (int argc, char *argv[])
{
  // option processing variables
  int  opt;
  int  option_index = 0;

  // should the action be forced
  bool forceAction = false;

  // should help be displayed
  bool displayHelp = false;

  // should version info be displayed
  bool displayVer = false;

  // the action the user has chosen to perform
  int  action = 0;

  // the argument to the action
  const char* action_arg = NULL;

  // should existing records be updated (default: No)
  bool updateRecords = false;

  // selected itemNr, 0 = no specific item selected
  uint16_t itemNr = 0;

  // enabled DBTypes (default to all)
  int dbTypes = (EQItemDB::LORE_DB | EQItemDB::NAME_DB | 
		 EQItemDB::DATA_DB | EQItemDB::RAW_DATA_DB);

  // search string
  QString search;

  // note program name for later use.
  progname = argv[0];

  // Get an instance of the EQItemDB
  EQItemDB* itemDB = new EQItemDB;
  
  // begin processing options
  while ((opt = getopt_long( argc,
			     argv,
			     OPTION_LIST,
			     option_list,
			     &option_index)) != -1)
    {
      switch(opt)
	{
	case 'd': // display an item
	case 'l': // list items
	case 'f': // import from a flat file db
	case 'r': // import from a itemrawdata.dbm file
	case 'o': // import from an old GDBM file
	case 'e': // export a raw data record
	case 'x': // export database as a CSV file
	case 'D': // delete a record
	case 'R': // reorganize database
	case 'u': // upgrade ItemDB to current format
	  // these actions are mutually exclusive, if two chosen, display help
	  if (action != 0)
	    displayHelp = true;
	  else
	  {
	    // save action and it's argument
	    action = opt;
	    action_arg = optarg;
	  }
	  break;
	case 'i':
	  itemNr = (uint16_t)atoi(optarg);
	  break;
	case 'U':
	  updateRecords = true;
	  break;
	case 'v':
	case 'V':
	  displayVer = true;
	  break;
	case ITEMDB_LORE_FILENAME_OPTION:
	  itemDB->SetDBFile(EQItemDB::LORE_DB, optarg);
	  break;
	case ITEMDB_NAME_FILENAME_OPTION:
	  itemDB->SetDBFile(EQItemDB::NAME_DB, optarg);
	  break;
	case ITEMDB_DATA_FILENAME_OPTION:
	  itemDB->SetDBFile(EQItemDB::DATA_DB, optarg);
	  break;
	case ITEMDB_RAW_FILENAME_OPTION:
	  itemDB->SetDBFile(EQItemDB::RAW_DATA_DB, optarg);
	  break;
	case ITEMDB_DATABASES_ENABLED:
	  dbTypes = atoi(optarg);
	  break;
	case FORCE_ACTION:
	  forceAction = true;
	  break;
	case 'h': // display usage info
	default:
	  displayHelp = true;
	  break;
	}
    }

  // if no action selected, display help
  if ((action == 0) && !displayHelp && !displayVer)
  {
    fprintf(stderr, "No action specified\n");
    displayHelp = true;
  }

  // are there extra arguments
  if (optind < argc)
  {
    //yes, there are

    // is the action list with no search argument
    if ((action == 'l') && (action_arg == 0))
    {
      // yes, so use them for the search argument
      while (optind < argc)
	{
	  if (!search.isEmpty())
	    search += " ";
	  
	  // append extra arguments to search string
	  search += argv[optind++];
	}
    }
    else // otherwise display help
    {
      fprintf(stderr, "Extra arguments!\n");
      displayHelp = true;
    }
  }

  // if either the display or delete actions were specified and no 
  // item was specified display help.
  if (((action == 'd') || (action == 'D')) && 
      (itemNr == 0))
    displayHelp = true;

  // result to return from the program (the exit code).
  int result = 0;

  // display the help/usage information if required and exit
  if (displayHelp)
  {
    // display the usage information
    displayUsage(); 

    // return non-zero result
    result = 1;
  }
  else
  {
    // enable the set of dbtypes
    itemDB->SetEnabledDBTypes(dbTypes);
    
    // display the version information
    if (displayVer)
      displayVersion(itemDB);

    // perform the requested action
    switch(action)
    {
    case 'd': // display an item
      result = displayRecord(itemDB, itemNr);
      break;
    case 'l': // list items
    {
      if (action_arg)
	search = action_arg;
      result = listRecords(itemDB, itemNr, search);
      break;
    }
    case 'f': // import from a flat file db
      result = importFlatFile(itemDB, action_arg, itemNr, 
			      forceAction, updateRecords);
      break;
    case 'r': // import from a itemrawdata.dbm file
    case 'o': // import from an old GDBM file
      // the above two options are really the same
      result = importGDBM(itemDB, action_arg, itemNr, 
			  forceAction, updateRecords);
      break;
    case 'e': // export a raw data record
      result = exportRawRecord(itemDB, action_arg, itemNr);
      break;
    case 'x': // export database as a CSV file
      result = exportRecordCSV(itemDB, action_arg, itemNr);
      break;
    case 'D': // delete a record
      result = deleteRecord(itemDB, itemNr, forceAction);
      break;
    case 'R': // reorganize database
      result = reorganize(itemDB);
      break;
    case 'u': // upgrade ItemDB to current format
      result = upgradeItemDB(itemDB);

    }
  }

  // shutdown the ItemDB
  itemDB->Shutdown();

  // delete this instance of ItemDB
  delete itemDB;

  return result;
}
Example #9
0
bool parseCommandline(const std::vector<Common::UString> &argv, Common::UString &target, int &code) {
	target.clear();

	Common::UString key;

	bool stopMark = false;
	for (size_t i = 1; i < argv.size(); i++) {

		if (!key.empty()) {
		// Still got one parameter missing from last time
			if (!setOption(key, argv[i])) {
				code = 1;
				return false;
			}

			continue;
		}

		if (!stopMark && argv[i].beginsWith("-")) {
			if (argv[i] == "--") {
				stopMark = true;
				continue;
			}

			if (argv[i] == "--help") {
				code = 0;
				displayUsage(argv[0]);
				return false;
			}

			if (argv[i] == "--version") {
				code = 0;
				displayVersion();
				return false;
			}

			if (!parseOption(argv[i], key)) {
				code = 1;
				return false;
			}

			if (key == "listdebug") {
				setOption(key, "true");
				key.clear();
			}

			if (key == "listlangs") {
				setOption(key, "true");
				key.clear();
			}

			continue;
		}

		if (!target.empty()) {
			warning("Found multiple target (\"%s\" and \"%s\")", target.c_str(), argv[i].c_str());
			code = 1;
			return false;
		}

		target = argv[i];
	}

	if (target.empty() && !ConfigMan.hasKey("path") && !ConfigMan.getBool("listdebug", false)) {
		displayUsage(argv[0]);
		code = 1;
		return false;
	}

	return true;
}
Example #10
0
// Main
int main(int argc, char *argv[])
{
    // We must save it here because QApplication constructor may change it
    bool isOneArg = (argc == 2);

    // Create Application
    QString appId = QLatin1String("qBittorrent-") + Utils::Misc::getUserIDString();
    QScopedPointer<Application> app(new Application(appId, argc, argv));

    const QBtCommandLineParameters params = parseCommandLine();

    if (!params.unknownParameter.isEmpty()) {
        displayBadArgMessage(QObject::tr("%1 is an unknown command line parameter.", "--random-parameter is an unknown command line parameter.")
                             .arg(params.unknownParameter));
        return EXIT_FAILURE;
    }

#ifndef Q_OS_WIN
    if (params.showVersion) {
        if (isOneArg) {
            displayVersion();
            return EXIT_SUCCESS;
        }
        else {
            displayBadArgMessage(QObject::tr("%1 must be the single command line parameter.")
                                 .arg(QLatin1String("-v (or --version)")));
            return EXIT_FAILURE;
        }
    }
#endif

    if (params.showHelp) {
        if (isOneArg) {
            displayUsage(argv[0]);
            return EXIT_SUCCESS;
        }
        else {
            displayBadArgMessage(QObject::tr("%1 must be the single command line parameter.")
                                 .arg(QLatin1String("-h (or --help)")));
            return EXIT_FAILURE;
        }
    }

    if ((params.webUiPort > 0) && (params.webUiPort <= 65535)) {
        Preferences::instance()->setWebUiPort(params.webUiPort);
    }
    else {
        displayBadArgMessage(QObject::tr("%1 must specify the correct port (1 to 65535).")
                             .arg(QLatin1String("--webui-port")));
        return EXIT_FAILURE;
    }

    // Set environment variable
    if (!qputenv("QBITTORRENT", QByteArray(VERSION)))
        std::cerr << "Couldn't set environment variable...\n";

#ifndef DISABLE_GUI
    if (!userAgreesWithLegalNotice())
        return EXIT_SUCCESS;
#else
    if (!params.shouldDaemonize
        && isatty(fileno(stdin))
        && isatty(fileno(stdout))
        && !userAgreesWithLegalNotice())
        return EXIT_SUCCESS;
#endif

    // Check if qBittorrent is already running for this user
    if (app->isRunning()) {
#ifdef DISABLE_GUI
        if (params.shouldDaemonize) {
            displayBadArgMessage(QObject::tr("You cannot use %1: qBittorrent is already running for this user.")
                                 .arg(QLatin1String("-d (or --daemon)")));
            return EXIT_FAILURE;
        }
        else
#endif
        qDebug("qBittorrent is already running for this user.");

        Utils::Misc::msleep(300);
        app->sendParams(params.torrents);

        return EXIT_SUCCESS;
    }

#ifndef DISABLE_GUI
    if (!upgrade()) return EXIT_FAILURE;
#else
    if (!upgrade(!params.shouldDaemonize
                 && isatty(fileno(stdin))
                 && isatty(fileno(stdout)))) return EXIT_FAILURE;
#endif

    srand(time(0));
#ifdef DISABLE_GUI
    if (params.shouldDaemonize) {
        app.reset(); // Destroy current application
        if ((daemon(1, 0) == 0)) {
            app.reset(new Application(appId, argc, argv));
            if (app->isRunning()) {
                // Another instance had time to start.
                return EXIT_FAILURE;
            }
        }
        else {
            qCritical("Something went wrong while daemonizing, exiting...");
            return EXIT_FAILURE;
        }
    }
#else
    if (!params.noSplash)
        showSplashScreen();
#endif

#if defined(Q_OS_UNIX) || defined(STACKTRACE_WIN)
    signal(SIGABRT, sigabrtHandler);
    signal(SIGTERM, sigtermHandler);
    signal(SIGINT, sigintHandler);
    signal(SIGSEGV, sigsegvHandler);
#endif

    return app->exec(params.torrents);
}
int main (int argc, char* argv[]) {
	int c;

	// Si hay pocos argumentos
	if (argc < 2) {
		fprintf(stderr, "ERROR: No hay suficientes argumentos\n");
		return 1;
	}


	// while (1) {
	static struct option opciones[] = {
		// No setean flags
		{"help", no_argument, 0, 'h'},
		{"version", no_argument, 0, 'V'},
		{"bubble", required_argument, 0, 'b'},
		{"heap", required_argument, 0, 'p'},
		{0,0,0,0}
	};
	// getopt_long stores the option index here.
	int indice_opciones = -1;

	int hayOpciones = 0;

	while( (c = getopt_long (argc, argv, "hVb:p:", opciones, &indice_opciones)) != -1 ) {

		hayOpciones = 1;

		switch (c) {
			case 0:
				printf ("Estoy en 0. Option %s", opciones[indice_opciones].name);
				if (optarg)
					printf (" with arg %s", optarg);
				printf ("\n");
				break;

			case 'h':
				if (argc == 2)
					displayAyuda();
				break;

			case 'V':
				if (argc == 2)
					displayVersion();
				break;

			case 'p':
				if (argc == 3)
					ejecutarHeapsort(optarg);
				break;

			case 'b':
				if (argc == 3)
					ejecutarBubblesort(optarg);
				break;

			default:
				break;
		}
	 }
	 // Si hay argumentos que no son opciones, se buscan si nos nombres de archivo
	if (optind < argc && !hayOpciones) {
		char op[256];
		while (optind < argc) {
			sprintf(op, "cat %s", argv[optind++]);
			system(op);
		}
	}

	return 0;
 }
Example #12
0
int main(int argc, char **argv)
#endif
{
  int expectedMods = 0;
  
#ifdef macintosh
  doSiouxStuff();
  argc = ccommand(&argv);
#endif
 
  /* Added by Bob Goode/Tam Ngo, 5/21/97, for WINSOCK option. */
#ifdef OS2
  sock_init();
#elif defined(_WINSOCK_)
  startWinsock();
#endif /* Winsock DLL loading */

  x_ipcModuleInitialize();
#ifdef VXWORKS
  /* Do this only after the socket is set up (in case there is an
     old central lying around that needs killed */
  centralTID = taskIdSelf();
#endif
  globalSInit();
  
#if !defined(THINK_C) && !defined(macintosh) && !defined(__TURBOC__) && !defined(OS2) && !defined(_WIN95_MSC_) && !defined(WINNT) && !defined(WIN32)
  (void)signal(SIGINT, abortCentral);
  (void)signal(SIGBUS, abortCentral);
  (void)signal(SIGSEGV, abortCentral);
  (void)signal(SIGPIPE, pipeClosedHnd);
  (void)signal(SIGTERM, abortCentral);
#endif /* !THINK_C && !macintosh */
  
#ifndef VXWORKS
  if ((argc > 1) && (STREQ(argv[1], "-v")))
    displayVersion();
  else if ((argc > 1) && (STREQ(argv[1], "-h"))) {
    displayOptions(argv[0]);
#ifdef macintosh
  SIOUXSettings.autocloseonquit = FALSE;
#endif
  } else {
    parseExpectedMods(argc, argv, &expectedMods);
    parseCommandLineOptions(argc, argv);
#else
  if ((options!= NULL) && (strstr(options, "-v") || strstr(options, "-V"))) {
    displayVersion();
  } else if ((options!= NULL) && 
	     (strstr(options, "-h") || strstr(options, "-H"))) {
    displayOptions("central");
  } else {
    parseOpsFromStr(options, &expectedMods, FALSE);
#endif
      
    if (expectedMods < 1)
      expectedMods = 1;
      
    if (!serverInitialize(expectedMods)) {
      X_IPC_ERROR("ERROR: Unable to start server, Is one already running?\n");
    }
      
#ifndef VXWORKS
    /* Register a method for freeing memory in an emergency. */
    x_ipcRegisterFreeMemHnd(centralFreeMemory,3);
      
    if (GET_S_GLOBAL(listenToStdin))
      printPrompt();
#endif

#ifndef DEFAULT_OPTIONS
    fprintf(stderr, "central running...\n");
#endif

    listenLoop();
  }
#ifdef _WINSOCK_
  WSACleanup();
  printf("Socket cleaned up.");
#endif /* Unload Winsock DLL */
#ifndef VXWORKS
  return 1;
#endif
}
Example #13
0
int ArgumentHandler::processArguments() {

  // short options
  char const *short_options = "A:C:D:F:HM:NP:Q:S:U:XZa:b:c:f:hil::m:o:pr:s:t:uvwy:z:";

  // long options: longname, no/optional/required argument?, flag(not used!), shortname
    const struct option long_options[] = {

      { "alwayssplitvars",      required_argument,  0, 'A'},
      { "caseweights",          required_argument,  0, 'C'},
      { "depvarname",           required_argument,  0, 'D'},
      { "fraction",             required_argument,  0, 'F'},
      { "holdout",              no_argument,        0, 'H'},
      { "memmode",              required_argument,  0, 'M'},
      { "savemem",              no_argument,        0, 'N'},
      { "predict",              required_argument,  0, 'P'},
      { "predictiontype",       required_argument,  0, 'Q'},
      { "splitweights",         required_argument,  0, 'S'},
      { "nthreads",             required_argument,  0, 'U'},
      { "predall",              no_argument,        0, 'X'},
      { "version",              no_argument,        0, 'Z'},

      { "alpha",                required_argument,  0, 'a'},
      { "minprop",              required_argument,  0, 'b'},
      { "catvars",              required_argument,  0, 'c'},
      { "file",                 required_argument,  0, 'f'},
      { "help",                 no_argument,        0, 'h'},
      { "impmeasure",           required_argument,  0, 'i'},
      { "targetpartitionsize",  required_argument,  0, 'l'},
      { "mtry",                 required_argument,  0, 'm'},
      { "outprefix",            required_argument,  0, 'o'},
      { "probability",          no_argument,        0, 'p'},
      { "splitrule",            required_argument,  0, 'r'},
      { "statusvarname",        required_argument,  0, 's'},
      { "ntree",                required_argument,  0, 't'},
      { "noreplace",            no_argument,        0, 'u'},
      { "verbose",              no_argument,        0, 'v'},
      { "write",                no_argument,        0, 'w'},
      { "treetype",             required_argument,  0, 'y'},
      { "seed",                 required_argument,  0, 'z'},

      { 0, 0, 0, 0}
    };

  while (1) {
    int option_index = 0;
    int c = getopt_long(argc, argv, short_options, long_options, &option_index);

    // stop if no options left
    if (c == -1) {
      break;
    }

    switch (c) {

    // upper case options
    case 'A':
      splitString(alwayssplitvars, optarg, ',');
      break;

    case 'C':
      caseweights = optarg;
      break;

    case 'D':
      depvarname = optarg;
      break;

    case 'F':
      try {
        fraction = std::stod(optarg);
        if (fraction > 1 || fraction <= 0) {
          throw std::runtime_error("");
        }
      } catch (...) {
        throw std::runtime_error(
            "Illegal argument for option 'fraction'. Please give a value in (0,1]. See '--help' for details.");
      }
      break;

    case 'H':
      holdout = true;
      break;

    case 'M':
      try {
        memmode = (MemoryMode) std::stoi(optarg);
        if (memmode > MAX_MEM_MODE) {
          throw std::runtime_error("");
        }
      } catch (...) {
        throw std::runtime_error(
            "Illegal argument for option 'memmode'. Please give a positive integer. See '--help' for details.");
      }
      break;

    case 'N':
      savemem = true;
      break;

    case 'P':
      predict = optarg;
      break;

    case 'Q':
          try {
            switch (std::stoi(optarg)) {
            case 1:
              predictiontype = RESPONSE;
              break;
            case 2:
              predictiontype = TERMINALNODES;
              break;
            default:
              throw std::runtime_error("");
              break;
            }
          } catch (...) {
            throw std::runtime_error("Illegal prediction type selected. See '--help' for details.");
          }
          break;

    case 'S':
      splitweights = optarg;
      break;

    case 'U':
      try {
        int temp = std::stoi(optarg);
        if (temp < 1) {
          throw std::runtime_error("");
        } else {
          nthreads = temp;
        }
      } catch (...) {
        throw std::runtime_error(
            "Illegal argument for option 'nthreads'. Please give a positive integer. See '--help' for details.");
      }
      break;

    case 'X':
      predall = true;
      break;

    case 'Z':
      displayVersion();
      return -1;
      break;

      // lower case options
    case 'a':
      try {
        double temp = std::stod(optarg);
        if (temp < 0 || temp > 1) {
          throw std::runtime_error("");
        } else {
          alpha = temp;
        }
      } catch (...) {
        throw std::runtime_error(
            "Illegal argument for option 'alpha'. Please give a value between 0 and 1. See '--help' for details.");
      }
      break;

    case 'b':
      try {
        double temp = std::stod(optarg);
        if (temp < 0 || temp > 0.5) {
          throw std::runtime_error("");
        } else {
          minprop = temp;
        }
      } catch (...) {
        throw std::runtime_error(
            "Illegal argument for option 'minprop'. Please give a value between 0 and 0.5. See '--help' for details.");
      }
      break;

    case 'c':
      splitString(catvars, optarg, ',');
      break;

    case 'f':
      file = optarg;
      break;

    case 'h':
      displayHelp();
      return -1;
      break;

    case 'i':
      try {
        impmeasure = (ImportanceMode) std::stoi(optarg);
        if (impmeasure > MAX_IMP_MODE) {
          throw std::runtime_error("");
        }
      } catch (...) {
        throw std::runtime_error(
            "Illegal argument for option 'impmeasure'. Please give a positive integer. See '--help' for details.");
      }
      break;

    case 'l':
      try {
        int temp = std::stoi(optarg);
        if (temp < 1) {
          throw std::runtime_error("");
        } else {
          targetpartitionsize = temp;
        }
      } catch (...) {
        throw std::runtime_error(
            "Illegal argument for option 'targetpartitionsize'. Please give a positive integer. See '--help' for details.");
      }
      break;

    case 'm':
      try {
        int temp = std::stoi(optarg);
        if (temp < 1) {
          throw std::runtime_error("");
        } else {
          mtry = temp;
        }
      } catch (...) {
        throw std::runtime_error(
            "Illegal argument for option 'mtry'. Please give a positive integer. See '--help' for details.");
      }
      break;

    case 'o':
      outprefix = optarg;
      break;

    case 'p':
      probability = true;
      break;

    case 'r':
      try {
        switch (std::stoi(optarg)) {
        case 1:
          splitrule = LOGRANK;
          break;
        case 2:
          splitrule = AUC;
          break;
        case 3:
          splitrule = AUC_IGNORE_TIES;
          break;
        case 4:
          splitrule = MAXSTAT;
          break;
        default:
          throw std::runtime_error("");
          break;
        }
      } catch (...) {
        throw std::runtime_error("Illegal splitrule selected. See '--help' for details.");
      }
      break;

    case 's':
      statusvarname = optarg;
      break;

    case 't':
      try {
        int temp = std::stoi(optarg);
        if (temp < 1) {
          throw std::runtime_error("");
        } else {
          ntree = temp;
        }
      } catch (...) {
        throw std::runtime_error(
            "Illegal argument for option 'ntree'. Please give a positive integer. See '--help' for details.");
      }
      break;

    case 'u':
      replace = false;
      break;

    case 'v':
      verbose = true;
      break;

    case 'w':
      write = true;
      break;

    case 'y':
      try {
        switch (std::stoi(optarg)) {
        case 1:
          treetype = TREE_CLASSIFICATION;
          break;
        case 3:
          treetype = TREE_REGRESSION;
          break;
        case 5:
          treetype = TREE_SURVIVAL;
          break;
        default:
          throw std::runtime_error("");
          break;
        }
      } catch (...) {
        throw std::runtime_error(
            "Illegal argument for option 'treetype'. Please give a positive integer. See '--help' for details.");
      }
      break;

    case 'z':
      try {
        int temp = std::stoi(optarg);
        if (temp < 0) {
          throw std::runtime_error("");
        } else {
          seed = temp;
        }
      } catch (...) {
        throw std::runtime_error(
            "Illegal argument for option 'seed'. Please give a positive integer. See '--help' for details.");
      }
      break;

    default:
      break;

    }
  }

  // print all other parameters
  while (optind < argc) {
    std::cout << "Other parameter, not processed: " << argv[optind++] << std::endl;
  }

  return 0;
}
Example #14
0
int main(int argc, char *argv[])
{
	char						*firmwareFileName;
	FILE						*fpFirmwareFile;
	int							inquiryType;
	int							firstRecordType;
	int							result;
	int							fileSize;
	int							isSpkg = 0;
	struct stat					statBuf;
	IcsImageHeader_Record_t		recordBuffer;
	uint8_t						cssBuf[CSS_HEADER_SIZE + 10];

	struct option longopts[] = 
	{
		{ "showVersion", no_argument, &inquiryType, SHOWVERSION },
		{ "showType",    no_argument, &inquiryType, SHOWTYPE    },
		{ "help",        no_argument, &inquiryType, HELP        },
		{ 0,             0,           0           , 0           }
	};

	/* parse options for inquiry type */
	if ((result = getopt_long(argc, argv, "", longopts, NULL)))	// assignment, not ==
		Usage();

	if (inquiryType == HELP)
		Usage_full();

	if (argc != 3)
		Usage();

	/* set up endian-ness */

	initializeState();

	/* stat file to get size and allocate buffers */

	firmwareFileName = argv[2];

	if (stat(firmwareFileName, &statBuf) < 0) {
		fprintf(stderr, "Error taking stat of file {%s}: %s\n",
			firmwareFileName, strerror(errno));
		exit(1);
	}

	fileSize = (int)statBuf.st_size;
	bufSize = fileSize + 1024; /* pad by 1K to be safe */
	if ((cmpBuffer = malloc(bufSize)) == NULL) {
		fprintf(stderr, "Error allocating memory for firmware buffer\n");
		goto fail;
	}
	if ((appBuffer = malloc(bufSize * 3)) == NULL) {
		fprintf(stderr, "Error allocating memory for inflated firmware buffer\n");
		goto fail;
	}

	memset(cmpBuffer, 0, bufSize);
	memset(appBuffer, 0, bufSize * 3);

	/* open file */
 
	if ((fpFirmwareFile = fopen(firmwareFileName, "rb")) == NULL)
	{
		fprintf(stderr, "Error opening file {%s} for input: %s\n",
			firmwareFileName, strerror(errno));
		goto fail;
	}

	if (0 == fread(&cssBuf, CSS_HEADER_SIZE, 1, fpFirmwareFile))
	{
		fprintf(stderr, "Error reading file {%s}: %s\n",
			firmwareFileName, strerror(errno));
		goto fail;
	}

	isSpkg = checkCssHeader(cssBuf);

	/* get first record, check if ICS image file */

	fseek(fpFirmwareFile, isSpkg ? CSS_HEADER_SIZE : 0, SEEK_SET);

	if (0 == fread(&firstRecordType, 4, 1, fpFirmwareFile))
	{
		fprintf(stderr, "Error reading file {%s}: %s\n",
			firmwareFileName, strerror(errno));
		goto fail;
	}

	fseek(fpFirmwareFile, isSpkg ? CSS_HEADER_SIZE : 0, SEEK_SET);

	if (ICS_IMAGE_HEADER_RECORD_TYPE_INFO != toHostEndian32(firstRecordType))
	{
		fprintf(stderr, "This is not a valid firmware image file\n");
		goto fail;
	}

	/* read in header, display what is asked for */

	if (ERR_OK != getRecord(fpFirmwareFile, &recordBuffer))
		goto fail;

	switch (inquiryType)
	{
		case SHOWVERSION:
			displayVersion(recordBuffer.payload.info.version);
			break;
		case SHOWTYPE:
			/*
			 * For the type, we really want to look for the embedded strings first.
			 * Call removeHeader, which will remove the ICS header from the package
			 * file and place it in the compressed buffer. Then call
			 * displayEmbeddedProdAndBsp which inflates and then searches. If the search
			 * fails, it is a pre-3.1.0.1 release, so feed the codes from the ICS header
			 * to displayType.
			 */
			result = removeHeader(argv[2], cmpBuffer);
			if (!displayEmbeddedProdAndBsp()) /* if this fails, try old way */
				displayType(toHostEndian32(recordBuffer.payload.info.productCode),
			    	        toHostEndian32(recordBuffer.payload.info.bspCode));
			break;
		default:
			fprintf(stderr, "Unknown inquiry type\n");
			goto fail;
	}

	fclose(fpFirmwareFile);
fail:
	if (cmpBuffer != NULL)
		free(cmpBuffer);
	if (appBuffer != NULL)
		free(appBuffer);
	exit(0);
}
Example #15
0
int main (int argc, char **argv)
{
	int ret = 1;


	/* Create application instance */
	QApplication qapp(argc, argv);

#ifdef Q_OS_WIN
	AllocConsole();
	freopen("CONOUT$", "wb", stdout);
#endif

	/* Print the version number */
	displayVersion();

	// scan command line arguments for a specified config file
	QString configFile;
	for (int i = 0; i < argc; i++)
	{
		if (argv[i][0] == '-' && argv[i][1] == 'o')
			configFile = argv[i + 1];
	}
	
	/* Create the session manager object with an optional user-specified
	 * configuration filename */
	SessionManager* sessionMgr = new SessionManager(configFile);

	// For now this will suffice
	pSEQPrefs = sessionMgr->preferences();

	// TODO: do something with this junk
	showeq_params = new ShowEQParams;

	QString section = "Interface";
	/* Allow map depth filtering */
	showeq_params->retarded_coords  = pSEQPrefs->getPrefBool("RetardedCoords", section, 0);
	showeq_params->systime_spawntime = pSEQPrefs->getPrefBool("SystimeSpawntime", section, false);
	showeq_params->pvp = pSEQPrefs->getPrefBool("PvPTeamColoring", section, false);
	showeq_params->deitypvp = pSEQPrefs->getPrefBool("DeityPvPTeamColoring", section, false);
	showeq_params->keep_selected_visible = pSEQPrefs->getPrefBool("KeepSelected", section, true);
	showeq_params->useUpdateRadius = pSEQPrefs->getPrefBool("UseUpdateRadius", section, false);

	section = "Misc";
	showeq_params->fast_machine = pSEQPrefs->getPrefBool("FastMachine", section, true);
	showeq_params->createUnknownSpawns = pSEQPrefs->getPrefBool("CreateUnknownSpawns", section, true);

	showeq_params->walkpathrecord = pSEQPrefs->getPrefBool("WalkPathRecording", section, false);
	showeq_params->walkpathlength = pSEQPrefs->getPrefInt("WalkPathLength", section, 25);
	/* Tells SEQ whether or not to display casting messages (Turn this off if you're on a big raid) */

	section = "SpawnList";
	showeq_params->showRealName = pSEQPrefs->getPrefBool("ShowRealName", section, false);

	/* Different files for different kinds of raw data */

	section = "SaveState";
	showeq_params->saveZoneState = pSEQPrefs->getPrefBool("ZoneState", section, 1);
	showeq_params->savePlayerState = pSEQPrefs->getPrefBool("PlayerState", section, 1);
	showeq_params->saveSpawns = pSEQPrefs->getPrefBool("Spawns", section, false);
	showeq_params->saveSpawnsFrequency = pSEQPrefs->getPrefInt("SpawnsFrequency", section, (120 * 1000));
	showeq_params->restorePlayerState = false;
	showeq_params->restoreZoneState = false;
	showeq_params->restoreSpawns = false;
	showeq_params->saveRestoreBaseFilename = sessionMgr->dataLocationMgr()->findWriteFile("tmp", pSEQPrefs->getPrefString("BaseFilename", section, "last")).absFilePath();
	showeq_params->filterZoneDataLog = 0;
	
#ifndef Q_OS_WIN
	parseArguments(argc, argv);		
#endif
#ifdef Q_WS_X11
	QColor::setAllowX11ColorNames(true);
#endif

	/* Create the main interface. */
	EQInterface* mainInterface = new EQInterface(sessionMgr);
	qapp.setMainWidget(mainInterface);
	
	/* Start the main program loop */
	ret = qapp.exec();
	
	// Clean up
	delete mainInterface;
	delete sessionMgr;
	
	return ret;
}
Example #16
0
void
gtBaseOpts::parse (int ac, char **av)
{
    bool haveRestrictConfigFile = !statFile (m_sys_restrict_cfg_file.c_str ());
    bool haveDefaultConfigFile = !statFile (m_sys_cfg_file.c_str ());
    bool haveUserConfigFile = false;

    try
    {
        add_options ();
        add_positionals ();

        bpo::command_line_parser parser (ac, av);
        parser.options (m_all_desc);
        parser.positional (m_pos);

        bpo::variables_map cli_vm; // CLI and non-restricted Config File options.
        bpo::variables_map res_vm; // Restricted Config File options.

        bpo::store (parser.run(), cli_vm);

        if (cli_vm.count (OPT_VERBOSE))
            m_haveVerboseOnCli = true;

        if (cli_vm.count (OPT_CFG_FILE))
            haveUserConfigFile = true;

        if (haveRestrictConfigFile)
            processConfigFile (m_sys_restrict_cfg_file, m_cfg_desc, res_vm);

        // Store config file variables on cli variables map
        if (haveRestrictConfigFile &&
            res_vm.count (OPT_NO_USER_CFG_FILE))
        {
            // Restricted config disallows user-supplied config file
            if (haveUserConfigFile)
                commandLineError ("Restricted configuration file disallows the "
                                  "use of the '" OPT_CFG_FILE "' option.");

            if (haveDefaultConfigFile)
                processConfigFile (m_sys_cfg_file, m_cfg_desc, cli_vm);
        }
        else
        {
            // Prefer user-supplied config file over default config file
            if (haveUserConfigFile)
            {
                std::string cfgPath = cli_vm[OPT_CFG_FILE].as<std::string>();
                processConfigFile (cfgPath, m_cfg_desc, cli_vm);
            }
            else if (haveDefaultConfigFile)
            {
                processConfigFile (m_sys_cfg_file, m_cfg_desc, cli_vm);
            }
        }

        if (haveRestrictConfigFile)
        {
            processConfigFile (m_sys_restrict_cfg_file, m_cfg_desc, cli_vm);
            checkForIllegalOverrides(res_vm, cli_vm);
        }
        // This call signals that the variables_map is now "finalized"
        // and calls notifiers to set variables to option values
        // (which we don't currently use)
        bpo::notify (cli_vm);

        m_vm = cli_vm;
    }
    catch (bpo::error &e)
    {
        std::ostringstream msg ("Options Error: ");
        msg << e.what();
        commandLineError (msg.str());
    }

    if (m_vm.count (OPT_HELP))
        displayHelp ();

    if (m_vm.count (OPT_VERSION))
        displayVersion ();

    processOptions ();

//    log_options_used ();
}