示例#1
0
Talent::Name Class::loseARandomLeafTalent() {
  auto candidates = std::vector<const Talent *>{};
  for (const auto &pair : _talentRanks) {
    if (isLeafTalent(*pair.first)) candidates.push_back(pair.first);
  }

  if (candidates.empty()) return {};

  auto indexToDrop = rand() % candidates.size();
  auto talentToDrop = candidates[indexToDrop];

  --_talentRanks[talentToDrop];
  --_talentPointsAllocated;

  _owner->sendMessage(
      SV_TALENT, makeArgs(talentToDrop->name(), _talentRanks[talentToDrop]));
  _owner->sendMessage(
      SV_POINTS_IN_TREE,
      makeArgs(talentToDrop->tree(), pointsInTree(talentToDrop->tree())));

  if (talentToDrop->type() == Talent::SPELL)
    _owner->sendMessage(SV_UNLEARNED_SPELL, talentToDrop->spellID());

  return talentToDrop->name();
}
示例#2
0
void ContainerGrid::rightMouseUp(Element &e, const ScreenPoint &mousePos) {
  ContainerGrid &grid = dynamic_cast<ContainerGrid &>(e);
  size_t slot = grid.getSlot(mousePos);
  if (dragSlot != NO_SLOT) {  // Cancel dragging
    dragSlot = NO_SLOT;
    dragGrid = nullptr;
    Client::_instance->onChangeDragItem();
    grid.markChanged();
  }
  if (useSlot != NO_SLOT) {  // Right-clicked instead of used: cancel use
    useSlot = NO_SLOT;
    useGrid = nullptr;
  } else if (slot != NO_SLOT) {  // Right-clicked a slot
    const ClientItem *item = grid._linked[slot].first;
    if (item != nullptr) {  // Slot is not empty
      if (grid._serial == Client::INVENTORY) {
        if (item->canUse()) {
          useSlot = slot;
          useGrid = &grid;
        } else if (item->gearSlot() < Client::GEAR_SLOTS) {
          Client::_instance->sendMessage(
              CL_SWAP_ITEMS, makeArgs(Client::INVENTORY, slot, Client::GEAR,
                                      item->gearSlot()));
          if (item->sounds() != nullptr) item->sounds()->playOnce("drop");
        }
      } else {  // An object: take item
        Client::_instance->sendMessage(CL_TAKE_ITEM,
                                       makeArgs(grid._serial, slot));
        if (item->sounds() != nullptr) item->sounds()->playOnce("drop");
      }
    }
  }
  grid._rightMouseDownSlot = NO_SLOT;
}
示例#3
0
int SP_HiveDBProtocol :: removeJson( int dbfile, const char * user,
		const char * dbname, int * result )
{
	SP_JsonArrayNode params;
	{
		SP_JsonObjectNode * args = new SP_JsonObjectNode();

		makeArgs( args, dbfile, user, dbname );

		params.addValue( args );
	}

	SP_JsonStringBuffer buffer;

	SP_JsonRpcUtils::toReqBuffer( "remove", user, &params, &buffer );

	SP_NKHttpResponse httpResp;

	int ret = clientCall( mSocket, "/sphivedb", mIsKeepAlive,
			buffer.getBuffer(), buffer.getSize(), &httpResp );

	if( 0 == ret ) {
		SP_JsonRpcRespObject respObj( (char*)httpResp.getContent(),
				httpResp.getContentLength() );

		SP_JsonHandle handle( respObj.getResult() );
		SP_JsonIntNode * resultNode = handle.toInt();

		*result = ( NULL != resultNode ) ? resultNode->getValue() : -1;
	}

	return ret;
}
示例#4
0
int SP_HiveDBProtocol :: removeProtoBuf( int dbfile, const char * user,
		const char * dbname, int * result )
{
	SP_ProtoBufEncoder params;
	{
		makeArgs( &params, dbfile, user, dbname );
	}

	SP_ProtoBufEncoder reqEncoder;

	SP_ProtoBufRpcUtils::initReqEncoder( &reqEncoder, "remove", user );

	reqEncoder.addBinary( SP_ProtoBufRpcReqObject::eParams,
			params.getBuffer(), params.getSize() );

	SP_NKHttpResponse httpResp;

	int ret = clientCall( mSocket, "/sphivedb/protobuf", mIsKeepAlive,
			reqEncoder.getBuffer(), reqEncoder.getSize(), &httpResp );

	if( 0 == ret ) {
		SP_ProtoBufDecoder decoder;
		decoder.copyFrom( (char*)httpResp.getContent(), httpResp.getContentLength() );

		SP_ProtoBufDecoder::KeyValPair_t pair;
		if( decoder.find( SP_ProtoBufRpcRespObject::eResult, &pair ) ) {
			*result = pair.m32Bit.s;
		}
	} else {
		SP_NKLog::log( LOG_WARNING, "clientCall %d", ret );
	}

	return ret;
}
示例#5
0
/*------------------------------------------------------------------------------
 *  Start the encoding
 *----------------------------------------------------------------------------*/
bool
ExternalEncoder :: start ( void )           throw ( Exception )
{
    pid_t   pid;

    if ( isRunning() ) {
        return false;
    }

    pid = fork();

    if ( pid == -1 ) {
        throw Exception( __FILE__, __LINE__, "fork error");
    } else if ( pid == 0 ) {
        cout << "wow, I'm a voodoo child!" << endl;

        makeArgs();
        execvp( getEncoderName(), cmdArgs);

        throw Exception( __FILE__, __LINE__, "exec returned");
    } else {
        child = pid;
        cout << "I'm a parent, the child's pid is " << child << endl;

        return true;
    }
}
示例#6
0
const Tooltip &ClientObjectType::constructionTooltip() const {
  if (_constructionTooltip.hasValue()) return _constructionTooltip.value();

  const auto &client = *Client::_instance;

  _constructionTooltip = Tooltip{};
  auto &tooltip = _constructionTooltip.value();
  tooltip.setColor(Color::TOOLTIP_NAME);
  tooltip.addLine(_name);

  auto descriptionLines = std::vector<std::string>{};

  auto gapDrawn = false;

  if (isDebug()) descriptionLines.push_back(id());

  if (canGather()) {
    std::string text = "Gatherable";
    if (!gatherReq().empty())
      text += " (requires " + client.tagName(gatherReq()) + ")";
    descriptionLines.push_back(text);
  }

  if (canDeconstruct()) descriptionLines.push_back("Can pick up as item");

  if (containerSlots() > 0)
    descriptionLines.push_back("Container: " + toString(containerSlots()) +
                               " slots");

  if (merchantSlots() > 0)
    descriptionLines.push_back("Merchant: " + toString(merchantSlots()) +
                               " slots");

  if (!descriptionLines.empty()) tooltip.addGap();
  for (const auto &line : descriptionLines) tooltip.addLine(line);

  // Tags
  if (hasTags()) {
    tooltip.addGap();
    tooltip.setColor(Color::TOOLTIP_TAG);
    for (const std::string &tag : tags()) tooltip.addLine(client.tagName(tag));
  }

  tooltip.addGap();
  tooltip.setColor(Color::TOOLTIP_BODY);
  tooltip.addLine("Construction materials:");
  for (const auto &material : _materials) {
    const ClientItem &item = *dynamic_cast<const ClientItem *>(material.first);
    tooltip.addLine(makeArgs(material.second) + "x " + item.name());
  }

  if (!_constructionReq.empty()) {
    tooltip.addGap();
    tooltip.addLine("Requires tool: " + client.tagName(_constructionReq));
  }

  return tooltip;
}
示例#7
0
void Class::takeTalent(const Talent *talent) {
  ++_talentPointsAllocated;

  if (_talentRanks.find(talent) == _talentRanks.end()) {
    _talentRanks[talent] = 1;
  } else {
    if (talent->type() != Talent::STATS && _talentRanks[talent] > 0) {
      SERVER_ERROR("Can't take a second rank of a non-stats talent");
      return;
    }
    ++_talentRanks[talent];
  }

  _owner->sendMessage(SV_TALENT,
                      makeArgs(talent->name(), _talentRanks[talent]));
  _owner->sendMessage(SV_POINTS_IN_TREE,
                      makeArgs(talent->tree(), pointsInTree(talent->tree())));
}
示例#8
0
void ContainerGrid::refresh() {
  renderer.setDrawColor(Color::BLACK);
  for (size_t i = 0; i != _linked.size(); ++i) {
    const px_t x = i % _cols, y = i / _cols;
    const auto slotRect =
        ScreenRect{x * (Client::ICON_SIZE + _gap + 2),
                   y * (Client::ICON_SIZE + _gap + 2) + 1,
                   Client::ICON_SIZE + 2, Client::ICON_SIZE + 2};
    if (_solidBackground) {
      static const auto SLOT_BACKGROUND_OFFSET = ScreenRect{1, 1, -2, -2};
      renderer.fillRect(slotRect + SLOT_BACKGROUND_OFFSET);
    }
    if (dragSlot != i ||
        dragGrid != this) {  // Don't draw an item being moved by the mouse.
      const std::pair<const ClientItem *, size_t> &slot = _linked[i];
      if (slot.first != nullptr) {
        slot.first->icon().draw(slotRect.x + 1, slotRect.y + 1);
        if (slot.second > 1) {
          Texture label(font(), makeArgs(slot.second), FONT_COLOR),
              labelOutline(font(), toString(slot.second), Color::UI_OUTLINE);
          px_t x = slotRect.x + slotRect.w - label.width() - 1,
               y = slotRect.y + slotRect.h - label.height() + textOffset;
          labelOutline.draw(x - 1, y);
          labelOutline.draw(x + 1, y);
          labelOutline.draw(x, y - 1);
          labelOutline.draw(x, y + 1);
          label.draw(x, y);
        }
      }
    }

    // Highlight moused-over slot
    if (_mouseOverSlot == i) {
      _highlight.draw(slotRect.x + 1, slotRect.y + 1);

      // Indicate matching gear slot if an item is being dragged
    } else if (_serial == Client::GEAR && dragGrid != nullptr) {
      size_t itemSlot = dragGrid->_linked[dragSlot].first->gearSlot();
      (i == itemSlot ? _highlightGood : _highlightBad)
          .draw(slotRect.x + 1, slotRect.y + 1);
    }
  }

  // Item tooltip
  if (_mouseOverSlot != NO_SLOT) {
    const ClientItem *item = _linked[_mouseOverSlot].first;
    if (item == nullptr)
      clearTooltip();
    else
      setTooltip(item->tooltip());
  }
}
示例#9
0
void
uio_debugInteractive(FILE *in, FILE *out, FILE *err) {
    char lineBuf[LINEBUFLEN];
    size_t lineLen;
    int argc;
    char **argv;
    DebugContext debugContext;
    uio_bool interactive;

    memset(&debugContext, '\0', sizeof (DebugContext));
    debugContext.exit = false;
    debugContext.in = in;
    debugContext.out = out;
    debugContext.err = err;
    debugContext.cwd = uio_openDir(repository, "/", 0);
    if (debugContext.cwd == NULL) {
        fprintf(err, "Fatal: Could not open working dir.\n");
        abort();
    }

    interactive = isatty(fileno(in));
    do {
        if (interactive)
            fprintf(out, "> ");
        if (fgets(lineBuf, LINEBUFLEN, in) == NULL) {
            if (feof(in)) {
                // user pressed ^D
                break;
            }
            // error occured
            clearerr(in);
            continue;
        }
        lineLen = strlen(lineBuf);
        if (lineBuf[lineLen - 1] != '\n' && lineBuf[lineLen - 1] != '\r') {
            fprintf(err, "Too long command line.\n");
            // TODO: read until EOL
            continue;
        }
        makeArgs(lineBuf, &argc, &argv);
        if (argc == 0) {
            uio_free(argv);
            continue;
        }
        debugCallCommand(&debugContext, argc, argv);
        uio_free(argv);
    } while (!debugContext.exit);
    if (interactive)
        fprintf(out, "\n");
    uio_closeDir(debugContext.cwd);
}
示例#10
0
void ContainerGrid::leftMouseUp(Element &e, const ScreenPoint &mousePos) {
  ContainerGrid &grid = dynamic_cast<ContainerGrid &>(e);
  size_t slot = grid.getSlot(mousePos);
  if (slot != NO_SLOT) {  // Clicked a valid slot
    size_t mouseDownSlot = grid._leftMouseDownSlot;
    grid._leftMouseDownSlot = NO_SLOT;

    // Enforce gear slots
    if (dragGrid != nullptr) {
      if (dragGrid->_serial == Client::GEAR) {  // From gear slot
        const ClientItem *item = grid._linked[slot].first;
        if (item != nullptr && item->gearSlot() != dragSlot) return;
      } else if (grid._serial == Client::GEAR) {  // To gear slot
        const ClientItem *item = dragGrid->_linked[dragSlot].first;
        if (item != nullptr && item->gearSlot() != slot) return;
      }
    }

    // Different grid/slot: finish dragging.
    if ((dragGrid != &grid || dragSlot != slot) && dragSlot != NO_SLOT) {
      Client::_instance->sendMessage(
          CL_SWAP_ITEMS,
          makeArgs(dragGrid->_serial, dragSlot, grid._serial, slot));
      const ClientItem *item = dragGrid->_linked[dragSlot].first;
      if (item != nullptr && item->sounds() != nullptr)
        item->sounds()->playOnce("drop");

      dragSlot = NO_SLOT;
      dragGrid = nullptr;
      Client::_instance->onChangeDragItem();

      // Dragging to same grid/slot; do nothing.
    } else if (slot == dragSlot && &grid == dragGrid) {
      dragSlot = NO_SLOT;
      dragGrid = nullptr;
      Client::_instance->onChangeDragItem();
      grid.markChanged();

      // Same grid and slot that mouse went down on and slot isn't empty: start
      // dragging.
    } else if (mouseDownSlot == slot && grid._linked[slot].first) {
      dragSlot = slot;
      dragGrid = &grid;
      Client::_instance->onChangeDragItem();
      grid.markChanged();
    }
  }
}
示例#11
0
/*
 * Here as the child process to try to execute the command.
 * This is only called if there are no meta-characters in the command.
 * This procedure never returns.
 */
static void
childProcess(const char * cmd)
{
	const char **	argv;
	int		argc;
	
	/*
	 * Close any extra file descriptors we have opened.
	 */	
	while (--sourceCount >= 0)
	{
		if (sourcefiles[sourceCount] != stdin)
			fclose(sourcefiles[sourceCount]);
	}
	
	/*
	 * Break the command line up into individual arguments.
	 * If this fails, then run the shell to execute the command.
	 */
	if (!makeArgs(cmd, &argc, &argv))
	{
		system(cmd);
		exit(0);
	}
	
	/*
	 * Try to execute the program directly.
	 */
	execvp(argv[0], (char **) argv);
	
	/*
	 * The exec failed, so try to run the command using the shell
	 * in case it is a shell script.
	 */
	if (errno == ENOEXEC)
	{
		system(cmd);
		exit(0);
	}
	
	/*
	 * There was something else wrong, complain and exit.
	 */
	perror(argv[0]);
	exit(1);
}
示例#12
0
SP_HiveRespObject * SP_HiveDBProtocol :: executeJson( int dbfile, const char * user,
		const char * dbname, SP_NKStringList * sql )
{
	SP_JsonArrayNode params;
	{
		SP_JsonObjectNode * args = new SP_JsonObjectNode();

		makeArgs( args, dbfile, user, dbname );

		SP_JsonArrayNode * sqlNode = new SP_JsonArrayNode();

		for( int i = 0; i < sql->getCount(); i++ ) {
			sqlNode->addValue( new SP_JsonStringNode( sql->getItem( i ) ) );
		}

		SP_JsonPairNode * sqlPair = new SP_JsonPairNode();
		sqlPair->setName( "sql" );
		sqlPair->setValue( sqlNode );

		args->addValue( sqlPair );

		params.addValue( args );
	}

	SP_JsonStringBuffer buffer;

	SP_JsonRpcUtils::toReqBuffer( "execute", user, &params, &buffer );

	SP_HiveRespObject * resp = NULL;

	SP_NKHttpResponse httpResp;

	int ret = clientCall( mSocket, "/sphivedb", mIsKeepAlive,
			buffer.getBuffer(), buffer.getSize(), &httpResp );

	if( 0 == ret ) {
		SP_JsonRpcRespObject * inner = new SP_JsonRpcRespObject(
				(char*)httpResp.getContent(), httpResp.getContentLength() );
		resp = new SP_HiveRespObjectJson( inner, 1 );
	} else {
		SP_NKLog::log( LOG_WARNING, "clientCall %d", ret );
	}

	return resp;
}
示例#13
0
void EditorInterface::run()
{
	FNTRACE("", "EditorInterface", "run", "");
	assert(!editorProcess || editorProcess->state() == QProcess::NotRunning);

	if (!(QFileInfo(editorDir.filePath(editorName))).exists())
		ETHROW(Exception("The Loader can't find the Ds1 Editor. "
			"You must setup the Loader's ini to select where the Ds1 Editor .exe is. "
			"Use the menu \"Settings->Configure Loader\"."));

	QDir temp = QDir::temp();
	int i = 0;
	// find first tempX.ini that doesn't exist in temporary directory
	while (QFileInfo(temp.filePath(QString("temp%1.ini").arg(i))).exists())
		++i;

	if (!editorProcess)
		editorProcess = new QProcess(this);

	fileName = temp.filePath(QString("temp%1").arg(i));
	makeRelativePaths();
	QStringList args = makeArgs();

	output->clear();
	output->insertPlainText("ds1edit Loader: starting editor using program\n");
	output->insertPlainText(editorDir.filePath(editorName));
	output->insertPlainText("\nand arguments\n\"");
	output->insertPlainText(args.join("\" \""));

	connect(editorProcess, SIGNAL(finished(int, QProcess::ExitStatus)),
		SLOT(terminated(int, QProcess::ExitStatus)));
	connect(editorProcess, SIGNAL(readyReadStandardOutput()),
		SLOT(editorOutputReady()));

	editorProcess->setWorkingDirectory(editorDir.absolutePath());
	output->insertPlainText("\"\nStarting from directory: ");
	output->insertPlainText(editorProcess->workingDirectory());
	output->insertPlainText("\n\n");

	editorProcess->start(editorDir.filePath(editorName), args, QIODevice::ReadOnly | QIODevice::Text);
	//if (!editorProcess->waitForStarted())
	//	ETHROW(Exception("Editor process failed to start"));
}
示例#14
0
void EditorInterface::makeBatch(QString& batchFileName)
{
	FNTRACE("", "EditorInterface", "batchFileName", batchFileName);

	if (batchFileName.endsWith(".bat", Qt::CaseInsensitive))
		fileName = batchFileName.left(batchFileName.length()-4);
	else
		fileName = batchFileName;

	makeRelativePaths();

	batchFileName = fileName+".bat";
	QString debugFileName = fileName + "_debug.txt";

	QStringList args = makeArgs();

	QFile batchFile(batchFileName);
	if (!batchFile.open(QIODevice::WriteOnly | QIODevice::Text))
		ETHROW(Exception(QString("Failed to open %1 for writing").arg(batchFileName)));
	QTextStream batch(&batchFile);

	batch << "@echo off\n";
	if (QDir::drives().size()>1)
		batch << editorDir.absolutePath().left(2) << "\n";
	batch << "cd \"" << editorDir.absolutePath() << "\"\n" << editorName;
	for (QStringList::iterator arg = args.begin(); arg != args.end(); ++arg)
	{
		batch << ' ';
		if (arg->contains(' '))
			batch << '"'+(*arg)+'"';
		else
			batch << (*arg);
	}
	batch << " > \"" << debugFileName << "\"\n"
			"If ERRORLEVEL 0 goto DONE\n"
			"pause\n"
			":DONE\n";
}
示例#15
0
SP_HiveRespObject * SP_HiveDBProtocol :: executeProtoBuf( int dbfile, const char * user,
		const char * dbname, SP_NKStringList * sql )
{
	SP_ProtoBufEncoder params;
	{
		makeArgs( &params, dbfile, user, dbname );

		for( int i = 0; i < sql->getCount(); i++ ) {
			params.addString( SP_HiveReqObjectProtoBuf::eSQL, sql->getItem(i) );
		}
	}

	SP_ProtoBufEncoder reqEncoder;

	SP_ProtoBufRpcUtils::initReqEncoder( &reqEncoder, "execute", user );

	reqEncoder.addBinary( SP_ProtoBufRpcReqObject::eParams,
			params.getBuffer(), params.getSize() );

	SP_HiveRespObjectProtoBuf * resp = NULL;

	SP_NKHttpResponse httpResp;

	int ret = clientCall( mSocket, "/sphivedb/protobuf", mIsKeepAlive,
			reqEncoder.getBuffer(), reqEncoder.getSize(), &httpResp );

	if( 0 == ret ) {
		SP_ProtoBufRpcRespObject * inner = new SP_ProtoBufRpcRespObject();
		inner->copyFrom( (char*)httpResp.getContent(), httpResp.getContentLength() );
		resp = new SP_HiveRespObjectProtoBuf( inner, 1 );
	} else {
		SP_NKLog::log( LOG_WARNING, "clientCall %d", ret );
	}

	return resp;
}
示例#16
0
void Permissions::alertNearbyUsersToNewOwner() const {
  auto &server = *Server::_instance;
  server.broadcastToArea(
      _parent.location(), SV_OWNER,
      makeArgs(_parent.serial(), _owner.typeString(), _owner.name));
}
示例#17
0
/*
 * Try to execute a built-in command.
 * Returns TRUE if the command is a built in, whether or not the
 * command succeeds.  Returns FALSE if this is not a built-in command.
 */
static BOOL
tryBuiltIn(const char * cmd)
{
	const char *		endCmd;
	const CommandEntry *	entry;
	int			argc;
	const char **		argv;
	char			cmdName[CMD_LEN];
	
	/*
	 * Look for the end of the command name and then copy the
	 * command name to a buffer so we can null terminate it.
	 */
	endCmd = cmd;
	
	while (*endCmd && !isBlank(*endCmd))
		endCmd++;
	
	memcpy(cmdName, cmd, endCmd - cmd);
	
	cmdName[endCmd - cmd] = '\0';
	
	/*
	 * Search the command table looking for the command name.
	 */
	for (entry = commandEntryTable; entry->name != NULL; entry++)
	{
		if (strcmp(entry->name, cmdName) == 0)
			break;
	}
	
	/*
	 * If the command is not a built-in, return indicating that.
	 */
	if (entry->name == NULL)
		return FALSE;
	
	/*
	 * The command is a built-in.
	 * Break the command up into arguments and expand wildcards.
	 */
	if (!makeArgs(cmd, &argc, &argv))
		return TRUE;
	
	/*
	 * Give a usage string if the number of arguments is too large
	 * or too small.
	 */
	if ((argc < entry->minArgs) || (argc > entry->maxArgs))
	{
		fprintf(stderr, "usage: %s %s\n", entry->name, entry->usage);
		
		return TRUE;
	}
	
	/*
	 * Call the built-in function with the argument list.
	 */
	entry->func(argc, argv);
	
	return TRUE;
}
示例#18
0
文件: main.c 项目: digideskio/afdko
/* Parse argument list */
static void parseArgs(int argc, char *argv[], int inScript) {
	int i;
	char *outputOTFfilename = NULL;
	char *pfbfile = "font.ps";
	convert.features = NULL;
	convert.maxNumSubrs = 0;
	convert.flags |= HOT_NO_OLD_OPS;	/* always remove old ops */
	convert.licenseID = NULL;
	for (i = 0; i < argc; i++) {
		int argsleft = argc - i - 1;
		char *arg = argv[i];
		switch (arg[0]) {
			case '-':
				/* Process regular and disabling options */
				switch (arg[1]) {
					case 'D': {
						/* Process list of debug args */
						int j = 2;
						do {
							switch (arg[j]) {
								case 'a':	/* [-Da] AFM debug */
									convert.flags |= HOT_DB_AFM;
									break;

								case 'f':	/* [-Df] Features debug level 1 */
									convert.flags |= HOT_DB_FEAT_1;
									break;

								case 'F':	/* [-DF] Features debug level 2 */
									convert.flags |= HOT_DB_FEAT_2;
									break;

								case 'm':	/* [-Dm] Map debug */
									convert.flags |= HOT_DB_MAP;
									break;

								default:
									cbFatal(cbctx, "unrecognized debug option (%s)", arg);
							}
						} while (arg[++j] != '\0');
					}
					break;

					case 'a':	/* adding glyphs */
						if (!strcmp(arg, "-addn")) {
							convert.flags |= HOT_FORCE_NOTDEF;
						}
						else if (!strcmp(arg, "-adds")) {
							convert.flags |= HOT_ADD_EURO;
							convert.addGlyphWeight = 0;
							if (argsleft > 0) {
								int value =  atoi(argv[i]);
								if ((value != 0) || (!strcmp(arg, "0"))) {
									convert.addGlyphWeight = value;
									i++;
								}
							}
						}
						else {
							cbFatal(cbctx, "unrecognized option (%s)", arg);
						}

						break;

					case 'b':
						convert.otherflags |= OTHERFLAGS_ISWINDOWSBOLD;
						break;

					case 'c':	/* Adobe CMap directory */
						switch (arg[2]) {
							case '\0':	/* [-c] CMap directory */
								if (argsleft == 0) {
									showUsage();
								}
								dircpy(convert.dir.cmap, argv[++i]);
								break;

							case 'h':	/* [-ch] Horizontal CMap */
								if (arg[3] != '\0' || argsleft == 0) {
									showUsage();
								}
								convert.hCMap = argv[++i];
								break;

							case 'i':	/* [-ci] UVS map */
								if (arg[3] != '\0' || argsleft == 0) {
									showUsage();
								}
								convert.uvsFile = argv[++i];
								break;

							case 'v':	/* [-cv] Vertical CMap */
								if (arg[3] != '\0' || argsleft == 0) {
									showUsage();
								}
								convert.vCMap = argv[++i];
								break;

							case 'm':	/* [-cm] Mac Adobe CMap */
								if (arg[3] != '\0' || argsleft == 0) {
									showUsage();
								}
								convert.mCMap = argv[++i];
								break;

							case 's':	/* [-cs] Mac Adobe CMap script id */
								if (arg[3] != '\0' || argsleft == 0) {
									showUsage();
								}
								convert.macScript = atoi(argv[++i]);
								break;

							case 'l':	/* [-cl] Mac Adobe CMap script id */
								if (arg[3] != '\0' || argsleft == 0) {
									showUsage();
								}
								convert.macLanguage = atoi(argv[++i]);
								break;

							default:
								cbFatal(cbctx, "unrecognized option (%s)", arg);
						}
						break;

					case 'd':
						switch (arg[2]) {
							case 'b':
								if (arg[3] != 'l' ||  arg[4] != '\0') {
									cbFatal(cbctx, "unrecognized option (%s)", arg);
								}
								else {
									convert.otherflags |= OTHERFLAGS_DOUBLE_MAP_GLYPHS;
								}
								break;

							case 'c':
								if (arg[3] != 's' ||  arg[4] != '\0') {
									cbFatal(cbctx, "unrecognized option (%s)", arg);
								}
								else {
									convert.otherflags |= OTHERFLAGS_OLD_SPACE_DEFAULT_CHAR;
								}
								break;

							default:
								cbFatal(cbctx, "unrecognized option (%s)", arg);
						}
						break;

					case 'f':
						switch (arg[2]) {
							case '\0':	/* [-f] Process file list */

								if (argsleft == 0) {
									showUsage();
								}
								else {
									pfbfile = argv[++i];
								}
								break;

							case 'c':
								/* [-fc] Force ID2 (incorrect) reading of backtrack string in changing context substitution. */
								convert.otherflags |= OTHERFLAGS_DO_ID2_GSUB_CHAIN_CONXT;
								break;

							case 'd':	/* [-fd] Standard feature directory */
								if (arg[3] != '\0' || argsleft == 0) {
									showUsage();
								}
								dircpy(convert.dir.feat, argv[++i]);
								break;

							case 'f':	/* [-ff] Feature file */
								if (arg[3] != '\0' || argsleft == 0) {
									showUsage();
								}
								convert.features = argv[++i];
								break;

							case 's':
								/* [-fs] If there are no GSUB rules, make a stub GSUB table */
								convert.otherflags |= OTHERFLAGS_ALLOW_STUB_GSUB;
								break;

							default:
								cbFatal(cbctx, "unrecognized option (%s)", arg);
						}
						break;

					case 'g':				/* Glyph name alias database */
						switch (arg[2]) {
							case 'f':	/* [-c] CMap directory */
								if (arg[3] != '\0' || argsleft == 0) {
									showUsage();
								}
								cbAliasDBRead(cbctx, argv[++i]);
								break;

							case 'a':
								convert.flags |= HOT_RENAME;
								break;

							case 's':
								convert.flags |= HOT_SUBSET;
								break;

							default:
								cbFatal(cbctx, "unrecognized option (%s)", arg);
						}
						break;

					case 'i':
						convert.otherflags |= OTHERFLAGS_ISITALIC;
						break;

					case 'l':
						if (!strcmp(arg, "-lic")) {
							convert.licenseID = argv[++i];
						}
						else {
							cbFatal(cbctx, "unrecognized option (%s)", arg);
						}
						break;

					case 'm':	/* Font conversion database */
						switch (arg[2]) {
							case 'f':	/* [-c] CMap directory */
								if (arg[3] != '\0' || argsleft == 0) {
									showUsage();
								}
								cbFCDBRead(cbctx, argv[++i]);
								break;

							case 'a':
								if ((arg[3] != 'x') || (arg[4] != 's') || (arg[5] != '\0') || argsleft == 0) {
									showUsage();
								}
								convert.maxNumSubrs = atoi(argv[++i]);
								break;

							default:
								cbFatal(cbctx, "unrecognized option (%s)", arg);
						}
						break;

					case 'o':		/* OTF filename*/
						if (arg[2] == '\0') {
							if (argsleft == 0) {
								showUsage();
							}
							outputOTFfilename = argv[++i];
							break;
						}

						else if (0 == strcmp(arg, "-oldNameID4")) {
							convert.otherflags |= OTHERFLAGS_OLD_NAMEID4;
                            if (convert.otherflags & OTHERFLAGS_OMIT_MAC_NAMES)
                                cbFatal(cbctx, "You cannot specify both -omitMacNames and -oldNameID4.");
							break;
						}


						else if (0 == strcmp(arg, "-omitMacNames")) {
							convert.otherflags |= OTHERFLAGS_OMIT_MAC_NAMES;
                            if (convert.otherflags & OTHERFLAGS_OLD_NAMEID4)
                                cbFatal(cbctx, "You cannot specify both -omitMacNames and -oldNameID4.");
							break;
						}
                        
						else if (0 == strcmp(arg, "-overrideMenuNames")) {
							convert.otherflags |= OTHERFLAGS_OVERRIDE_MENUNAMES;
							break;
						}
                        
                        
						switch (arg[2]) {
							case 's': {
								short val;
								if (0 == strcmp(arg, "-osbOn")) {
									val = atoi(argv[++i]);
									if ((val < 0) || (val > 15)) {
										cbFatal(cbctx, "The bit index value for option (-%s) must be an integer number between 0 and 15 (%s)", arg);
									}
									if (convert.fsSelectionMask_on >= 0) {
										convert.fsSelectionMask_on |= 1 << val;
									}
									else {
										convert.fsSelectionMask_on = 1 << val;
									}
								}
								else if (0 == strcmp(arg, "-osbOff")) {
									val = atoi(argv[++i]);
									if (val < 1) {
										cbFatal(cbctx, "The OS/2 table version value for option (-%s) must be an integer number greater than 0 (%s)", arg);
									}
									if (convert.fsSelectionMask_off >= 0) {
										convert.fsSelectionMask_off |= 1 << val;
									}
									else {
										convert.fsSelectionMask_off = 1 << val;
									}
								}
								else if (0 == strcmp(arg, "-osv")) {
									val = atoi(argv[++i]);
									if (val < 1) {
										cbFatal(cbctx, "The OS/2 table version value for option (-%s) must be an integer number greater than 0 (%s)", arg);
									}
									convert.os2_version = val;
								}
								else {
									cbFatal(cbctx, "unrecognized option (%s)", arg);
								}
								break;
							}

							default:
								cbFatal(cbctx, "unrecognized option (%s)", arg);
						}
						break;

					case 'n':	/* all the 'off' settings */
						switch (arg[2]) {
							case 'g': {
								if (arg[4] != '\0') {
									showUsage();
								}
								if (arg[3] == 'a') {
									convert.flags &= ~HOT_RENAME;
									/* just in case the GOADB has already been read in */
									cbAliasDBCancel(cbctx);
								}
								if (arg[3] == 's') {
									convert.flags &= ~HOT_SUBSET;
									/* just in case the GOADB has already been read in */
								}

								break;
							}

							case 'S':
								if (arg[3] != '\0') {
									showUsage();
								}
								convert.flags &= ~HOT_SUBRIZE;
								break;

							default:
								cbFatal(cbctx, "unrecognized option (%s)", arg);
						}
						break;

					case 's':	/* Process script file */
						if (!strcmp(arg, "-serif")) {
							convert.flags &= ~HOT_IS_SANSSERIF;
							convert.flags |= HOT_IS_SERIF;
						}
						else if (!strcmp(arg, "-sans")) {
							convert.flags |= HOT_IS_SANSSERIF;
							convert.flags &= ~HOT_IS_SERIF;
						}
						else if (!strcmp(arg, "-shw")) {
							convert.flags |= HOT_SUPRESS_HINT_WARNINGS;
						}
						else if (!strcmp(arg, "-swo")) {
							convert.flags |= HOT_SUPRESS__WIDTH_OPT;
						}
                        
						else if (!strcmp(arg, "-stubCmap4")) {
							convert.otherflags |= OTHERFLAGS_STUB_CMAP4;
						}
						else if (!strcmp(arg, "-skco")) {
							convert.otherflags |= OTHERFLAGS_DO_NOT_OPTIMIZE_KERN;
							break;
						}
						else {
							/* Process script file */
							if (arg[2] != '\0' || argsleft == 0) {
								showUsage();
							}
							if (inScript) {
								cbFatal(cbctx, "can't nest scripts");
							}
							if (script.buf != NULL) {
								cbFatal(cbctx, "can't have multiple scripts");
							}
							makeArgs(argv[++i]);
							parseArgs(script.args.cnt, script.args.array, 1);
						}
						break;

/*	This is left over from when Morisawa was demanding font protection mechanims.
            case 'A':
                convert.flags |= HOT_ADD_AUTH_AREA;
                break;
            case 'a':
                convert.flags &= ~HOT_ADD_AUTH_AREA;
                break;
 */
					case 'r':
						convert.otherflags |= OTHERFLAGS_RELEASEMODE;
						convert.flags |= HOT_RENAME;
						convert.flags |= HOT_SUBRIZE;
						break;

/* No longer supported - not used enough
            case 'K':
                KeepGoing = 1;
                break;
 */
					case 'S':
						convert.flags |= HOT_SUBRIZE;
						break;

/* I now always set this flag; see start of this function.
            case 'z':
                convert.flags &= ~HOT_NO_OLD_OPS;
                break;
 */
					case 'u':
						showUsage();
						break;

					case 't':
					case 'h':
						showHelp();
						break;

					default:
						cbFatal(cbctx, "unrecognized option (%s)", arg);
				}
				break;

			case '+':
				/* Process enabling options */
				switch (arg[1]) {
/*	This is left over from when Morisawa was demanding font protection mechanims.
        case 'a':
                convert.flags |= HOT_ADD_AUTH_AREA;
                break;
 */
/* I now always remove old ops, and don't bother with warning.
            case 'z':
                convert.flags |= HOT_NO_OLD_OPS;
                break;
 */
					default:
						cbFatal(cbctx, "unrecognized option (%s)", arg);
				}
				break;

			default:			/* Non-option arg is taken to be filename */
				cbFatal(cbctx, "unrecognized option (%s)", arg);
				break;
		}
	}
	if (!convert.fontDone) {
		convFont(pfbfile, outputOTFfilename);
	}

	convert.fontDone = 1;
}
示例#19
0
void City::addAndAlertPlayers(const User &user) {
  _members.insert(user.name());
  user.sendMessage(SV_JOINED_CITY, _name);
  Server::instance().broadcastToArea(user.location(), SV_IN_CITY,
                                     makeArgs(user.name(), _name));
}
示例#20
0
TEST_CASE("A user can't build multiple player-unique objects") {
  // Given "blonde" and "readhead" object types,
  // And each is marked with the "wife" player-unique category,
  auto s = TestServer::WithData("wives");

  // And Bob has a blonde wife
  s.addObject("blonde", {}, "Bob");

  SECTION("Bob can't have a second wife") {
    // When Bob logs in,
    auto c = TestClient::WithUsernameAndData("Bob", "wives");
    s.waitForUsers(1);

    // And tries to get a readhead wife
    c.sendMessage(CL_CONSTRUCT, makeArgs("redhead", 10, 15));

    // Then Bob receives an error message,
    c.waitForMessage(WARNING_UNIQUE_OBJECT);

    // And there is still only one in the world
    CHECK(s.entities().size() == 1);
  }

  SECTION("Charlie can have a wife too") {
    // When Charlie logs in,
    auto c = TestClient::WithUsernameAndData("Charlie", "wives");
    s.waitForUsers(1);
    auto &user = s.getFirstUser();

    // And tries to get a readhead wife
示例#21
0
文件: main.c 项目: Nixsm/nsh
int main(int argc, char** argv){
    char line[LINE_SIZE];
    char* username;
    char curDir[1024];
    char** parsedArgs;
    char promptMsg[LINE_SIZE];
    int len;
    int argsLen;
    struct timeval wallClockBegin;
    struct rusage usage;
    int returnStatus;
    int background;
    int pgid;

    Jobs jobs = createList();
    
    fputs("NSH VERSION 0.0.0.0.1\n", stdout);
    
    while(1) {
        signal(SIGINT, sigHandler);

        getcwd(curDir, sizeof(curDir));
        username = getenv("USER");
        
        sprintf(promptMsg, "%s -- %s >>> ", username, curDir);
        
        if (fputs(promptMsg, stdout) == EOF) { /* check for errors at fputs */
            continue;
        }
        
        if (fgets(line, LINE_SIZE, stdin) == NULL) { /* if our fgets finds a EOF, continue */
            break;
        }

        len = strlen(line); /* get the lenght of the line to remove the last \n */

        if (line[len - 1] == '\n') { /* removes the \n from fgets */
            line[len - 1] = '\0';
        }

        if (strcmp(line, QUIT_PHRASE) == 0){ /* check if the current command isnt our exit command */
            break;
        }

        if (strchr(line, BACKGROUND_SYMBOL) != 0) {
            line[len - 2] = '\0';
            background = 1;
        } else {
            background = 0;
        }

        argsLen = makeArgs(line, " ", &parsedArgs);

        if (argsLen > 0){
            if (strcmp(parsedArgs[0], "cd") == 0) {
                chdir(parsedArgs[1]);
            } else if (strcmp(parsedArgs[0], "jobs") == 0) {
                showJobs(&jobs);
            } else {
                gettimeofday(&wallClockBegin, NULL);
                getrusage(RUSAGE_CHILDREN, &usage);
                pgid = fork();
                if (pgid == 0) {
                    execvp(parsedArgs[0], parsedArgs);
                    printf("nsh: command not found: %s\n", parsedArgs[0]);
                    return 1; /* for some strange reason this will return 256 later */
                } else {
                    if (background) {
                        add(&jobs, pgid, line, BACKGROUND);
                    } else {
                        add(&jobs, pgid, line, FOREGROUND);
                    }
                }
                if (!background) {
                    waitpid(pgid, &returnStatus, 0);
                    if (returnStatus != 256) {
                        printStatitics(&wallClockBegin, &usage); //Print statics when child return
                    }
                } else {
                    
                    waitpid(-1, &returnStatus, WUNTRACED);
                }
            }
        }
        
        free(parsedArgs);
        strcpy(line, "");
    }

    fputs("\nGood bye, please come again!", stdout);

    return 0;
}
示例#22
0
文件: main.c 项目: Acidburn0zzz/afdko
/* Main program */
IntN main(IntN argc, Byte8 *argv[])
	{
	   IntX value = 0;
	  static double glyphptsize = STDPAGE_GLYPH_PTSIZE;
	  static opt_Option opt[] =
		{
		  {"-u", opt_Call, (void*)showUsage},
		  {"-h", opt_Call, (void*)showHelp},
		  {"-ht", opt_Call, (void*)sfntTableSpecificUsage},
#if AUTOSPOOL
		  {"-l", opt_Flag},
		  {"-O", opt_Flag},
#endif
		  {"-r", opt_Flag},
		  {"-n", opt_Flag},
		  {"-nc", opt_Flag},
		  {"-ngid", opt_Flag},
		  {"-T", opt_Flag},
		  {"-F", opt_Flag},
		  {"-f", opt_Flag},
		  {"-G", opt_Flag},
		  {"-V", opt_Flag},
		  {"-m", opt_Flag},
		  {"-d", opt_Flag},
		  {"-br", opt_Flag},
		  {"-i", resIdScan},
		  {"-o", sfntTTCScan},
		  {"-t", sfntTagScan},
		  {"-P", sfntFeatScan}, 
		  {"-A", sfntFeatScan}, 
		  {"-p", proofPolicyScan}, 
		  {"-a", opt_Flag},
		  {"-R", opt_Flag},
		  {"-c", opt_Flag},
		  {"-g", glyfGlyphScan},
		  {"-b", glyfBBoxScan},
		  {"-s", glyfScaleScan},
		  {"-@", opt_Double, &glyphptsize},
		  {"-C", opt_Int, &cmapSelected},
#if AUTOSCRIPT
		  {"-X", opt_String, scriptfilename},
#endif
		  {"-ag", opt_String, &glyphaliasfilename},
		  {"-of", opt_String, &outputfilebase},
		};

	  IntX files, goodFileCount=0;
	  IntN argi;
      Byte8 *filename = NULL;
	  volatile IntX i = 0;
#if AUTOSCRIPT
	  cmdlinetype *cmdl;
	  Byte8 foundXswitch = 0;
#endif
	  int status = 0; /* = setjmp(global.env); only ued when compiled as lib */

	  if (status)
	  {
#if AUTOSCRIPT
	  	if (global.doingScripting)
	  		{
	  		  goto scriptAbEnd;
	  		}
	  	else
#endif
			exit(status - 1);	/* Finish processing */
	  }
	  gcr.reportNumber=0;
	 /*  value = setjmp(mark); only used when comiled as lib */

         if (value==-1)
                 exit(1);

	  da_SetMemFuncs(memNew, memResize, memFree);
	  global.progname = "spot";

#if AUTOSCRIPT
	scriptfilename[0] = '\0'; /* init */

	if (!foundXswitch && (argc < 2)) /* if no -X on cmdline, and no OTHER switches */
	  strcpy(scriptfilename, "spot.scr");

/* see if scriptfile exists to Auto-execute */
	if ((scriptfilename[0] != '\0') && sysFileExists(scriptfilename))
		{
			global.doingScripting = 1;
			makeArgs(scriptfilename);
		}
#endif /* AUTOSCRIPT */

	  if (
#if AUTOSCRIPT
		  !global.doingScripting
#else
		  1
#endif
		  )
		{
	  	argi = opt_Scan(argc, argv, opt_NOPTS(opt), opt, NULL, NULL);
		if (opt_hasError())
			{
			exit(1);
			}
	  
	  if (argi == 0 )
		showUsage();

#if AUTOSCRIPT
	if (!global.doingScripting && opt_Present("-X"))
	{
		if (scriptfilename && scriptfilename[0] != '\0')
		{
		global.doingScripting = 1;
		makeArgs(scriptfilename);
		goto execscript;
		}
	}
#endif


	  if (opt_Present("-@"))
		proofSetGlyphSize(glyphptsize);

	  if (opt_Present("-V"))  /* equivalent to "-p6" */
		proofSetPolicy(6, 1); 

	  if (opt_Present("-ngid")) 
		global.flags |= SUPPRESS_GID_IN_NAME;

	  files = argc - argi;
      if ((files == 0) && (argc > 1)) /* no files on commandline, but other switches */
		{
		}

	  for (; argi < argc; argi++)
		{
		  filename = argv[argi];
		  
		  if (files > 1)
		  	{
			fprintf(stderr, "Proofing %s.\n", filename);
			fflush(stderr);
			}

		  if (outputfilebase== NULL)
		 	outputfilebase = filename;
		  fileOpen(filename);		  
		  
		  if (!fileIsOpened())
		  {
		  	warning(SPOT_MSG_BADFILE, filename);
			fileClose();
			continue;
		  }
		  if (readFile(filename))
			{
			  fileClose();
			  continue;
			}

		  goodFileCount++;
		  fileClose();
		}
		
	}
#if AUTOSCRIPT
	else /* executing cmdlines from a script file */
	{
execscript:
			{
				char * end;
				
			end=strrchr(scriptfilename, '\\');
				if(end==NULL)
					sourcepath="";
				else{
					char *scurr = scriptfilename;
					char *dcurr;
					
					sourcepath=(char *)memNew(strlen(scriptfilename));
					dcurr = sourcepath;
					while(scurr!=end)
					{
						*dcurr++=*scurr++;
					}		
					*dcurr=0;
				}
			
			}

	  for (i = 0; i < script.cmdline.cnt ; i++) 
	  {
		char * tempfilename;
		
		cmdl = da_INDEX(script.cmdline, i);
		if (cmdl->args.cnt < 2) continue;

		proofResetPolicies();
		
		{
			IntX a;
			
			inform(SPOT_MSG_EOLN);
			message(SPOT_MSG_ECHOSCRIPTCMD);
			for (a = 1; a < cmdl->args.cnt; a++)
			{
				inform(SPOT_MSG_RAWSTRING, cmdl->args.array[a]);
			}
			inform(SPOT_MSG_EOLN);
		}
		
		argi = opt_Scan(cmdl->args.cnt, cmdl->args.array, opt_NOPTS(opt), opt, NULL, NULL);		
		if (opt_hasError())
			{
			exit(1);
			}

		if (opt_Present("-@"))
			proofSetGlyphSize(glyphptsize);
	  	if (opt_Present("-V"))  /* equivalent to "-p6" */
			proofSetPolicy(6, 1); 

		tempfilename = MakeFullPath(cmdl->args.array[cmdl->args.cnt-1]);
		
		
		if (fileExists(tempfilename) )
		  { 						/* (new) font filename on cmdline */
			memFree(tempfilename);
			if (filename != NULL) /* not first time */
			{
			  fileClose(); /* previous font file */
	  		  sfntFree(1);
		  	}
			if(sourcepath[0]!='\0')
				filename=MakeFullPath(cmdl->args.array[cmdl->args.cnt-1]);
			else
				filename = cmdl->args.array[cmdl->args.cnt-1];
			fileOpen(filename);
			if (outputfilebase == NULL)
		 		outputfilebase = filename;
			fprintf(stderr, "Proofing %s.\n", filename);
			fflush(stderr);
		    goodFileCount++;
		
		  if (readFile(filename))
			{
			  goodFileCount--;
			  fileClose();
			  continue;
			}
			
		  }
		else
		{
		  /* none specified */
		  fatal(SPOT_MSG_MISSINGFILENAME);
		  memFree(tempfilename);
		  continue;
		}
		
		sfntDump();
		
scriptAbEnd:
		sfntFree(1);
	    fileClose();
	  }
	  global.doingScripting = 0;
	}
#endif /* AUTOSCRIPT */

/*	fprintf(stderr, "\nDone.\n");*/
	if(goodFileCount<=0)
		exit(1);

	quit(0);
	return 0;		
}