Example #1
0
void ResizeableBuffer::resize(size_t new_capacity) {
	if(!new_capacity) {
		free(ptr);
		ptr = NULL;
		capacity = 0;
	} else if(!ptr) {
		ptr = (char*)malloc(new_capacity);
		if(!ptr)
			ThrowInternalError("out of memory");
		capacity = new_capacity;
	} else if(char* newptr = (char*)realloc(ptr,new_capacity)) {
		ptr = newptr;
		capacity = new_capacity;
	} else
		ThrowInternalError("out of memory");
}
Example #2
0
void HttpServerConnection::writeResponseCode(int code,const char* message) {
	if(write_state != LINE)
		ThrowInternalError("cannot write response code");
	write_state = HEADER;
	async_printf("HTTP/%s %d %s\r\nConnection: %s\r\n%s",(version==HTTP_1_1?"1.1":"1.0"),code,message,
		keep_alive?"keep-alive":"close",out_encoding_chunked?"Transfer-Encoding: chunked\r\n":"");
}
Example #3
0
/*----------------------------------------------------------------------------------------------
	Create a property with the given writing system, old writing system, and named style (ktptNamedStyle).
	Note that ktptCharStyle (which this used to use) is effectively obsolete.
----------------------------------------------------------------------------------------------*/
STDMETHODIMP TsPropsFact::MakePropsRgch(const OLECHAR * prgch, int cch,	int ws, int ows,
	ITsTextProps ** ppttp)
{
	BEGIN_COM_METHOD;
	ChkComArrayArg(prgch, cch);
	ChkComOutPtr(ppttp);
	if ((uint)ws > kwsLim)
		ThrowInternalError(E_INVALIDARG, "Magic writing system invalid in string");

	TsIntProp tip;
	TsStrProp tsp;
	int ctip = 0;
	int ctsp = 0;

	tip.m_nVal = ws;
	tip.m_nVar = ows;
	tip.m_tpt = ktptWs;
	ctip = 1;
	if (cch)
	{
		StrUni stu(prgch, cch);
		TsStrHolder * ptsh = TsStrHolder::GetStrHolder();
		tsp.m_hstuVal = ptsh->GetCookieFromString(stu);
		tsp.m_tpt = ktptNamedStyle;
		ctsp = 1;
	}
	TsTextProps::Create(ctip ? &tip : NULL, ctip, ctsp ? &tsp : NULL, ctsp, ppttp);

	END_COM_METHOD(g_factPropsFact, IID_ITsPropsFactory);
}
Example #4
0
/*----------------------------------------------------------------------------------------------
	First step of displaying the modal dialog: create the dialog object and initialize it.
----------------------------------------------------------------------------------------------*/
void FwCppStylesDlg::SetupForDoModal()
{
    if (m_sdt == ksdtStandard)
        m_qafsd.Attach(NewObj AfStylesDlg);
    else if (m_sdt == ksdtTransEditor)
        m_qafsd.Attach(NewObj TeStylesDlg(m_fShowAll));
    else
        ThrowInternalError(E_UNEXPECTED);

    m_qafsd->SetMsrSys(m_nMsrSys);
    m_qafsd->SetUserWs(m_wsUser);
    m_qafsd->SetHelpFile(m_strHelpFile.Chars());
    m_qafsd->SetCustomUserLevel(m_nCustomStyleLevel);
    m_qafsd->SetAppClsid(&m_clsidApp);

    for (int i = 0; i < AfStylesDlg::kcdlgv; i++)
    {
        if (m_strTabHelpFileUrl[i].Length() > 0)
            m_qafsd->SetTabHelpFileUrl(i, m_strTabHelpFileUrl[i].Chars());
    }
    m_qafsd->SetLgWritingSystemFactory(m_qwsf);
    m_qafsd->SetApplicableStyleContexts(m_vApplicableContexts);
    m_qafsd->SetHelpTopicProvider(m_qhtprov);
    m_qafsd->SetupForAdjustTsTextProps(m_fCanDoRtl, m_fOuterRtl, m_fFontFeatures,
                                       m_f1DefaultFont, m_qvss, m_vqttpPara, m_vqttpChar, m_fCanFormatChar, m_fReloadDb,
                                       m_vwsAvailable, m_hvoRootObj, m_qstrmLog, m_stuStyleName, m_fOnlyCharStyles);
}
Example #5
0
void HttpServerConnection::writeHeader(const char* header,const char* value) {
	if(write_state == LINE)
		writeResponseCode(200,"OK");
	else if(write_state != HEADER) // could keep a chain to write after the body if chunk encoded
		ThrowInternalError("cannot write response code");
	async_printf("%s: %s\r\n",header,value);
}
Example #6
0
ResizeableBuffer& ResizeableBuffer::write_ptr(const void* aptr,size_t alen) {
	if(1>alen)
		ThrowInternalError("invalid length");
	ensure_capacity(alen);
	memcpy(ptr+len,aptr,alen);
	len += alen;
	return *this;
}
Example #7
0
	virtual void ProcessAttach(void)
	{
		HRESULT hr;

		if (FAILED(hr = ::CreateErrorInfo(&s_qcerrinfoMem)))
			ThrowInternalError(hr);
		if (FAILED(hr = s_qcerrinfoMem->QueryInterface(IID_IErrorInfo,
			(LPVOID FAR*) &s_qerrinfoMem)))
		{
			// We should have plenty of memory as we start up components!
			ThrowInternalError(hr);
		}
		StrUni stuDesc(kstidOutOfMemory);
		s_qcerrinfoMem->SetDescription(stuDesc.Bstr());
		// We can't set the IID or source yet.
		s_qcerrinfoMem->SetHelpFile(const_cast<OLECHAR *>(GetModuleHelpFilePath().Chars()));
		s_qcerrinfoMem->SetHelpContext(khcidHelpOutOfMemory);
	}
Example #8
0
void HttpServerConnection::finishHeader() {
	if(write_state == LINE || write_state == HEADER) {
		if(write_state == LINE)
			writeResponseCode(200,"OK");
		if(!out_encoding_chunked)
			async_write("\r\n");
		write_state = BODY;
	} else if(write_state != BODY)
		ThrowInternalError("connection not ready for body");
}
Example #9
0
/*----------------------------------------------------------------------------------------------
	Set the database root object id for the current program.
----------------------------------------------------------------------------------------------*/
STDMETHODIMP FwCppStylesDlg::put_RootObjectId(int hvoRootObj)
{
    BEGIN_COM_METHOD;
    if (hvoRootObj == 0)
        ThrowInternalError(E_INVALIDARG);

    m_hvoRootObj = hvoRootObj;

    END_COM_METHOD(g_factOPD, IID_IFwCppStylesDlg);
}
Example #10
0
/*----------------------------------------------------------------------------------------------
	Create a property with the given writing system, old writing system, and named style (ktptNamedStyle).
	Note that ktptCharStyle (which this used to use) is effectively obsolete.
----------------------------------------------------------------------------------------------*/
STDMETHODIMP TsPropsFact::MakeProps(BSTR bstr, int ws, int ows, ITsTextProps ** ppttp)
{
	BEGIN_COM_METHOD;
	ChkComBstrArgN(bstr);
	ChkComOutPtr(ppttp);
	if ((uint)ws > kwsLim)
		ThrowInternalError(E_INVALIDARG, "Magic writing system invalid in string");

	return MakePropsRgch(bstr, BstrLen(bstr), ws, ows, ppttp);

	END_COM_METHOD(g_factPropsFact, IID_ITsPropsFactory);
}
Example #11
0
ResizeableBuffer& ResizeableBuffer::nprintf(size_t maxlen,const char* const fmt,...) {
	va_list args;
	va_start(args,fmt);
	ensure_capacity(maxlen);
	const int used = vsnprintf(ptr+len,maxlen,fmt,args);
	va_end(args);
	check(used);
	if(used==(int)maxlen)
		ThrowInternalError("buffer overflow");
	len += used;
	return *this;
}
Example #12
0
void NetworkPNL::GetValue(int node, bool &valueValid, std::vector<int> &parents, std::vector<double> &values)
{
    MarkCallFunction("GetValue unfin x", true);
    int len = GetOutcomeCount(node);
    MarkCallFunction("GetValue unfin x", true, (String() << node << "#" << len).c_str());

    TokArr evid(m_pWNet->Net().EvidenceBoard()->Get());
    parents.resize(0);
    values.resize(0);
    m_pWNet->ClearEvid();
    if(evid.size())
    {
        if ( m_pWNet->Net().nNetNode() > 1)
        {
            m_pWNet->EditEvidence(evid);
            evid = m_pWNet->GetJPD(Graph().NodeName(node));
        }
        else
        {
    	    valueValid = false;
	        return;
        }
    }
    else
    {
        evid = m_pWNet->GetJPD(Graph().NodeName(node));
    }
    valueValid = true;
    values.resize(len);

    Vector<int> aiNode, aiValue;

    String x;
    int i;

    x = String(evid);

    //    Token().Resolve(evid);
    Net().ExtractTokArr(evid, &aiNode, &aiValue);
    for(i = evid.size(); --i >= 0;)
    {
	if(aiValue[0] >= len || aiValue[0] < 0)
	{
	    ThrowInternalError("outcome index exceed limit", "GetValue");
	    valueValid = false;
	    return;
	}
	values[aiValue[i]] = evid[i].FltValue();
    }
}
Example #13
0
pnl::CPNLBase *PersistProbabilisticNet::Load(pnl::CContextLoad *pContext)
{
    int nNode = -1;
    int i;
    WNodeInfo* pNodeInfo;
    String modelType;
    
    pContext->GetAttribute(modelType, "ModelType");
    if(!modelType.length())
    {
        modelType = "bnet";
    }
    ProbabilisticNet *net = new ProbabilisticNet(modelType.c_str());
    
    pContext->GetAttribute(&nNode, "NumberOfNodes");
    for(i = 0; i < nNode; ++i)
    {
	pnl::pnlString name("Node");

	name << i;

	pNodeInfo = static_cast<WNodeInfo*>(pContext->Get(name.c_str()));
        pnl::EIDNodeState ns = pNodeInfo->m_NodeType.GetNodeState();

        TokArr *classificator;

        if(!pNodeInfo->m_NodeType.IsDiscrete())
        {
            classificator = &continuous;
        }
        else // discrete
        {
            switch(ns)
            {
            case pnl::nsChance:   classificator = &chance;    break;
            case pnl::nsDecision: classificator = &decision;  break;
            case pnl::nsValue:    classificator = &value;     break;
            default: ThrowInternalError("Unknown node state", "LoadNet");break;
            }
        }
        net->AddNode(*classificator ^ pNodeInfo->m_Name, pNodeInfo->m_aValue);
    }

    return new pnl::CCover<ProbabilisticNet>(net);
}
Example #14
0
static void TranslatePropertyFromReal(NetworkPNL::PropertyMap *to, const NetworkPNL::PropertyRealMap &from)
{
    NetworkPNL::PropertyRealMap::const_iterator it, itEnd;
    int i;

    it = from.begin();
    itEnd = from.end();
    to->resize(0);
    to->reserve(from.size());
    for(i = 0; it != itEnd; ++it, ++i)
    {
	to->push_back(std::pair<std::string, std::string>(it->first.c_str(), it->second.c_str()));
    }
    if(i != from.size())
    {
	ThrowInternalError("Bad coping", "TranslatePropertyFromReal");
    }
}
Example #15
0
int NetworkPNL::GetEvidence(int node)
{
    MarkCallFunction("GetEvidence", true);
    Vector<int> aiNode, aiValue;
    if (m_pWNet->Net().EvidenceBoard()->IsEmpty())
        return -1;
    if (!(m_pWNet->Net().EvidenceBoard()->IsNodeHere(Tok(m_pWNet->Net().Token().Node(node)))) || 
        m_pWNet->Net().EvidenceBoard()->IsHidden(Tok(m_pWNet->Net().Token().Node(node))))
        return -1;
    Net().ExtractTokArr(m_pWNet->Net().EvidenceBoard()->Get(), &aiNode, &aiValue);
    for(int i = aiNode.size(); --i >= 0;)
    {
	if(aiNode[i] == node)
	{
	    return aiValue[i];
	}
    }

    ThrowInternalError("Not found evidence", "GetEvidence");// must be here, but ...
    return -1;
}
Example #16
0
/*----------------------------------------------------------------------------------------------
	This method is called by CheckHr (with punk and iid null) or CheckExtHr, after confirming
	that hrErr is an error HRESULT.

	It first confirms that there is an error info object available. If punk and iid
	are supplied, it further checks that the error info object is relevant to that object and
	interface.

	If a relevant error object is available, and it indicates that a programming error has
	occurred, and its Description does not yet contain a stack dump, we add one if possible.
	Then we ThrowHr, with a special HelpId to indicate that HandleThrowable need not generate
	a new error object.

	If no relevant error object is available, we generate a stack dump and treat the problem
	as an internal error.
----------------------------------------------------------------------------------------------*/
void CheckHrCore(HRESULT hrErr)
{
	IErrorInfoPtr qerrinfo;
	::GetErrorInfo(0, &qerrinfo); // This clears the system wide error info
	if (!qerrinfo)
	{
		// We didn't have any (relevant) error info
		ThrowInternalError(hrErr);
	}

	SmartBstr sbstrDesc;
	qerrinfo->GetDescription(&sbstrDesc);

	// We have an error info object, and presume that it is relevant.
	// If it indicates a programming error, and doesn't already contain a
	// stack dump, try to add one.
	if (hrErr == E_INVALIDARG || hrErr == E_POINTER || hrErr == E_UNEXPECTED)
	{
		// If so look for stack dump type info.
		std::wstring strDesc = sbstrDesc;
		if (!wcsstr(strDesc.c_str(), ThrowableSd::MoreSep()))
		{
			// no stack there, so add one
			DumpStackHere("Error was detected by CheckHr here:\r\n");
			StrUni stuDescNew;
			stuDescNew.Format(L"%s%s%S", sbstrDesc.Chars(), ThrowableSd::MoreSep(),
				StackDumper::GetDump());
			sbstrDesc.Append(const_cast<OLECHAR *>(stuDescNew.Chars()));

			// Now modify the error info
			ICreateErrorInfoPtr qcerrinfo;
			if (SUCCEEDED(qerrinfo->QueryInterface(IID_ICreateErrorInfo, (LPVOID FAR*) &qcerrinfo)))
				qcerrinfo->SetDescription(sbstrDesc);
		}
	}
	// Throw an error indicating there is already a good error object in place.
	ThrowHr(hrErr, sbstrDesc.Bstr(), -1, qerrinfo);
}
Example #17
0
/*----------------------------------------------------------------------------------------------
	Generate a sort key.
	If output pointer is null, just gives the needed length in *pcchKey.
	prgchSource: string sort key is to be generated for.
	cchSource: number of characters in prgchSource.
	cchMaxKey: space available in prgchKey.
	prgchKey: variable that will contain sort key.
	pcchKey: Number of characters in prgchKey.
	This method generates a sort key with full decompositions, it takes into consideration
	ignorable characters (fVariant).  It also establishes collating elements for expansions.
	ENHANCE: As of now, this method does not support contractions,  reordering
		  or direction.
----------------------------------------------------------------------------------------------*/
STDMETHODIMP LgUnicodeCollater::SortKeyRgch(const OLECHAR * prgchSource, int cchSource,
			LgCollatingOptions colopt, int cchMaxKey, OLECHAR * prgchKey, int * pcchKey)
{
	BEGIN_COM_METHOD
	ChkComArrayArg(prgchSource, cchSource);
	ChkComArrayArg(prgchKey, cchMaxKey);
	if ((uint) colopt > (uint)fcoLim)
		ThrowInternalError(E_INVALIDARG, "Invalid collating options");
	ChkComArgPtr(pcchKey);

	// Create a pointer to LgCharacterPropertyEngine to access get_FullDecomp
	// ENHANCE JohnT: Should this be the default character property engine or a ws-specific one?
	if (!m_qcpe) //m_qcpe is initialized to null in constructor.
	{
		CheckHr(LgIcuCharPropEngine::GetUnicodeCharProps(&m_qcpe));
	}
	const OLECHAR * pchSource;	// points to next char to process, in prgchSource
	OLECHAR * pch;			// points to next char to process, in rgchDecomp
	OLECHAR * pchLim;
	#define MAXDECOMP 256
	OLECHAR rgchDecomp[MAXDECOMP];	// holds decompositions
	int cchDecomp;			// character count in decomposition

	OLECHAR * pchKey = prgchKey;

	const OLECHAR * pchLimSource = prgchSource + cchSource;
	CollatingElement * pcolel; // pointer to next collating element to do
	CollatingElement * pcolelLim; //will be assigned limit address in "multiple" loop
	int cchOut = 0;				// count of characters we have output
	bool fEven = true;      // true for first char of pair at levels 2 and 3

	int cchMaxOut = cchMaxKey;
	if (!cchMaxKey)
	{
		// Set a large limit so we don't report errors below, and ensure we don't output
		// anything, even if we were given a pointer to a real buffer
		cchMaxOut = INT_MAX;
		pchKey = NULL;
	}

	//Enter weight 1's into sort key
	for (pchSource = prgchSource; pchSource < pchLimSource; pchSource++)
	{
		ComBool fHasDecomp;
		// If there is no decomposition, this routine copies the one character we passed into
		// rgchDecomp.  Otherwise, it puts the decomposition there.
		CheckHr(m_qcpe->FullDecompRgch(*pchSource, MAXDECOMP, rgchDecomp, &cchDecomp,
						&fHasDecomp));
		pchLim = rgchDecomp + cchDecomp;
		for (pch = rgchDecomp; pch < pchLim; pch++)
		{
			int icolel = FindColel(*pch);
			if(icolel == -1)//an index of -1 means the weights are the standard (U, 0x20, 2)
			{
				cchOut++;
				if(cchOut > cchMaxOut)
					return E_FAIL;
				if(pchKey)
					*pchKey++ = *pch;
				continue;
			}
			pcolel = const_cast <CollatingElement *> (g_prgcolel + icolel);
			if((colopt & fcoDontIgnoreVariant) == 0)
			{
				if(pcolel->Variant())
					continue;
			}
			int ccolel = 1; // by default we have just one, the one we point at now
			if (pcolel->Multiple())
			{
				// there are several to process
				ccolel = pcolel->uWeight3; // before we change pcolel!
				// move pcolel to point at the list in the multiple array
				pcolel = const_cast<CollatingElement *>(g_prgcolelMultiple + pcolel->MultipleIndex());
			}
			pcolelLim = pcolel + ccolel;
			for(;pcolel < pcolelLim; pcolel++)
			{
				int nWeight;
				nWeight = pcolel->uWeight1;
				if (nWeight)
				{
					cchOut++;
					if (cchOut > cchMaxOut)
						return E_FAIL;
					if (pchKey)
						*pchKey++ = (OLECHAR) nWeight;
				}
			}
		}
	}

	//enter level separator into array
	if(pchKey)
	{
		*pchKey++ = 0x0001;
	}
	cchOut++;
	if(cchOut > cchMaxOut)
		return E_FAIL;

	//Packing weight 2's two per character.  If there is an odd number of weight 2's, the LSB of the
	//last character is padded with zero.
	for (pchSource = prgchSource; pchSource < pchLimSource; pchSource++)
	{
		ComBool fHasDecomp;
		// If there is no decomposition, this routine copies the one character we passed into
		// rgchDecomp.  Otherwise, it puts the decomposition there.
		CheckHr(m_qcpe->FullDecompRgch(*pchSource, MAXDECOMP, rgchDecomp, &cchDecomp,
												&fHasDecomp));
		pchLim = rgchDecomp + cchDecomp;
		for (pch = rgchDecomp; pch < pchLim; pch++)
		{
			int icolel = FindColel(*pch);
			if(icolel == -1)
			{
				if (!PackWeights(pchKey, cchOut, cchMaxOut, 0x20, fEven))
					return E_FAIL;
				continue;
			}
			pcolel = const_cast<CollatingElement *>(g_prgcolel + icolel);
			if((colopt & fcoDontIgnoreVariant) == 0)
			{
				if(pcolel->Variant())
					continue;
			}

			int ccolel = 1; // by default we have just one, the one we point at now
			if (pcolel->Multiple())
			{
				// there are several to process
				ccolel = pcolel->uWeight3; // before we change pcolel!
				// move pcolel to point at the list in the multiple array
				pcolel =const_cast<CollatingElement *>(g_prgcolelMultiple + pcolel->MultipleIndex());
			}
			pcolelLim = pcolel + ccolel;
			for(;pcolel < pcolelLim; pcolel++)
			{
				int nWeight;
				nWeight = pcolel->uWeight2;
				if (nWeight)
				{
					if (!PackWeights(pchKey, cchOut, cchMaxOut, nWeight, fEven))
						return E_FAIL;
				}
			}
		}
	}
	//uWeight3 is normally a case indicator.  If fcoIgnoreCase is set, case is ignored,
	//therefore uWeight3 is ignored in the sort key.
	if(colopt & fcoIgnoreCase)
	{
		*pcchKey = cchOut;
		return S_OK;
	}
	//enter level separator into array
	if(pchKey)
	{
		*pchKey++ = 0x0001;
	}
	cchOut++;
	if(cchOut > cchMaxOut)
		return E_FAIL;
	fEven = true;

	//Treating weight 3's like weight 2's
	for (pchSource = prgchSource; pchSource < pchLimSource; pchSource++)
	{
		ComBool fHasDecomp;
		// If there is no decomposition, this routine copies the one character we passed into
		// rgchDecomp.  Otherwise, it puts the decomposition there.
		CheckHr(m_qcpe->FullDecompRgch(*pchSource, MAXDECOMP, rgchDecomp, &cchDecomp,
												&fHasDecomp));
		pchLim = rgchDecomp + cchDecomp;
		for (pch = rgchDecomp; pch < pchLim; pch++)
		{
			int icolel = FindColel(*pch);
			if(icolel == -1) //use the standard weights
			{
				if (!PackWeights(pchKey, cchOut, cchMaxOut, 0x02, fEven))
					return E_FAIL;
				continue;
			}
			pcolel = const_cast<CollatingElement *>(g_prgcolel + icolel);
			if((colopt & fcoDontIgnoreVariant) == 0)
			{
				if(pcolel->Variant())
					continue;
			}

			int ccolel = 1; // by default we have just one, the one we point at now
			if (pcolel->Multiple())
			{
				// there are several to process
				ccolel = pcolel->uWeight3; // before we change pcolel!
				// move pcolel to point at the list in the multiple array
				pcolel = const_cast<CollatingElement *>(g_prgcolelMultiple + pcolel->MultipleIndex());
			}
			pcolelLim = pcolel + ccolel;
			for(;pcolel < pcolelLim; pcolel++)
			{
				int nWeight;
				nWeight = pcolel->uWeight3;
				if (nWeight)
				{
					if (!PackWeights(pchKey, cchOut, cchMaxOut, nWeight, fEven))
						return E_FAIL;
				}
			}
		}
	}
	if(pchKey)//level separator
	{
		*pchKey++ = 0x0001;
	}
	cchOut++;
	if(cchOut > cchMaxOut)
		return E_FAIL;

	//add the actual characters to the sort key
	for (pchSource = prgchSource; pchSource < pchLimSource; pchSource++)
	{
		cchOut++;
		if (cchOut > cchMaxOut)
			return E_FAIL;
		if (pchKey)
			*pchKey++ = *pchSource;
	}
	*pcchKey = cchOut;
	END_COM_METHOD(g_fact, IID_ILgCollatingEngine);
}
Example #18
0
/*----------------------------------------------------------------------------------------------
	Renders the data described in a FORMATETC structure and transfers it through the STGMEDIUM
	structure.

	This is a standard COM IDataObject method.

	@param pfmte Pointer to a FORMATETC structure describing the desired data format.
	@param pmedium Pointer to a STGMEDIUM structure that defines the output medium.

	@return S_OK, DV_E_DVASPECT, DV_E_FORMATETC, DV_E_LINDEX, DV_E_TYMED, E_POINTER,
					E_UNEXPECTED, or E_NOTIMPL.
----------------------------------------------------------------------------------------------*/
STDMETHODIMP LgTsDataObject::GetData(FORMATETC * pfmte, STGMEDIUM * pmedium)
{
	BEGIN_COM_METHOD;
	ChkComArgPtr(pfmte);
	ChkComArgPtr(pmedium);
	AssertPtr(m_qtsswss.Ptr());
	if (pfmte->lindex != -1 && pfmte->lindex != 1)
		return DV_E_LINDEX;
	if (pfmte->dwAspect && pfmte->dwAspect != DVASPECT_CONTENT)
		return DV_E_DVASPECT;	// Invalid dwAspect value.

	if (pfmte->cfFormat == LgTsDataObject::s_cfTsString)
	{
		if (pfmte->tymed == TYMED_NULL)
		{
			pmedium->tymed = TYMED_NULL;
			pmedium->pstm = NULL;
			pmedium->pUnkForRelease = NULL;
			return S_OK;
		}
		if (pfmte->tymed & TYMED_ISTORAGE)
		{
			// Since we have no idea where to put the IStorage object, this particular request
			// is handled by GetDataHere instead.
			return E_NOTIMPL;
		}
		else
		{
			return DV_E_TYMED;
		}
	}
	else if (pfmte->cfFormat == CF_TEXT)
	{
		if (pfmte->tymed == TYMED_NULL)
		{
			pmedium->tymed = TYMED_NULL;
			pmedium->pstm = NULL;
			pmedium->pUnkForRelease = NULL;
			return S_OK;
		}
		if (pfmte->tymed & TYMED_HGLOBAL)
		{
			SmartBstr sbstr;
			CheckHr(m_qtsswss->get_Text(&sbstr));
			StrUni stu = sbstr.Chars();
			if (!StrUtil::NormalizeStrUni(stu, UNORM_NFC))
				ThrowInternalError(E_FAIL, "Normalize failure in StringDataObject::GetData.");
			StrAnsi sta(stu);
			pmedium->tymed = TYMED_HGLOBAL;
			pmedium->pUnkForRelease = NULL;
			pmedium->hGlobal = ::GlobalAlloc(GHND, (DWORD)(sta.Length() + 1));
			if (pmedium->hGlobal)
			{
				char * pszDst;
				pszDst = (char *)::GlobalLock(pmedium->hGlobal);
				strcpy_s(pszDst, sta.Length() + 1, sta.Chars());
				::GlobalUnlock(pmedium->hGlobal);
			}
			return S_OK;
		}
		if (!(pfmte->tymed & TYMED_HGLOBAL))
			return DV_E_TYMED;
		else
			return E_UNEXPECTED;
	}
	else if (pfmte->cfFormat == CF_OEMTEXT)
	{
		if (pfmte->tymed == TYMED_NULL)
		{
			pmedium->tymed = TYMED_NULL;
			pmedium->pstm = NULL;
			pmedium->pUnkForRelease = NULL;
			return S_OK;
		}
		if (pfmte->tymed & TYMED_HGLOBAL)
		{
			// REVIEW SteveMc: How does CF_OEMTEXT differ from CF_TEXT?
			SmartBstr sbstr;
			CheckHr(m_qtsswss->get_Text(&sbstr));
			StrUni stu = sbstr.Chars();
			if (!StrUtil::NormalizeStrUni(stu, UNORM_NFC))
				ThrowInternalError(E_FAIL, "Normalize failure in StringDataObject::GetData.");
			StrAnsi sta(stu);
			pmedium->tymed = TYMED_HGLOBAL;
			pmedium->pUnkForRelease = NULL;
			pmedium->hGlobal = ::GlobalAlloc(GHND, (DWORD)(sta.Length() + 1));
			if (pmedium->hGlobal)
			{
				char * pszDst;
				pszDst = (char *)::GlobalLock(pmedium->hGlobal);
				strcpy_s(pszDst, sta.Length() + 1, sta.Chars());
				::GlobalUnlock(pmedium->hGlobal);
			}
			return S_OK;
		}
		if (!(pfmte->tymed & TYMED_HGLOBAL))
			return DV_E_TYMED;
	}
	else if (pfmte->cfFormat == CF_UNICODETEXT)
	{
		if (pfmte->tymed == TYMED_NULL)
		{
			pmedium->tymed = TYMED_NULL;
			pmedium->pstm = NULL;
			pmedium->pUnkForRelease = NULL;
			return S_OK;
		}
		if (pfmte->tymed & TYMED_HGLOBAL)
		{
			SmartBstr sbstr;
			CheckHr(m_qtsswss->get_Text(&sbstr));
			StrUni stu = sbstr.Chars();
			if (!StrUtil::NormalizeStrUni(stu, UNORM_NFC))
				ThrowInternalError(E_FAIL, "Normalize failure in StringDataObject::GetData.");
			pmedium->tymed = TYMED_HGLOBAL;
			pmedium->pUnkForRelease = NULL;
			int cb = isizeof(wchar) * (stu.Length() + 1);
			pmedium->hGlobal = ::GlobalAlloc(GHND, (DWORD)cb);
			if (pmedium->hGlobal)
			{
				wchar * pszDst;
				pszDst = (wchar *)::GlobalLock(pmedium->hGlobal);
				memcpy(pszDst, stu.Chars(), cb);
				::GlobalUnlock(pmedium->hGlobal);
			}
			return S_OK;
		}
		if (!(pfmte->tymed & TYMED_HGLOBAL))
			return DV_E_TYMED;
		else
			return E_UNEXPECTED;
	}
	else
	{
		return DV_E_FORMATETC;
	}
	END_COM_METHOD(g_fact, IID_IDataObject);
}
Example #19
0
bool NetworkPNL::Save(const char *filename, IXmlWriterExtension *externalExtension,
                       const LegacyDslFileInfo *gnet)
{
    MarkCallFunction("Save", true);
    static const char fname[] = "Save";
    pnl::CContextPersistence saver;
    pnl::CXMLWriterStd writer;
    pnl::CGroupObj pnlhGroup;
    bool bWriteNodeProperty = false;

    if(!writer.OpenFile(filename))
    {
        ThrowUsingError("can't open file", fname);
    }
    if(!m_pWNet->Net().SaveNet(&saver, &pnlhGroup))
    {
        ThrowInternalError("Can't save file", fname);
    }
    saver.Put(&pnlhGroup, "WrapperInfo", false);

    pnl::CGroupObj propertyGroup, propertyNodes, propDiagInfo;

    propertyGroup.Put(new pnl::CCover<PropertyRealMap >(&m_NetProperty),
        "NetProperty", true);

    Vector<String> aNodeName = Graph().Names();
    String name;
    int i, j, k;
    std::vector<NodeDiagInfo> diagInfo;
    diagInfo.resize(aNodeName.size());

    for(i = 0; i < aNodeName.size(); ++i)
    {
        switch (GetDiagType(i))
        {
        case 1:
            diagInfo[i].m_diagType = "Target";
            break;
        case 2:
            diagInfo[i].m_diagType = "Observation";
            break;
        case 3:
            diagInfo[i].m_diagType = "Auxiliary";
            break;
        }
        diagInfo[i].m_isMandatory = IsMandatory(i);
        diagInfo[i].m_isRanked = IsRanked(i);
        diagInfo[i].m_isDefault = GetDefaultOutcome(i);
        std::vector<bool> targetStates;
        diagInfo[i].m_isTarget.resize(GetOutcomeCount(i));
        for (k = 0; k < GetOutcomeCount(i); ++k)
        {
            diagInfo[i].m_isTarget[k] = IsFaultOutcome(i,k);
        }
        std::vector<double> costs;
        costs.resize(0);
        GetCost(i, costs);
        diagInfo[i].cost = costs[0];
        name = aNodeName[i];
        propDiagInfo.Put(new pnl::CCover<NodeDiagInfo >(&diagInfo[i]),
            name.c_str(), true);
        j = Graph().INode(aNodeName[i]);
        if(!m_aNodeProperty[j].size())
        {
            continue;
        }
        bWriteNodeProperty = true;
        name = aNodeName[i];
        name << ".property";
        propertyNodes.Put(new pnl::CCover<PropertyRealMap >(&m_aNodeProperty[j]),
            name.c_str(), true);
    }
    if(bWriteNodeProperty)
    {
        propertyGroup.Put(&propertyNodes, "Nodes", false);
    }

    saver.Put(&propertyGroup, "Bridge_PNL_to_GeNIe", false);
    saver.Put(&propDiagInfo, "DiagnosisInfo", false);

    if(!saver.SaveViaWriter(&writer))
    {
	ThrowInternalError("Can't save file", fname);
    }

    XmlWriterPNLH genieWriter(&writer);
    externalExtension->WriteExtension(&genieWriter);
    if(!writer.CloseFile())
    {
	ThrowInternalError("Can't close file", fname);
    }

    return true;
}
Example #20
0
/*----------------------------------------------------------------------------------------------
	Write an integer-valued text property in XML format.

	@param pstrm Pointer to an IStream for output.
	@param tpt
	@param nVar
	@param nVal
----------------------------------------------------------------------------------------------*/
void FwXml::WriteIntTextProp(IStream * pstrm, ILgWritingSystemFactory * pwsf, int tpt, int nVar,
	int nVal)
{
	AssertPtr(pstrm);
	AssertPtr(pwsf);

	switch (tpt)
	{
	case ktptBackColor:
		FormatToStream(pstrm, " backcolor=\"%s\"", ColorName(nVal));
		break;
	case ktptBold:
		FormatToStream(pstrm, " bold=\"%s\"", ToggleValueName((byte)nVal));
		break;
	case ktptWs:
		if (nVal == 0)
		{
			Assert(nVar == 0);
		}
		else
		{
			SmartBstr sbstrWs;
			CheckHr(pwsf->GetStrFromWs(nVal, &sbstrWs));
			if (!sbstrWs.Length())
				ThrowInternalError(E_INVALIDARG, "Writing system invalid for <Run ws>");
			FormatToStream(pstrm, " ws=\"", nVal);
			WriteXmlUnicode(pstrm, sbstrWs.Chars(), sbstrWs.Length());
			FormatToStream(pstrm, "\"", nVal);
		}
		break;
	case ktptBaseWs:
		if (nVal == 0)
		{
			Assert(nVar == 0);
		}
		else
		{
			SmartBstr sbstrWs;
			CheckHr(pwsf->GetStrFromWs(nVal, &sbstrWs));
			if (!sbstrWs.Length())
				ThrowInternalError(E_INVALIDARG, "Writing system invalid for <Run wsBase>");
			FormatToStream(pstrm, " wsBase=\"", nVal);
			WriteXmlUnicode(pstrm, sbstrWs.Chars(), sbstrWs.Length());
			FormatToStream(pstrm, "\"", nVal);
		}
		break;
	case ktptFontSize:
		FormatToStream(pstrm, " fontsize=\"%d\"", nVal);
		if (nVar != ktpvDefault)
			FormatToStream(pstrm, " fontsizeUnit=\"%s\"", PropVarName(nVar));
		break;
	case ktptForeColor:
		FormatToStream(pstrm, " forecolor=\"%s\"", ColorName(nVal));
		break;
	case ktptItalic:
		FormatToStream(pstrm, " italic=\"%s\"", ToggleValueName((byte)nVal));
		break;
	case ktptOffset:
		FormatToStream(pstrm, " offset=\"%d\"", nVal);
		FormatToStream(pstrm, " offsetUnit=\"%s\"",	PropVarName(nVar));
		break;
	case ktptSuperscript:
		FormatToStream(pstrm, " superscript=\"%s\"", SuperscriptValName((byte)nVal));
		break;
	case ktptUnderColor:
		FormatToStream(pstrm, " undercolor=\"%s\"", ColorName(nVal));
		break;
	case ktptUnderline:
		FormatToStream(pstrm, " underline=\"%s\"", UnderlineTypeName((byte)nVal));
		break;
	case ktptSpellCheck:
		FormatToStream(pstrm, " spellcheck=\"%s\"", SpellingModeName((byte)nVal));
		break;

	//	Paragraph-level properties:

	case ktptAlign:
		FormatToStream(pstrm, " align=\"%s\"", AlignmentTypeName((byte)nVal));
		break;
	case ktptFirstIndent:
		FormatToStream(pstrm, " firstIndent=\"%d\"", nVal);
		break;
	case ktptLeadingIndent:
		FormatToStream(pstrm, " leadingIndent=\"%d\"", nVal);
		break;
	case ktptTrailingIndent:
		FormatToStream(pstrm, " trailingIndent=\"%d\"", nVal);
		break;
	case ktptSpaceBefore:
		FormatToStream(pstrm, " spaceBefore=\"%d\"", nVal);
		break;
	case ktptSpaceAfter:
		FormatToStream(pstrm, " spaceAfter=\"%d\"", nVal);
		break;
	case ktptTabDef:
		FormatToStream(pstrm, " tabDef=\"%d\"", nVal);
		break;
	case ktptLineHeight:
		FormatToStream(pstrm, " lineHeight=\"%d\"", abs(nVal));
		FormatToStream(pstrm, " lineHeightUnit=\"%s\"",	PropVarName(nVar));
		Assert(nVal >= 0 || nVar == ktpvMilliPoint);
		if (nVar == ktpvMilliPoint)
		{
			// negative means "exact" internally.  See FWC-20.
			FormatToStream(pstrm, " lineHeightType=\"%s\"", nVal < 0 ? "exact" : "atLeast");
		}
		break;
	case ktptParaColor:
		FormatToStream(pstrm, " paracolor=\"%s\"", ColorName(nVal));
		break;

	//	Properties from the views subsystem:

	case ktptRightToLeft:
		FormatToStream(pstrm, " rightToLeft=\"%d\"", nVal);
		break;
	case ktptPadLeading:
		FormatToStream(pstrm, " padLeading=\"%d\"", nVal);
		break;
	case ktptPadTrailing:
		FormatToStream(pstrm, " padTrailing=\"%d\"", nVal);
		break;
	// Not the other margins: they are duplicated by FirstIndent etc.
	case ktptMarginTop:
		FormatToStream(pstrm, " MarginTop=\"%d\"", nVal);
		break;
	case ktptPadTop:
		FormatToStream(pstrm, " padTop=\"%d\"", nVal);
		break;
	case ktptPadBottom:
		FormatToStream(pstrm, " padBottom=\"%d\"", nVal);
		break;

	case ktptBorderTop:
		FormatToStream(pstrm, " borderTop=\"%d\"", nVal);
		break;
	case ktptBorderBottom:
		FormatToStream(pstrm, " borderBottom=\"%d\"", nVal);
		break;
	case ktptBorderLeading:
		FormatToStream(pstrm, " borderLeading=\"%d\"", nVal);
		break;
	case ktptBorderTrailing:
		FormatToStream(pstrm, " borderTrailing=\"%d\"", nVal);
		break;
	case ktptBorderColor:
		FormatToStream(pstrm, " borderColor=\"%s\"", ColorName(nVal));
		break;

	case ktptBulNumScheme:
		FormatToStream(pstrm, " bulNumScheme=\"%d\"", nVal);
		break;
	case ktptBulNumStartAt:
		FormatToStream(pstrm, " bulNumStartAt=\"%d\"", nVal == INT_MIN ? 0 : nVal);
		break;

	case ktptDirectionDepth:
		FormatToStream(pstrm, " directionDepth=\"%d\"", nVal);
		break;
	case ktptKeepWithNext:
		FormatToStream(pstrm, " keepWithNext=\"%d\"", nVal);
		break;
	case ktptKeepTogether:
		FormatToStream(pstrm, " keepTogether=\"%d\"", nVal);
		break;
	case ktptHyphenate:
		FormatToStream(pstrm, " hyphenate=\"%d\"", nVal);
		break;
	case ktptWidowOrphanControl:
		FormatToStream(pstrm, " widowOrphan=\"%d\"", nVal);
		break;
	case ktptMaxLines:
		FormatToStream(pstrm, " maxLines=\"%d\"", nVal);
		break;
	case ktptCellBorderWidth:
		FormatToStream(pstrm, " cellBorderWidth=\"%d\"", nVal);
		break;
	case ktptCellSpacing:
		FormatToStream(pstrm, " cellSpacing=\"%d\"", nVal);
		break;
	case ktptCellPadding:
		FormatToStream(pstrm, " cellPadding=\"%d\"", nVal);
		break;
	case ktptEditable:
		FormatToStream(pstrm, " editable=\"%s\"", EditableName(nVal));
		break;
	case ktptSetRowDefaults:
		FormatToStream(pstrm, " setRowDefaults=\"%d\"", nVal);
		break;
	case ktptRelLineHeight:
		FormatToStream(pstrm, " relLineHeight=\"%d\"", nVal);
		break;
	case ktptTableRule:
		// Ignore this view-only property.
		break;
	default:
		break;
	}
}
Example #21
0
/*----------------------------------------------------------------------------------------------
	Throw an exception indicating UNEXPECTED failure of a built-in function. This should be
	used only when we believe there is no reason ever to expect failure, but are checking it
	just to be sure. For now treat it as an internal error.
----------------------------------------------------------------------------------------------*/
void ThrowBuiltInError(char * pchFnName)
{
	StrUni stuMsg;
	stuMsg.Format(L"%S unexpectedly failed", pchFnName);
	ThrowInternalError(E_UNEXPECTED, stuMsg.Chars());
}
Example #22
0
void HttpServerConnection::read() {
	while(!is_closed()) {
		switch(read_state) {
		case LINE:
			// get the request line
			try {
				if(!async_read_in(line,sizeof(uri)-1))
					return;
			} catch(EndOfStreamError*) {
				if(!count)
					throw;
				// so we get end-of-stream when keep-alive?  no problem
				return;
			}
			if(!line.ends_with("\r\n",2))
				HttpError::Throw(HttpError::ERequestURITooLong,*this);
			if(!memcmp(line.cstr(),"\r\n",3)) { // empty lines are ok before request line
				line.clear();
				continue;
			}
			count++;
			read_state = HEADER;
			{
				const char* method = strtok(line.cstr()," ");
				strncpy(uri,strtok(NULL," \r"),sizeof(this->uri));
				const char* v = strtok(NULL,"\r");
				if(!memcmp(v,"HTTP/1.1",9))
					version = HTTP_1_1;
				else if(!memcmp(v,"HTTP/1.0",9))
					version = HTTP_1_0;
				else
					version = HTTP_0_9;
				in_encoding_chunked = false;
				in_content_length = -1; // not known
				keep_alive = out_encoding_chunked = (HTTP_1_1 == version);
				on_request(method,uri);
			}
			line.clear();
			break;
		case HEADER:
			if(!async_read_in(line))
				return;
			if(!memcmp("\r\n",line.cstr(),3)) {
				read_state = BODY;
				if(keep_alive && !in_encoding_chunked && (-1 == in_content_length))
					in_content_length = 0; // length isn't specified, yet its keep-alive, so there is no content
				line.clear();
				on_body();
				break;
			}
			if(!line.ends_with("\r\n",2))
				HttpError::Throw(HttpError::ERequestEntityTooLarge,*this);
			{
				const char* header = strtok(line.cstr()," "), *value = strtok(NULL,"\r");
				if(!ends_with(header,":",1))
					HttpError::Throw(HttpError::EBadRequest,*this);
				if((write_state == LINE) && !strcasecmp(header,"connection:") && !strcasecmp(value,"keep-alive"))
					keep_alive = true;
				else if(!strcasecmp(header,"content-length:")) {
					in_content_length = atoi(value);
					if(in_content_length < 0)
						HttpError::Throw(HttpError::EBadRequest,*this);
				} else if(!strcasecmp(header,"transfer-encoding:"))
					in_encoding_chunked = !strcasecmp(value,"chunked");
				on_header(header,value);
			}
			line.clear();
			break;
		case BODY:
			if(in_encoding_chunked) { //RFC2616-s4.4 says this overrides any explicit content-length header
				ThrowInternalError("in encoding chunked not implemented yet");
			} else if(!keep_alive && (-1 == in_content_length)) {
				// read all available
				uint8_t* chunk;
				while(uint16_t len = async_read_buffered(chunk))
					on_data(chunk,len);
			} else if(-1 != in_content_length) {
				// read all available
				while(in_content_length) {
					uint8_t* chunk;
					if(const uint16_t len = async_read_buffered(chunk,in_content_length)) {
						in_content_length -= len;
						on_data(chunk,len);
					} else
						return;
				}
				if(!keep_alive) {
					read_state = FINISHED;
					shutdown(fd,SHUT_RD);
					return;
				}
				read_state = LINE;
			} else
				ThrowInternalError("cannot cope with combination of keep_alive %d, content_length %d and encoding_chunked %d",
					keep_alive,in_content_length,in_encoding_chunked);
			break;
		default:
			ThrowInternalError("unexpected read_state");
		}
	}
}
Example #23
0
/*----------------------------------------------------------------------------------------------
	Saves changes but keeps the editing window open. In this method we need to convert dummy
	items into real items if there are any people present. We also need to delete
	RnRoledPartic and convert the field into a dummy if all of the people have been
	deleted. Otherwise, there is no way for the user to get rid of RnRoledPartic.
	@return True if successful.
----------------------------------------------------------------------------------------------*/
bool RnDeFeRoleParts::SaveEdit()
{
	// See if any items are present.
	int cpss;
	HVO hvopssl = m_vpssl[0];
	ISilDataAccessPtr qsdaTemp;
	HRESULT hr = m_qvcd->QueryInterface(IID_ISilDataAccess, (void **)&qsdaTemp);
	if (FAILED(hr))
		ThrowInternalError(E_INVALIDARG);
	CheckHr(qsdaTemp->get_VecSize(hvopssl, kflidPssIds, &cpss));
	CustViewDaPtr qcvd;
	GetDataAccess(&qcvd);
	AssertPtr(qcvd);

	if (cpss > 1) // Don't count the dummy at the end.
	{
		if (m_hvoObj == khvoDummyRnRoledPartic)
		{
			// We have a dummy RnRoledParticipant with at least one item, so we need to
			// turn the dummy into a real object.
			HVO hvo;
			BeginChangesToLabel();
			CheckHr(qcvd->MakeNewObject(kclidRnRoledPartic, m_hvoOwner, kflidRnEvent_Participants,
				-1, &hvo));
			Assert(hvo);
			m_hvoObj = hvo;

			// If someone deleted the role we are interested in while we are displaying
			// this field, we can't set the object prop or we'll get an error from the
			// database. So before doing a save, make sure our role hasn't been deleted.
			if (m_pssRole)
				CheckHr(qcvd->SetObjProp(hvo, kflidRnRoledPartic_Role, m_pssRole));

			SuperClass::SaveEdit();
			CheckHr(qcvd->EndUndoTask());
			// Need to notify this property after the participants were added in the superclass
			// for this to properly update document views.
			CheckHr(qcvd->PropChanged(m_qrootb, kpctNotifyAllButMe, m_hvoOwner,
				kflidRnEvent_Participants, 1, 1, 0));
			return true;
		}
		else
		{
			// We have a real RnRoledParticipant with at least one item, so handle it as usual.
			bool fDirty = m_fDirty;
			if (!SuperClass::SaveEdit())
				return false;
			if (fDirty)
			{
				// Database triggers/procs do not update the entry, so we must do it here.
				qcvd->SetTimeStamp(m_hvoOwner);
				qcvd->CacheCurrTimeStamp(m_hvoOwner);
			}
			return true;
		}
	}
	else
	{
		if (m_hvoObj == khvoDummyRnRoledPartic)
		{
			// We have a dummy RnRoledParticipant without any people. Do nothing so the
			// field will go away when we move to the next record.
			return true;
		}
		else
		{
			// We have a real RnRoledParticipant with no items, so we need to change this
			// into a dummy RnRoledParticipant and remove it from the database.
			CustViewDaPtr qcvd;
			GetDataAccess(&qcvd);
			AssertPtr(qcvd);
			int ihvo;
			BeginChangesToLabel();
			CheckHr(qcvd->GetObjIndex(m_hvoOwner, kflidRnEvent_Participants, m_hvoObj, &ihvo));
			CheckHr(qcvd->DeleteObjOwner(m_hvoOwner, m_hvoObj, kflidRnEvent_Participants, ihvo));
			CheckHr(qcvd->EndUndoTask());
			m_hvoObj = khvoDummyRnRoledPartic;
			CheckHr(qcvd->PropChanged(m_qrootb, kpctNotifyAllButMe, m_hvoOwner,
				kflidRnEvent_Participants, 1, 0, 1));
			return true;
		}
	}
}