Esempio n. 1
0
BOOL CAuthDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	CWinApp* pApp = AfxGetApp();

	if (pApp->m_pszRegistryKey) {
		CRegKey hSecKey(pApp->GetSectionKey(IDS_R_LOGINS));

		if (hSecKey) {
			int i = 0;
			TCHAR username[256], password[256];

			for (;;) {
				DWORD unlen = _countof(username);
				DWORD pwlen = sizeof(password);
				DWORD type = REG_SZ;

				if (ERROR_SUCCESS == RegEnumValue(hSecKey, i++, username, &unlen, 0, &type, (BYTE*)password, &pwlen)) {
					m_logins[username] = DEncrypt(password);
					m_usernamectrl.AddString(username);
				} else {
					break;
				}
			}
		}
	} else {
		CAutoVectorPtr<TCHAR> buff;
		buff.Allocate(32767/sizeof(TCHAR));

		DWORD len = GetPrivateProfileSection(IDS_R_LOGINS, buff, 32767/sizeof(TCHAR), pApp->m_pszProfileName);

		TCHAR* p = buff;
		while (*p && len > 0) {
			CString str = p;
			p += str.GetLength()+1;
			len -= str.GetLength()+1;
			CAtlList<CString> sl;
			Explode(str, sl, '=', 2);

			if (sl.GetCount() == 2) {
				m_logins[sl.GetHead()] = DEncrypt(sl.GetTail());
				m_usernamectrl.AddString(sl.GetHead());
			}
		}
	}

	m_usernamectrl.SetFocus();

	return TRUE;
}
Esempio n. 2
0
void CWebServer::OnRequest(CWebClientSocket* pClient, CStringA& hdr, CStringA& body)
{
    CPath p(pClient->m_path);
    CStringA ext = p.GetExtension().MakeLower();
    CStringA mime;
    if (ext.IsEmpty()) {
        mime = "text/html";
    } else {
        m_mimes.Lookup(ext, mime);
    }

    hdr = "HTTP/1.0 200 OK\r\n";

    bool fHandled = false, fCGI = false;

    if (!fHandled && m_webroot.IsDirectory()) {
        CStringA tmphdr;
        fHandled = fCGI = CallCGI(pClient, tmphdr, body, mime);

        if (fHandled) {
            tmphdr.Replace("\r\n", "\n");
            CAtlList<CStringA> hdrlines;
            ExplodeMin(tmphdr, hdrlines, '\n');
            POSITION pos = hdrlines.GetHeadPosition();
            while (pos) {
                POSITION cur = pos;
                CAtlList<CStringA> sl;
                CStringA key = Explode(hdrlines.GetNext(pos), sl, ':', 2);
                if (sl.GetCount() < 2) {
                    continue;
                }
                key.Trim().MakeLower();
                if (key == "content-type") {
                    mime = sl.GetTail().Trim();
                    hdrlines.RemoveAt(cur);
                } else if (key == "content-length") {
                    hdrlines.RemoveAt(cur);
                }
            }
            tmphdr = Implode(hdrlines, '\n');
            tmphdr.Replace("\n", "\r\n");
            hdr += tmphdr + "\r\n";
        }
    }

    RequestHandler rh = NULL;
    if (!fHandled && m_internalpages.Lookup(pClient->m_path, rh) && (pClient->*rh)(hdr, body, mime)) {
        if (mime.IsEmpty()) {
            mime = "text/html";
        }

        CString redir;
        if (pClient->m_get.Lookup(_T("redir"), redir)
                || pClient->m_post.Lookup(_T("redir"), redir)) {
            if (redir.IsEmpty()) {
                redir = '/';
            }

            hdr =
                "HTTP/1.0 302 Found\r\n"
                "Location: " + CStringA(redir) + "\r\n";
            return;
        }

        fHandled = true;
    }

    if (!fHandled && m_webroot.IsDirectory()) {
        fHandled = LoadPage(0, body, pClient->m_path);
    }

    UINT resid;
    CStringA res;
    if (!fHandled && m_downloads.Lookup(pClient->m_path, resid)
            && (LoadResource(resid, res, _T("FILE")) || LoadResource(resid, res, _T("PNG")))) {
        if (mime.IsEmpty()) {
            mime = "application/octet-stream";
        }
        memcpy(body.GetBufferSetLength(res.GetLength()), res.GetBuffer(), res.GetLength());
        fHandled = true;
    }

    if (!fHandled) {
        hdr = mime == "text/html"
              ? "HTTP/1.0 301 Moved Permanently\r\n" "Location: /404.html\r\n"
              : "HTTP/1.0 404 Not Found\r\n";
        return;
    }

    if ((mime == "text/html" || mime == "text/javascript") && !fCGI) {
        if (mime == "text/html") {
            hdr +=
                "Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n"
                "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n"
                "Pragma: no-cache\r\n";

            CStringA debug;
            if (AfxGetAppSettings().fWebServerPrintDebugInfo) {
                debug += "<br><hr>\r\n";
                debug += "<div id=\"debug\">";
                CString key, value;
                POSITION pos;
                pos = pClient->m_hdrlines.GetStartPosition();
                while (pos) {
                    pClient->m_hdrlines.GetNextAssoc(pos, key, value);
                    debug += "HEADER[" + key + "] = " + value + "\r\n";
                }
                debug += "cmd: " + pClient->m_cmd + "\r\n";
                debug += "path: " + pClient->m_path + "\r\n";
                debug += "ver: " + pClient->m_ver + "\r\n";
                pos = pClient->m_get.GetStartPosition();
                while (pos) {
                    pClient->m_get.GetNextAssoc(pos, key, value);
                    debug += "GET[" + key + "] = " + value + "\r\n";
                }
                pos = pClient->m_post.GetStartPosition();
                while (pos) {
                    pClient->m_post.GetNextAssoc(pos, key, value);
                    debug += "POST[" + key + "] = " + value + "\r\n";
                }
                pos = pClient->m_cookie.GetStartPosition();
                while (pos) {
                    pClient->m_cookie.GetNextAssoc(pos, key, value);
                    debug += "COOKIE[" + key + "] = " + value + "\r\n";
                }
                pos = pClient->m_request.GetStartPosition();
                while (pos) {
                    pClient->m_request.GetNextAssoc(pos, key, value);
                    debug += "REQUEST[" + key + "] = " + value + "\r\n";
                }
                debug += "</div>";
            }
            body.Replace("[debug]", debug);
        }

        body.Replace("[browserpath]", "/browser.html");
        body.Replace("[commandpath]", "/command.html");
        body.Replace("[controlspath]", "/controls.html");
        body.Replace("[indexpath]", "/index.html");
        body.Replace("[path]", CStringA(pClient->m_path));
        body.Replace("[setposcommand]", CMD_SETPOS);
        body.Replace("[setvolumecommand]", CMD_SETVOLUME);
        body.Replace("[wmcname]", "wm_command");
        // TODO: add more general tags to replace
    }

    // gzip
    if (AfxGetAppSettings().fWebServerUseCompression && hdr.Find("Content-Encoding:") < 0)
        do {
            CString accept_encoding;
            pClient->m_hdrlines.Lookup(_T("accept-encoding"), accept_encoding);
            accept_encoding.MakeLower();
            CAtlList<CString> sl;
            ExplodeMin(accept_encoding, sl, ',');
            if (!sl.Find(_T("gzip"))) {
                break;
            }

            CHAR path[_MAX_PATH], fn[_MAX_PATH];
            if (!GetTempPathA(_MAX_PATH, path) || !GetTempFileNameA(path, "mpc_gz", 0, fn)) {
                break;
            }

            gzFile gf = gzopen(fn, "wb9");
            if (!gf || gzwrite(gf, (LPVOID)(LPCSTR)body, body.GetLength()) != body.GetLength()) {
                if (gf) {
                    gzclose(gf);
                }
                DeleteFileA(fn);
                break;
            }
            gzclose(gf);

            FILE* f = NULL;
            if (fopen_s(&f, fn, "rb")) {
                DeleteFileA(fn);
                break;
            }
            fseek(f, 0, 2);
            CHAR* s = body.GetBufferSetLength(ftell(f));
            fseek(f, 0, 0);
            int len = (int)fread(s, 1, body.GetLength(), f);
            ASSERT(len == body.GetLength());
#ifndef _DEBUG
            UNREFERENCED_PARAMETER(len);
#endif
            fclose(f);
            DeleteFileA(fn);

            hdr += "Content-Encoding: gzip\r\n";
        } while (0);

    CStringA content;
    content.Format(
        "Content-Type: %s\r\n"
        "Content-Length: %d\r\n",
        mime, body.GetLength());
    hdr += content;
}
Esempio n. 3
0
bool CLibraryStream::Load(const WCHAR* fnw)
{
  Clear();

  CStringW url = CStringW(fnw);

  CAtlList<CStringW> sl;
  Explode(url, sl, ':');

  CStringW protocol = sl.RemoveHead();
  if (protocol != L"hsl") return false;

  try
  {
    yami::parameters params;

    params.set_long_long("local_channel", 37830072008705);
    params.set_string("destination", name());
    params.set_string("endpoint", YC.endpoint());

    std::auto_ptr<yami::outgoing_message> message(AGENT.send(DISCOVERY.get("dvb-source"), "dvb-source", "create_streaming_session", params));

    message->wait_for_completion();

    if (message->get_state() == yami::replied)
    {
      int session_id = message->get_reply().get_integer("session");
      params.clear();

      params.set_integer("session", session_id);

      AGENT.send(DISCOVERY.get("dvb-source"), "dvb-source", "start_streaming_session", params);
    }
    else
    {
      return false;
    }
  }
  catch (const home_system::service_not_found&)
  {
    return false;
  }

  if (sl.GetCount() != 2 || FAILED(GUIDFromCString(CString(sl.GetTail()), m_subtype)))
  {
    m_subtype = MEDIASUBTYPE_MPEG2_TRANSPORT;    // TODO: detect subtype
  }

  m_len = 0;
  while(m_len < 1048576)
  {
    yami::parameters params;
    params.set_integer("len", 65535);
    params.set_long_long("pos", m_len);
    std::auto_ptr<yami::outgoing_message> message(AGENT.send(DISCOVERY.get("dvb-source"), "dvb-source", "read", params));
    message->wait_for_completion();
    size_t len = 0;
    PBYTE buf = (PBYTE)message->get_reply().get_binary("payload", len);
    m_len += len;
    for (size_t i = 0; i < len; ++i)
    {
      m_buffer.push_back(buf[i]);
    }

    Sleep(10);
  }

  boost::thread(boost::ref(*this));

  return true;
}
Esempio n. 4
0
void CWebServer::OnRequest(CWebClientSocket* pClient, CStringA& hdr, CStringA& body)
{
    CPath p(AToT(pClient->m_path));
    CStringA ext = p.GetExtension().MakeLower();
    CStringA mime;
    if (ext.IsEmpty()) {
        mime = "text/html";
    } else {
        m_mimes.Lookup(ext, mime);
    }

    hdr = "HTTP/1.0 200 OK\r\n";

    bool fHandled = false, fCGI = false;

    if (!fHandled && m_webroot.IsDirectory()) {
        CStringA tmphdr;
        fHandled = fCGI = CallCGI(pClient, tmphdr, body, mime);

        if (fHandled) {
            tmphdr.Replace("\r\n", "\n");
            CAtlList<CStringA> hdrlines;
            ExplodeMin(tmphdr, hdrlines, '\n');
            POSITION pos = hdrlines.GetHeadPosition();
            while (pos) {
                POSITION cur = pos;
                CAtlList<CStringA> sl;
                CStringA key = Explode(hdrlines.GetNext(pos), sl, ':', 2);
                if (sl.GetCount() < 2) {
                    continue;
                }
                key.Trim().MakeLower();
                if (key == "content-type") {
                    mime = sl.GetTail().Trim();
                    hdrlines.RemoveAt(cur);
                } else if (key == "content-length") {
                    hdrlines.RemoveAt(cur);
                }
            }
            tmphdr = Implode(hdrlines, "\r\n");
            hdr += tmphdr + "\r\n";
        }
    }

    RequestHandler rh = NULL;
    if (!fHandled && m_internalpages.Lookup(pClient->m_path, rh) && (pClient->*rh)(hdr, body, mime)) {
        if (mime.IsEmpty()) {
            mime = "text/html";
        }

        CString redir;
        if (pClient->m_get.Lookup("redir", redir)
                || pClient->m_post.Lookup("redir", redir)) {
            if (redir.IsEmpty()) {
                redir = '/';
            }

            hdr =
                "HTTP/1.0 302 Found\r\n"
                "Location: " + CStringA(redir) + "\r\n";
            return;
        }

        fHandled = true;
    }

    if (!fHandled && m_webroot.IsDirectory()) {
        fHandled = LoadPage(0, body, UTF8To16(pClient->m_path));
    }

    UINT resid;
    if (!fHandled && m_downloads.Lookup(pClient->m_path, resid)
            && (LoadResource(resid, body, _T("FILE")) || LoadResource(resid, body, _T("PNG")))) {
        if (mime.IsEmpty()) {
            mime = "application/octet-stream";
        }
        fHandled = true;
    }

    if (!fHandled) {
        hdr = mime == "text/html"
              ? "HTTP/1.0 301 Moved Permanently\r\n" "Location: /404.html\r\n"
              : "HTTP/1.0 404 Not Found\r\n";
        return;
    }

    if ((mime == "text/html" || mime == "text/javascript") && !fCGI) {
        if (mime == "text/html") {
            hdr +=
                "Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n"
                "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n"
                "Pragma: no-cache\r\n";

            CStringA debug;
            if (AfxGetAppSettings().fWebServerPrintDebugInfo) {
                debug += "<br><hr>\r\n";
                debug += "<div id=\"debug\">";

                CStringA key;
                POSITION pos;

                {
                    CStringA value;

                    pos = pClient->m_hdrlines.GetStartPosition();
                    while (pos) {
                        pClient->m_hdrlines.GetNextAssoc(pos, key, value);
                        debug += "HEADER[" + key + "] = " + value + "\r\n";
                    }
                }
                debug += "cmd: " + pClient->m_cmd + "\r\n";
                debug += "path: " + pClient->m_path + "\r\n";
                debug += "ver: " + pClient->m_ver + "\r\n";

                {
                    CString value;

                    pos = pClient->m_get.GetStartPosition();
                    while (pos) {
                        pClient->m_get.GetNextAssoc(pos, key, value);
                        debug += "GET[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n";
                    }
                    pos = pClient->m_post.GetStartPosition();
                    while (pos) {
                        pClient->m_post.GetNextAssoc(pos, key, value);
                        debug += "POST[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n";
                    }
                    pos = pClient->m_cookie.GetStartPosition();
                    while (pos) {
                        pClient->m_cookie.GetNextAssoc(pos, key, value);
                        debug += "COOKIE[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n";
                    }
                    pos = pClient->m_request.GetStartPosition();
                    while (pos) {
                        pClient->m_request.GetNextAssoc(pos, key, value);
                        debug += "REQUEST[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n";
                    }
                }
                debug += "</div>";
            }
            body.Replace("[debug]", debug);
        }

        body.Replace("[browserpath]", "/browser.html");
        body.Replace("[commandpath]", "/command.html");
        body.Replace("[controlspath]", "/controls.html");
        body.Replace("[indexpath]", "/index.html");
        body.Replace("[path]", pClient->m_path);
        body.Replace("[setposcommand]", CMD_SETPOS);
        body.Replace("[setvolumecommand]", CMD_SETVOLUME);
        body.Replace("[wmcname]", "wm_command");
        // TODO: add more general tags to replace
    }

    // gzip
    if (AfxGetAppSettings().fWebServerUseCompression && !body.IsEmpty()
            && hdr.Find("Content-Encoding:") < 0 && ext != ".png" && ext != ".jpeg" && ext != ".gif")
        do {
            CStringA accept_encoding;
            pClient->m_hdrlines.Lookup("accept-encoding", accept_encoding);
            accept_encoding.MakeLower();
            CAtlList<CStringA> sl;
            ExplodeMin(accept_encoding, sl, ',');
            if (!sl.Find("gzip")) {
                break;
            }

            // Allocate deflate state
            z_stream strm;

            strm.zalloc = Z_NULL;
            strm.zfree = Z_NULL;
            strm.opaque = Z_NULL;
            int ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY);
            if (ret != Z_OK) {
                ASSERT(0);
                break;
            }

            int gzippedBuffLen = body.GetLength();
            BYTE* gzippedBuff = DEBUG_NEW BYTE[gzippedBuffLen];

            // Compress
            strm.avail_in = body.GetLength();
            strm.next_in = (Bytef*)(LPCSTR)body;

            strm.avail_out = gzippedBuffLen;
            strm.next_out = gzippedBuff;

            ret = deflate(&strm, Z_FINISH);
            if (ret != Z_STREAM_END || strm.avail_in != 0) {
                ASSERT(0);
                deflateEnd(&strm);
                delete [] gzippedBuff;
                break;
            }
            gzippedBuffLen -= strm.avail_out;
            memcpy(body.GetBufferSetLength(gzippedBuffLen), gzippedBuff, gzippedBuffLen);

            // Clean up
            deflateEnd(&strm);
            delete [] gzippedBuff;

            hdr += "Content-Encoding: gzip\r\n";
        } while (0);

    CStringA content;
    content.Format(
        "Content-Type: %s\r\n"
        "Content-Length: %d\r\n",
        mime, body.GetLength());
    hdr += content;
}
Esempio n. 5
0
//THIS FUNCTION IS QUITE COMPLICATED BECAUSE 
//IT HAS TO DEAL WITH MAYA NAME MANGLING!
//tokenize the path.
//add each token into the element list which tracks the attributes and indices
//for each entry added make sure there are no parents left out from maya name mangling.
//after the list is populated and missing elements area added 
//we reiterate and produce the final result.
MPlug		FxInternal::DecodePlug(const CStringA& plugStr)
{

	MPlug result;
	MFnDependencyNode depNode(GetSite());

	CAtlList<PathDecodeElement> elementList;

	//tokenize the path
	int iLastPos=0;
	int iThisPos=0;
	CStringA subStr;
	while( iLastPos= iThisPos, 
		subStr=plugStr.Tokenize(".[]", iThisPos), 
		iThisPos != -1 )
	{
		//char lastChar= subStr[iLastPos];
		//char thisChar= subStr[iThisPos];

		//are we looking at a named portion?
		if(iLastPos == 0 
			|| plugStr[iLastPos-1]=='.'
			|| (plugStr[iLastPos-1]==']' && plugStr[iLastPos]=='.'))
		{
			//if the name is length zero then it must be the case when 
			// you do last[#].  The situation is caused by  the sequence "]."
			//if we dont have a name we can skip since only 1d arrays are allowed.

			if(subStr.GetLength() > 0)
			{
		
				//everything we add is going to be based on the current tail.
				//because we are adding parents, as we find parents we can continue
				//to add them to this position so that they will order themselves properly
				POSITION insertPos= elementList.GetTailPosition();

				//calculate the cancel condition.
				//it is the current tail's object if a tail exists otherwise NULL
				//NULL indicates go all the way to the root
				MObject cancelObj= MObject::kNullObj;
				if(elementList.GetCount() > 0)
				{
					cancelObj= elementList.GetTail().Attribute.object();
				}


				//get the object we are currently working with
				MObject thisObj= depNode.attribute(subStr.GetString());
				if(thisObj.isNull())
					return MPlug();//Critical element of the path was not found...return NULL


				//add it to the list so that we have something to insertBefore
				elementList.AddTail();
				elementList.GetTail().Name= subStr;
				elementList.GetTail().Attribute.setObject(thisObj);



				//walk through all of the parents until we reach cancel condition.
				//we can add  the current element onto the list in the same way.
				for( MFnAttribute itrAttr( elementList.GetTail().Attribute.parent() );
					!itrAttr.object().isNull()  && (cancelObj != itrAttr.object());
					itrAttr.setObject(itrAttr.parent()))
				{
					PathDecodeElement element;
					element.Attribute.setObject( itrAttr.object() );

					//we change the position so that the grandparent is inserted before the parent
					insertPos= elementList.InsertBefore( insertPos, element);
				}
			}
		}
		//are we looking at a numbered portion?
		else if(plugStr[iLastPos-1]=='[' && plugStr[iThisPos-1]==']')
		{
			//if so change the array index.
			elementList.GetTail().IsArray= true;
			elementList.GetTail().Index = atoi( subStr.GetString() );
		}
		else
			DXCC_ASSERT(false);//VERY POORLY FORMED STRING

	}

	//produce the result plug off of the elementList.
	bool first= true;
	for(POSITION pos= elementList.GetHeadPosition();
		pos != NULL;
		elementList.GetNext(pos))
	{
		PathDecodeElement& element= elementList.GetAt(pos);

		if(first)
		{//on first one we initialize the result 
			first= false;
			result= MPlug( GetSite(), element.Attribute.object() );
		}
		else
		{
			result= result.child( element.Attribute.object() );
		}

		if(element.IsArray)
		{
			result= result.elementByLogicalIndex(element.Index);
		}


		if(result.isNull())
			return MPlug();//Critical element of the path was not found...return NULL
	}


	return result;
}
   // Define the list
   CAtlList<int> myList;

   // Add elements to the tail
   myList.AddTail(1);
   myList.AddTail(2);
   myList.AddTail(3);

   // Confirm the current head of the list
   ATLASSERT(myList.GetHead() == 1);

   // Confirm the current tail of the list
   ATLASSERT(myList.GetTail() == 3);   
Esempio n. 7
0
void SZYamlDocument::Dump(CString& strText, int nDumpIndent/* = SZYAML_DUMP_INDENT*/)
{
    POSITION pos = m_YamlItemList.GetHeadPosition();
    struct _KeyStackNode 
    {
        _KeyStackNode()
            : nIndent(0)
            , nChildIndent(0)
            , bIsList(FALSE)
        {
        }
        int nIndent;
        int nChildIndent;
        CString strKey;
        BOOL bIsList;
    };
    CAtlList<_KeyStackNode> listKeyStack;
    int nLastIndent = -1;
    BOOL bListItem = FALSE, bPrintThisLine = TRUE;
    CString strLine;

    strText = _T("");

    while (pos)
    {
        _YamlItem &item = m_YamlItemList.GetAt(pos);

        if (listKeyStack.IsEmpty())
            bListItem = FALSE;
        else
            bListItem = listKeyStack.GetTail().bIsList;

        if (item.nIndent == nLastIndent + 1)
        {
            _KeyStackNode &newkey = listKeyStack.GetAt(listKeyStack.AddTail());
            POSITION posNext = _GetNextPos(pos, TRUE);

            newkey.nIndent = item.nIndent;
            newkey.strKey = item.node.Key();
            newkey.bIsList = (posNext != NULL);
        }
        else if (item.nIndent == nLastIndent)
        {
            _KeyStackNode &newkey = listKeyStack.GetTail();
            POSITION posNext = _GetNextPos(pos, TRUE);

            newkey.nIndent = item.nIndent;
            newkey.strKey = item.node.Key();
            newkey.bIsList = (posNext != NULL);
        }
        else if (item.nIndent < nLastIndent)
        {
            for (nLastIndent -= item.nIndent; nLastIndent > 0; -- nLastIndent)
                listKeyStack.RemoveTail();

            if (listKeyStack.IsEmpty())
                bPrintThisLine = TRUE;
            else
            {
                _KeyStackNode &newkey = listKeyStack.GetTail();

                newkey.nIndent = item.nIndent;
                if (newkey.strKey != item.node.Key())
                {
                    newkey.strKey = item.node.Key();
                    POSITION posNext = _GetNextPos(pos, TRUE);
                    newkey.bIsList = (posNext != NULL);
                }
                else
                    bPrintThisLine = !newkey.bIsList;
            }
        }

#ifdef _SZYAML_DEBUG_TRACE
        { // Trace Key Stack
            kconsole::printf(_T("  "));

            for (POSITION pos = listKeyStack.GetHeadPosition(); pos != NULL; listKeyStack.GetNext(pos))
            {
                _KeyStackNode key = listKeyStack.GetAt(pos);
                kconsole::settextcolor(TRUE, TRUE, TRUE, FALSE);
                kconsole::printf(_T("(%d, '%s', %d)"), key.nIndent, key.strKey, key.bIsList);
                kconsole::settextcolor(TRUE, TRUE, TRUE, TRUE);
            }

            kconsole::printf(_T("\r\n"));
        }
#endif

        // 这里对不确定长度的%s不使用Format,是因为MIN_CRT的格式化输出限制长度为1024,见atlstr.h
        // by bbcallen 2009-07-02
        if (bPrintThisLine)
        {
            if (bListItem)
            {
                strLine.Format(
                    _T("%s-%s"),  
                    CString(_T(' '), (item.nIndent - 1) * nDumpIndent),  
                    CString(_T(' '), nDumpIndent - 1)
                    );
                strLine.Append(item.node.Key());
                strLine.Append(_T(": "));
                strLine.Append(item.node.String());
                strLine.Append(_T("\r\n"));
            }
            else
            {
                strLine.Format(
                    _T("%s"),  
                    CString(_T(' '), item.nIndent * nDumpIndent)
                    );

                strLine.Append(item.node.Key());
                strLine.Append(_T(": "));
                strLine.Append(item.node.String());
                strLine.Append(_T("\r\n"));
            }
#ifdef _SZYAML_DEBUG_TRACE
            kconsole::printf(strLine);
#endif
            strText += strLine;
        }
        else
            bPrintThisLine = TRUE;

        nLastIndent = item.nIndent;

        m_YamlItemList.GetNext(pos);
    }
}
Esempio n. 8
0
BOOL SZYamlDocument::Load(LPCTSTR lpszText)
{
    BOOL bResult = FALSE;
    BOOL bNotFinish = TRUE;
    CString strText = lpszText, strLine, strKey, strValue;
    int nThisLinePos = 0, nNextLinePos = 0, nColonPos = 0;
    int nIndent = 0, nLineNum = 1;
    struct _KeyStackNode 
    {
        _KeyStackNode()
            : nIndent(0)
            , nChildIndent(0)
            , bIsList(FALSE)
        {
        }
        int nIndent;
        int nChildIndent;
        CString strKey;
        BOOL bIsList;
    };
    CAtlList<_KeyStackNode> listKeyStack;
    BOOL bNewChild = FALSE, bIsListItem = FALSE;

    m_YamlItemList.RemoveAll();

    if (!lpszText)
        goto Exit0;

    while (bNotFinish)
    {
        nNextLinePos = strText.Find(_T('\n'), nThisLinePos);
        if (-1 == nNextLinePos)
        {
            bNotFinish = FALSE;
            strLine = strText.Mid(nThisLinePos);
        }
        else
            strLine = strText.Mid(nThisLinePos, nNextLinePos - nThisLinePos);

        nIndent = 0;

        // Get indent
        while (_T(' ') == strLine[nIndent])
            nIndent ++;

        nColonPos = strLine.Find(_T(':'));

        strKey = strLine.Left(nColonPos).Trim();
        strValue = strLine.Mid(nColonPos + 1).Trim();

        if (_T('-') == strKey[0])
        {
            int nIndentMore = 1;

            while (_T(' ') == strKey[nIndentMore])
                nIndentMore ++;

            nIndent += nIndentMore;

            strKey = strKey.Mid(nIndentMore);

            bIsListItem = TRUE;
        }
        else
            bIsListItem = FALSE;

        if (bNewChild)
        {
            _KeyStackNode &LastKey = listKeyStack.GetTail();
            LastKey.nChildIndent = nIndent;

            if (bIsListItem)
                LastKey.bIsList = TRUE;

#ifdef _SZYAML_DEBUG_TRACE
            { // Trace Key Stack
                kconsole::printf(_T("  "));

                for (POSITION pos = listKeyStack.GetHeadPosition(); pos != NULL; listKeyStack.GetNext(pos))
                {
                    _KeyStackNode key = listKeyStack.GetAt(pos);
                    kconsole::printf(_T("(%d, '%s', %d)"), key.nChildIndent, key.strKey, key.bIsList);
                }

                kconsole::printf(_T("\r\n"));
            }
#endif
        }

        strLine = strLine.Mid(nIndent);

        if (strLine.IsEmpty())
            continue;

        while (!listKeyStack.IsEmpty())
        {
            _KeyStackNode &LastKey = listKeyStack.GetTail();
            if (LastKey.nChildIndent == nIndent)
                break;

#ifdef _SZYAML_DEBUG_TRACE
            kconsole::printf(_T(" ### (%d, %d)\r\n"), LastKey.nChildIndent, nIndent);
#endif

            if (LastKey.nChildIndent < nIndent)
            {
#ifdef _SZYAML_DEBUG_TRACE
                kconsole::printf(_T(" * ERROR: Line %d, Indent Error\r\n"), nLineNum);
#endif
                goto Exit0;
            }

            listKeyStack.RemoveTail();

#ifdef _SZYAML_DEBUG_TRACE
            { // Trace Key Stack
                kconsole::printf(_T("  "));

                for (POSITION pos = listKeyStack.GetHeadPosition(); pos != NULL; listKeyStack.GetNext(pos))
                {
                    _KeyStackNode key = listKeyStack.GetAt(pos);
                    kconsole::printf(_T("(%d, '%s', %d)"), key.nChildIndent, key.strKey, key.bIsList);
                }

                kconsole::printf(_T("\r\n"));
            }
#endif
        }

        if (bIsListItem && !bNewChild)
        {
            _KeyStackNode &LastKey = listKeyStack.GetTail();
            SZYamlNode newNode;

            newNode.SetKey(LastKey.strKey);
            _AppendNode((int)listKeyStack.GetCount() - 1, newNode);
        }

        if (1 < strValue.GetLength() && strValue[0] == strValue[strValue.GetLength() - 1]
            && (_T('\'') == strValue[0] || _T('\"') == strValue[0]))
            strValue = strValue.Mid(1, strValue.GetLength() - 2);

        if (strValue.IsEmpty())
        {
            _KeyStackNode &NewKey = listKeyStack.GetAt(listKeyStack.AddTail());

            NewKey.nIndent = nIndent;
            NewKey.strKey = strKey;

            bNewChild = TRUE;
        }
        else
            bNewChild = FALSE;

        {
            SZYamlNode newNode;

            newNode.SetKey(strKey);
            newNode.SetValue(strValue);
            _AppendNode((int)listKeyStack.GetCount() - (bNewChild ? 1 : 0), newNode);
        }

        nThisLinePos = nNextLinePos + 1;
        ++ nLineNum;
    }

    SZYamlHandle::_SetPosition(this, m_YamlItemList.GetHeadPosition());

    bResult = TRUE;

Exit0:

    return bResult;
}