Ejemplo n.º 1
0
gint
asCEnum(USER_OBJECT_ s_enum, GType etype)
{
    GEnumClass *eclass = g_type_class_ref(etype);
    GEnumValue *evalue = NULL;
    gint eval = 0;

    if (IS_INTEGER(s_enum) || IS_NUMERIC(s_enum)) {
        evalue = g_enum_get_value(eclass, asCInteger(s_enum));
    } else if (IS_CHARACTER(s_enum)) {
        const gchar* ename = asCString(s_enum);
        evalue = g_enum_get_value_by_name(eclass, ename);
        if (!evalue)
            evalue = g_enum_get_value_by_nick(eclass, ename);
        if (!evalue)
            evalue = g_enum_get_value(eclass, atoi(ename));
    }

    if (!evalue) {
        PROBLEM "Could not parse enum value %s", asCString(s_enum)
        ERROR;
    } else eval = evalue->value;

    return(eval);
}
Ejemplo n.º 2
0
guint
R_asFlag(USER_OBJECT_ s_flag, USER_OBJECT_ ftype)
{
    GType type = g_type_from_name(asCString(ftype));
    if (!type) {
        PROBLEM "Invalid flag type %s", asCString(ftype)
        ERROR;
    }
    return(asCFlag(s_flag, type));
}
Ejemplo n.º 3
0
gint
R_asEnum(USER_OBJECT_ s_enum, USER_OBJECT_ etype)
{
    GType type = g_type_from_name(asCString(etype));
    if (!type) {
        PROBLEM "Invalid enum type %s", asCString(etype)
        ERROR;
    }
    return(asCEnum(s_enum, type));
}
Ejemplo n.º 4
0
void worker_engine::respond_to_assignment(void * socket,
		Json::Value const & json) {
	string txt;
	if (data->enrolled) {
		auto aid = json["body"]["assignment"]["id"];
		auto lines = json["body"]["assignment"]["lines"];
		assignment * asgn = new assignment(aid.asCString(), lines.asCString());
		accept_assignment(asgn);
		txt = serialize_msg(NITRO_ACCEPT_ASSIGNMENT);
	} else {
		txt = serialize_msg(NITRO_REJECT_ASSIGNMENT_1REASON,
				"not yet enrolled");
	}
	send_full_msg(socket, txt);
}
Ejemplo n.º 5
0
guint
asCFlag(USER_OBJECT_ s_flag, GType ftype)
{
    GFlagsClass* fclass = g_type_class_ref(ftype);
    guint flags = 0;

    if (IS_INTEGER(s_flag) || IS_NUMERIC(s_flag)) {
        if (asCNumeric(s_flag) > fclass->mask) {
            PROBLEM "The flags value %f is too high", asCNumeric(s_flag)
            ERROR;
        }
        flags = asCNumeric(s_flag);
    } else {
        int i;
        for (i = 0; i < GET_LENGTH(s_flag); i++) {
            const gchar *fname = asCString(STRING_ELT(s_flag, i));
            /*Rprintf("Searching for flag value %s\n", fname);*/
            GFlagsValue *fvalue = g_flags_get_value_by_name(fclass, fname);
            if (!fvalue)
                fvalue = g_flags_get_value_by_nick(fclass, fname);
            if (!fvalue && atoi(fname) <= fclass->mask) {
                flags |= atoi(fname);
                continue;
            }
            if (!fvalue) {
                PROBLEM "Could not find flag by name %s", fname
                ERROR;
            }
            /*Rprintf("Found: %d\n", fvalue->value);*/
            flags |= fvalue->value;
        }
    }

    return(flags);
}
Ejemplo n.º 6
0
USER_OBJECT_
RS_GGOBI(getTourProjection)(USER_OBJECT_ s_display, USER_OBJECT_ s_mode_name)
{
	displayd *display = toDisplay(s_display);
  ProjectionMode mode = GGOBI(getPModeId)(asCString(s_mode_name));
  gint k, n;
  USER_OBJECT_ matrix;
  gdouble *x = NULL, *y = NULL;
  
  g_return_val_if_fail(GGOBI_IS_DISPLAY(display), NULL_USER_OBJECT);
  
  RS_INTERNAL_GGOBI(getTourVectorsFromMode)(display, mode, &x, &y);
  g_return_val_if_fail(x != NULL, NULL_USER_OBJECT);
  
  n = display->d->ncols;
  PROTECT(matrix = allocMatrix(REALSXP, n, 3));
  for (k = 0; k < n; k++) {
    vartabled *vt = vartable_element_get (k, display->d);
    REAL(matrix)[k] = x[k]; /* x coeff */
    if (y)
      REAL(matrix)[k+n] = y[k]; /* y coeff */
    else REAL(matrix)[k+n] = 0;
    REAL(matrix)[k+2*n] = vt->lim.max - vt->lim.min; /* range */
  }
  
  UNPROTECT(1);
  
  return matrix;
}
Ejemplo n.º 7
0
/* Expects a 2 column matrix with the X and Y coefficients for each var */
USER_OBJECT_
RS_GGOBI(setTourProjection)(USER_OBJECT_ s_display, USER_OBJECT_ s_mode_name,
  USER_OBJECT_ matrix)
{
  displayd *display = toDisplay(s_display);
  ProjectionMode mode = GGOBI(getPModeId)(asCString(s_mode_name));
  gint k, n;
  gdouble *x = NULL, *y = NULL;
  
  g_return_val_if_fail(GGOBI_IS_DISPLAY(display), NULL_USER_OBJECT);
  
  RS_INTERNAL_GGOBI(getTourVectorsFromMode)(display, mode, &x, &y);
  g_return_val_if_fail(x != NULL, NULL_USER_OBJECT);
  
  n = display->d->ncols;
  for (k = 0; k < n; k++) {
    x[k] = REAL(matrix)[k];
    if (y)
      y[k] = REAL(matrix)[k+n];
  }
  
  display_tailpipe (display, FULL, display->ggobi);
  varcircles_refresh (display->d, display->ggobi);
  
  return NULL_USER_OBJECT;
}
EXPORT int primitiveDrawString(void) {
	int bitmapOop;
	void *bitmapPtr;
	int result;
	int h;
	int utf8Oop;
	int w;
	int utf8Length;
	char *utf8;

	utf8Oop = interpreterProxy->stackValue(3);
	utf8 = asCString(utf8Oop);
	w = interpreterProxy->stackIntegerValue(2);
	h = interpreterProxy->stackIntegerValue(1);
	bitmapOop = interpreterProxy->stackValue(0);
	bitmapPtr = cWordsPtrminSize(bitmapOop, w * h);
	if (interpreterProxy->failed()) {
		return 0;
	}
	utf8Length = interpreterProxy->stSizeOf(utf8Oop);
	unicodeDrawString(utf8, utf8Length, &w, &h, bitmapPtr);
	result = interpreterProxy->makePointwithxValueyValue(w, h);
	interpreterProxy->popthenPush(5, result);
	return 0;
}
Ejemplo n.º 9
0
bool JValue::operator==(const std::string& other) const
{
	const char * buffer = asCString();
	if (buffer == NULL)
		return false;

	return other.compare(buffer) == 0;
}
Ejemplo n.º 10
0
Archivo: utils.c Proyecto: cran/RGtk2
USER_OBJECT_
getNumericType(USER_OBJECT_ s)
{
  /* Get the numeric type code for an R object */
  /*return asRNumeric(TYPEOF(s));*/
  /* Instead, get the numeric type for an R type name */
  return asRNumeric(str2type(asCString(s)));
}
Ejemplo n.º 11
0
bool JValue::operator==(const char * other) const
{
	const char * buffer = asCString();
	if (buffer == NULL)
		return false;

	return strcmp(buffer, other) == 0;
}
Ejemplo n.º 12
0
gchar
asCCharacter(USER_OBJECT_ s_char)
{
  gchar c = '\0';
  gchar *str = asCString(s_char);
  if (str)
    c = str[0];
  return(c);
}
Ejemplo n.º 13
0
USER_OBJECT_
S_glade_xml_signal_connect_data(USER_OBJECT_ s_object, USER_OBJECT_ s_handlername, USER_OBJECT_ s_func, USER_OBJECT_ s_user_data)
{
        GladeXML* object = GLADE_XML(getPtrValue(s_object));
		const char* handlername = (const char*)asCString(s_handlername);
		
		USER_OBJECT_ _result = NULL_USER_OBJECT;

        glade_xml_signal_connect_full(object, handlername, (GladeXMLConnectFunc)S_GladeXMLConnectFuncDefault, 
			R_createGClosure(s_func, s_user_data));

        return(_result);
}
Ejemplo n.º 14
0
Value::operator bool () const
{
    if (isNull ())
        return false;

    if (isString ())
    {
        auto s = asCString();
        return s && strlen(s);
    }

    return ! (isArray () || isObject ()) || size ();
}
Ejemplo n.º 15
0
/* reason: discard text length parameter and handle in-out position
	it's probably too much trouble to add automatic in-out support, especially
	because it only affects primitive types
	- why couldn't they just return that by value? */
USER_OBJECT_
S_atk_editable_text_insert_text(USER_OBJECT_ s_object, USER_OBJECT_ s_string, USER_OBJECT_ s_position)
{
        AtkEditableText* object = ATK_EDITABLE_TEXT(getPtrValue(s_object));
        const gchar* string = (const gchar*)asCString(s_string);
        gint* position = (gint*)asCArray(s_position, gint, asCInteger);
		gint length = strlen(string);
        USER_OBJECT_ _result = NULL_USER_OBJECT;

        atk_editable_text_insert_text(object, string, length, position);

		_result = retByVal(_result, "position", asRInteger(*position), NULL);
        return(_result);
}
EXPORT int primitiveGetFontList(void) {
	int strOop;
	char *str;
	int count;
	int strLength;

	strOop = interpreterProxy->stackValue(0);
	str = asCString(strOop);
	if (interpreterProxy->failed()) {
		return 0;
	}
	strLength = interpreterProxy->stSizeOf(strOop);
	count = unicodeGetFontList(str, strLength);
	interpreterProxy->popthenPush(2, ((count << 1) | 1));
	return 0;
}
Ejemplo n.º 17
0
USER_OBJECT_
RS_GGOBI(createDisplay)(USER_OBJECT_ stype, USER_OBJECT_ svars, 
  USER_OBJECT_ datasetId, USER_OBJECT_ useWindow)
{
  GGobiData *d;
  ggobid *gg;
  displayd *display = NULL;
  GType type;
  GGobiExtendedDisplayClass *klass;
  gboolean use_window = asCLogical(useWindow);

  d = toData(datasetId);
  g_return_val_if_fail(GGOBI_IS_DATA(d), NULL_USER_OBJECT);
  gg = d->gg;

  type = g_type_from_name(asCString(stype));
  klass = GGOBI_EXTENDED_DISPLAY_CLASS(g_type_class_peek(type));

  if(!klass) {
     PROBLEM "Unrecognized display type"
     ERROR;
  }

  if(klass->createWithVars && GET_LENGTH(svars)) {
     gint nvars, *vars, i;
     nvars = GET_LENGTH(svars);
     vars = g_malloc(sizeof(gint)*nvars);
     for(i = 0; i < nvars; i++)
       vars[i] = INTEGER_DATA(svars)[i];
     display = klass->createWithVars(use_window, false, nvars, vars, d, gg);
  } else if(klass->create)
     display = klass->create(use_window, false, NULL, d, gg);

  if(!display) {
    PROBLEM "Couldn't create the display"
    ERROR;
  }

  display_add(display, gg);

  gdk_flush();
  
  return(RS_displayInstance(display));
}
Ejemplo n.º 18
0
void CGroup::reqGroupMembers(stGroupItem* pGroup )
{
	// refresh cnt ;
//	Json::Value cValue ;
//	cValue["email"] = "*****@*****.**" ;
//	cValue["devpwd"] = "bill007" ;
//#ifndef ONLINE_APP_KEY
//	cValue["appkey"] = "e87f31bb-e86c-4d87-a3f3-57b3da76b3d6";
//#else
//	cValue["appkey"] = "abffee4b-deea-4e96-ac8d-b9d58f246c3f" ;
//#endif // DEBUG
//	//cValue["index"] = pGroup->getMemberCnt() / REQ_PAGE_MEMBER_CNT_OF_CLUB ;
//	//cValue["count"] = REQ_PAGE_MEMBER_CNT_OF_CLUB ;
//	cValue["group_id"] = pGroup->nGroupID ;
//	Json::StyledWriter sWrite ;
//	std::string str = sWrite.write(cValue);
//	m_pGoTyeAPI.performRequest("GetGroupUserList",str.c_str(),str.size(),pGroup,eReq_GroupMembers );

	auto pQinjia = CGameServerApp::SharedGameServerApp()->getQinjiaModule();
	Json::Value cValue ;
	cValue["group_id"] = pGroup->nGroupID ;

	pQinjia->sendQinJiaRequest("GetGroupUserList",cValue,[this](Json::Value& jsResult , Json::Value& jsUserData){
		auto nClubID = jsUserData["group_id"].asUInt();
		auto pClub = getGroupByID(nClubID);

		if ( jsResult.isNull() || jsResult["errcode"].asUInt() != 200 )
		{
			LOGFMTE("req club = %u, member list error ",nClubID) ;
			return ;
		}

		Json::Value jsMembers = jsResult["user_list"] ;
		for ( uint16_t nIdx = 0 ; nIdx < jsMembers.size() ; ++nIdx )
		{
			auto jsM = jsMembers[nIdx] ;
			uint32_t nUID = atoi(jsM.asCString()) ;
			LOGFMTD("req member to add group id = %u , uid = %u",pClub->nGroupID,nUID);
			pClub->addMember(nUID) ;
		}
	},cValue) ;
}
EXPORT int primitiveMeasureString(void) {
	int utf8Length;
	int result;
	int h;
	int utf8Oop;
	int w;
	char *utf8;

	utf8Oop = interpreterProxy->stackValue(0);
	utf8 = asCString(utf8Oop);
	if (interpreterProxy->failed()) {
		return 0;
	}
	w = h = 0;
	utf8Length = interpreterProxy->stSizeOf(utf8Oop);
	unicodeMeasureString(utf8, utf8Length, &w, &h);
	result = interpreterProxy->makePointwithxValueyValue(w, h);
	interpreterProxy->popthenPush(2, result);
	return 0;
}
EXPORT int primitiveGetXRanges(void) {
	int count;
	int utf8Oop;
	int resultOop;
	int *resultPtr;
	int utf8Length;
	int resultLength;
	char *utf8;

	utf8Oop = interpreterProxy->stackValue(1);
	utf8 = asCString(utf8Oop);
	resultOop = interpreterProxy->stackValue(0);
	resultPtr = cWordsPtrminSize(resultOop, 0);
	if (interpreterProxy->failed()) {
		return 0;
	}
	utf8Length = interpreterProxy->stSizeOf(utf8Oop);
	resultLength = interpreterProxy->stSizeOf(resultOop);
	count = unicodeGetXRanges(utf8, utf8Length, resultPtr, resultLength);
	interpreterProxy->popthenPush(3, ((count << 1) | 1));
	return 0;
}
Ejemplo n.º 21
0
/// Process data from bitcoind daemon (esp. RPC getrawmempool for live transactions)
void daemonThreadFunc(BlockChain* blockChain)
{
	leveldb::WriteBatch batch;

	while (true)
	{
		std::this_thread::sleep_for(std::chrono::seconds(1));

		if (requestedQuit)
			break;

		if (!txCheck)
			continue;

		try
		{
			auto transactions = rpcClient->CallMethod("getrawmempool", Json::Value());

			BlockInfo blockInfo;
			Hash256 latestBlock;
			{
				boost::lock_guard<boost::mutex> guard(chainMutex);
				latestBlock = currentChain.back();

				auto blockInfoIt = blocks.find(latestBlock);
				if (blockInfoIt == blocks.end())
				{
					continue;
				}
				blockInfo = blockInfoIt->second;
			}

			if (pendingPreviousBlock != latestBlock)
			{
				pendingPreviousBlock = latestBlock;

				// Broadcast new block for live update
				Json::Value blockResult;
				blockResult["item"] = "block";
				convertBlock(blockResult, pendingPreviousBlock, blockInfo);
				websocket_server.broadcast_livetx(blockResult.toStyledString().c_str());

				{
					boost::lock_guard<boost::mutex> guard(pendingTransactionsMutex);
					pendingTransactionIndices.clear();
					pendingTransactions.clear();
					pendingTransactionsByAddress.clear();
				}
			}

			for (auto tx = transactions.begin(); tx != transactions.end(); ++tx)
			{
				Hash256 txHash;
				encodeHexString((uint8_t*) &txHash, 32, (*tx).asString(), true);

				batch.Clear();

				{
					// Already exists?
					boost::unique_lock<boost::mutex> guard(pendingTransactionsMutex);
					if (pendingTransactionIndices.find(txHash) != pendingTransactionIndices.end())
						continue;
				}

				{
					DbTransaction dbTx;

					Json::Value parameters(Json::arrayValue);
					parameters.append(*tx);
					auto rawTx = rpcClient->CallMethod("getrawtransaction", parameters);

					auto data = rawTx.asCString();
					auto bufferLength = strlen(data) / 2;

					llvm::SmallVector<uint8_t, 65536> buffer;
					buffer.resize(bufferLength);

					encodeHexString(buffer.begin(), bufferLength, data);

					BlockChain::BlockTransaction tx2;
					if (!blockChain->processSingleTransaction(buffer.begin(), bufferLength, tx2))
						assert("could not read tx" && false);

					assert(memcmp(tx2.transactionHash, &txHash, 32) == 0);
					uint64_t totalOutput = 0;
					bool needBroadcast = false;

					auto txIndex = dbHelper.txLoad(txHash, dbTx, NULL, NULL);
					if (txIndex == 0)
					{
						{
							boost::unique_lock<boost::mutex> guard(pendingTransactionsMutex);
							try
							{
								txIndex = processTransaction(batch, dbTx, tx2, time(NULL), false, &pendingTransactionIndices, &pendingTransactions);
							}
							catch (std::exception e)
							{
								batch.Clear();
								continue;
							}
						}

						needBroadcast = true;

						dbHelper.txSave(batch, txHash, dbTx);
						db->Write(leveldb::WriteOptions(), &batch);
					}

					{
						boost::unique_lock<boost::mutex> guard(pendingTransactionsMutex);
						pendingTransactionIndices[txHash] = pendingTransactions.size();
						pendingTransactions.emplace_back(txHash, dbTx);

						// lastPendingTransactions only holds last N items 
						if (lastPendingTransactions.size() >= lastPendingTransactionsSize)
							lastPendingTransactions.pop_front();

						lastPendingTransactions.emplace_back(txHash, dbTx);

						for (auto output = dbTx.outputs.begin(); output != dbTx.outputs.end(); ++output)
						{
							if (output->address.IsNull())
								continue;
							totalOutput += output->value;

							pendingTransactionsByAddress.emplace(output->address, pendingTransactions.size() - 1);
						}

						for (auto input = dbTx.inputs.begin(); input != dbTx.inputs.end(); ++input)
						{
							if (input->address.IsNull())
								continue;

							pendingTransactionsByAddress.emplace(input->address, pendingTransactions.size() - 1);
						}
					}

					if (needBroadcast)
					{
						Json::Value txResult;

						// Broadcast tx for live update
						txResult["item"] = "tx";
						txResult["output"] = (double)totalOutput;

						char timeBuffer[65];
						convertTime(dbTx.getBestTimeStamp(), timeBuffer, sizeof(timeBuffer));
						txResult["time"] = timeBuffer;

						txResult["coinage_destroyed"] = dbTx.coinAgeDestroyed / 86400.0;
						txResult["hash"] = *tx;

						websocket_server.broadcast_livetx(txResult.toStyledString().c_str());
					}
				}
			}
		}
		catch (std::exception e)
		{
			boost::lock_guard<boost::mutex> guard(pendingTransactionsMutex);
			pendingTransactionIndices.clear();
			pendingTransactions.clear();
			pendingTransactionsByAddress.clear();

			printf("Error processing live transactions: %s!\n", e.what());
		}
	}
}
Ejemplo n.º 22
0
void Client::updateStatus(Json::Value& msg, Ime::EditSession* session) {
	// We need to handle ordering of some types of the requests.
	// For example, setCompositionCursor() should happen after setCompositionCursor().

	// set sel keys before update candidates
	const auto& setSelKeysVal = msg["setSelKeys"];
	if (setSelKeysVal.isString()) {
		// keys used to select candidates
		std::wstring selKeys = utf8ToUtf16(setSelKeysVal.asCString());
		textService_->setSelKeys(selKeys);
	}

	// show message
    bool endComposition = false;
	const auto& showMessageVal = msg["showMessage"];
	if (showMessageVal.isObject()) {
		const Json::Value& message = showMessageVal["message"];
		const Json::Value& duration = showMessageVal["duration"];
		if (message.isString() && duration.isInt()) {
			if (!textService_->isComposing()) {
				textService_->startComposition(session->context());
                endComposition = true;
			}
			textService_->showMessage(session, utf8ToUtf16(message.asCString()), duration.asInt());
		}
	}

	if (session != nullptr) { // if an edit session is available
		// handle candidate list
		const auto& showCandidatesVal = msg["showCandidates"];
		if (showCandidatesVal.isBool()) {
			if (showCandidatesVal.asBool()) {
				// start composition if we are not composing.
				// this is required to get correctly position the candidate window
				if (!textService_->isComposing()) {
					textService_->startComposition(session->context());
				}
				textService_->showCandidates(session);
			}
			else {
				textService_->hideCandidates();
			}
		}

		const auto& candidateListVal = msg["candidateList"];
		if (candidateListVal.isArray()) {
			// handle candidates
			// FIXME: directly access private member is dirty!!!
			vector<wstring>& candidates = textService_->candidates_;
			candidates.clear();
			for (auto cand_it = candidateListVal.begin(); cand_it != candidateListVal.end(); ++cand_it) {
				wstring cand = utf8ToUtf16(cand_it->asCString());
				candidates.push_back(cand);
			}
			textService_->updateCandidates(session);
			if (!showCandidatesVal.asBool()) {
				textService_->hideCandidates();
			}
		}

		const auto& candidateCursorVal = msg["candidateCursor"];
		if (candidateCursorVal.isInt()) {
			if (textService_->candidateWindow_ != nullptr) {
				textService_->candidateWindow_->setCurrentSel(candidateCursorVal.asInt());
				textService_->refreshCandidates();
			}
		}

		// handle comosition and commit strings
		const auto& commitStringVal = msg["commitString"];
		if (commitStringVal.isString()) {
			std::wstring commitString = utf8ToUtf16(commitStringVal.asCString());
			if (!commitString.empty()) {
				if (!textService_->isComposing()) {
					textService_->startComposition(session->context());
				}
				textService_->setCompositionString(session, commitString.c_str(), commitString.length());
                // FIXME: update the position of candidate and message window when the composition string is changed.
                if (textService_->candidateWindow_ != nullptr) {
                    textService_->updateCandidatesWindow(session);
                }
                if (textService_->messageWindow_ != nullptr) {
                    textService_->updateMessageWindow(session);
                }
				textService_->endComposition(session->context());
			}
		}

		const auto& compositionStringVal = msg["compositionString"];
		bool emptyComposition = false;
		bool hasCompositionString = false;
		std::wstring compositionString;
		if (compositionStringVal.isString()) {
			// composition buffer
			compositionString = utf8ToUtf16(compositionStringVal.asCString());
			hasCompositionString = true;
			if (compositionString.empty()) {
				emptyComposition = true;
				if (textService_->isComposing() && !textService_->showingCandidates()) {
					// when the composition buffer is empty and we are not showing the candidate list, end composition.
					textService_->setCompositionString(session, L"", 0);
					endComposition = true;
				}
			}
			else {
				if (!textService_->isComposing()) {
					textService_->startComposition(session->context());
				}
				textService_->setCompositionString(session, compositionString.c_str(), compositionString.length());
			}
            // FIXME: update the position of candidate and message window when the composition string is changed.
            if (textService_->candidateWindow_ != nullptr) {
                textService_->updateCandidatesWindow(session);
            }
            if (textService_->messageWindow_ != nullptr) {
                textService_->updateMessageWindow(session);
            }
		}

		const auto& compositionCursorVal = msg["compositionCursor"];
		if (compositionCursorVal.isInt()) {
			// composition cursor
			if (!emptyComposition) {
				int compositionCursor = compositionCursorVal.asInt();
				if (!textService_->isComposing()) {
					textService_->startComposition(session->context());
				}
				// NOTE:
				// This fixes PIME bug #166: incorrect handling of UTF-16 surrogate pairs.
				// The TSF API unfortunately treat a UTF-16 surrogate pair as two characters while
				// they actually represent one unicode character only. To workaround this TSF bug,
				// we get the composition string, and try to move the cursor twice when a UTF-16
				// surrogate pair is found.
				if(!hasCompositionString)
					compositionString = textService_->compositionString(session);
				int fixedCursorPos = 0;
				for (int i = 0; i < compositionCursor; ++i) {
					++fixedCursorPos;
					if (IS_HIGH_SURROGATE(compositionString[i])) // this is the first part of a UTF16 surrogate pair (Windows uses UTF16-LE)
						++fixedCursorPos;
				}
				textService_->setCompositionCursor(session, fixedCursorPos);
			}
		}

		if (endComposition) {
			textService_->endComposition(session->context());
		}
	}

	// language buttons
	const auto& addButtonVal = msg["addButton"];
	if (addButtonVal.isArray()) {
		for (auto btn_it = addButtonVal.begin(); btn_it != addButtonVal.end(); ++btn_it) {
			const Json::Value& btn = *btn_it;
			// FIXME: when to clear the id <=> button map??
			Ime::ComPtr<PIME::LangBarButton> langBtn{ PIME::LangBarButton::fromJson(textService_, btn), false };
			if (langBtn != nullptr) {
				buttons_.emplace(langBtn->id(), langBtn); // insert into the map
				textService_->addButton(langBtn);
			}
		}
	}

	const auto& removeButtonVal = msg["removeButton"];
	if (removeButtonVal.isArray()) {
		// FIXME: handle windows-mode-icon
		for (auto btn_it = removeButtonVal.begin(); btn_it != removeButtonVal.end(); ++btn_it) {
			if (btn_it->isString()) {
				string id = btn_it->asString();
				auto map_it = buttons_.find(id);
				if (map_it != buttons_.end()) {
					textService_->removeButton(map_it->second);
					buttons_.erase(map_it); // remove from the map
				}
			}
		}
	}
	const auto& changeButtonVal = msg["changeButton"];
	if (changeButtonVal.isArray()) {
		// FIXME: handle windows-mode-icon
		for (auto btn_it = changeButtonVal.begin(); btn_it != changeButtonVal.end(); ++btn_it) {
			const Json::Value& btn = *btn_it;
			if (btn.isObject()) {
				string id = btn["id"].asString();
				auto map_it = buttons_.find(id);
				if (map_it != buttons_.end()) {
					map_it->second->updateFromJson(btn);
				}
			}
		}
	}

	// preserved keys
	const auto& addPreservedKeyVal = msg["addPreservedKey"];
	if (addPreservedKeyVal.isArray()) {
		// preserved keys
		for (auto key_it = addPreservedKeyVal.begin(); key_it != addPreservedKeyVal.end(); ++key_it) {
			const Json::Value& key = *key_it;
			if (key.isObject()) {
				std::wstring guidStr = utf8ToUtf16(key["guid"].asCString());
				CLSID guid = { 0 };
				CLSIDFromString(guidStr.c_str(), &guid);
				UINT keyCode = key["keyCode"].asUInt();
				UINT modifiers = key["modifiers"].asUInt();
				textService_->addPreservedKey(keyCode, modifiers, guid);
			}
		}
	}
	
	const auto& removePreservedKeyVal = msg["removePreservedKey"];
	if (removePreservedKeyVal.isArray()) {
		for (auto key_it = removePreservedKeyVal.begin(); key_it != removePreservedKeyVal.end(); ++key_it) {
			if (key_it->isString()) {
				std::wstring guidStr = utf8ToUtf16(key_it->asCString());
				CLSID guid = { 0 };
				CLSIDFromString(guidStr.c_str(), &guid);
				textService_->removePreservedKey(guid);
			}
		}
	}

	// keyboard status
	const auto& openKeyboardVal = msg["openKeyboard"];
	if (openKeyboardVal.isBool()) {
		textService_->setKeyboardOpen(openKeyboardVal.asBool());
	}

	// other configurations
	const auto& customizeUIVal = msg["customizeUI"];
	if (customizeUIVal.isObject()) {
		// customize the UI
		updateUI(customizeUIVal);
	}

	// hide message
    const auto& hideMessageVal = msg["hideMessage"];
	if (hideMessageVal.isBool()) {
        textService_->hideMessage();
	}
}
Ejemplo n.º 23
0
char
asCCharacter(USER_OBJECT_ s_char)
{
    return(asCString(s_char)[0]);
}