示例#1
0
BOOL CConfigAdapter::bGetConfigData(BYTE*& lpData, int& nStreamLength, eSECTION_ID eSectionId)
{
    BOOL bReturn = TRUE;

    switch (eSectionId)
    {
        case MAINFRAME_SECTION_ID:
        {
            UINT unSize = 0;
            BYTE* pbyConfigData = NULL;
            //FIRST CALC SIZE REQUIRED
            unSize += sizeof(BYTE); //Configuration version
            unSize += (sizeof(char) * MAX_PATH);
            unSize += sizeof(STOOLBARINFO);
            //ALLOCATE THE MEMORY
            pbyConfigData = new BYTE[unSize];
            BYTE* pbyTemp = pbyConfigData;
            //UPDATE THE DATA
            BYTE byVersion = 0x1;
            COPY_DATA(pbyTemp, &byVersion, sizeof(BYTE));
            CString* pomMRU_C_FILE_NAME = NULL;
            m_ouConfigDetails.bGetData(MRU_C_FILE_NAME, (void**)(&pomMRU_C_FILE_NAME));
            char acName[MAX_PATH] = {_T('0')};
            ASSERT(pomMRU_C_FILE_NAME != NULL);
            strcpy_s(acName, pomMRU_C_FILE_NAME->GetBuffer(MAX_PATH));
            delete pomMRU_C_FILE_NAME;
            COPY_DATA(pbyTemp, acName, (sizeof(char) * MAX_PATH));
            PSTOOLBARINFO psToolBarInfo = NULL;
            m_ouConfigDetails.bGetData(TOOLBAR_DETAILS, (void**)(&psToolBarInfo));
            ASSERT(psToolBarInfo != NULL);
            COPY_DATA(pbyTemp, psToolBarInfo, sizeof(STOOLBARINFO));
            delete psToolBarInfo;
            lpData = pbyConfigData;
            nStreamLength = unSize;
        }
        break;

        case LOG_SECTION_ID:
        {
            UINT unSize = 0;
            BYTE* pbyConfigData = NULL;
            SLOGCONFIGDETS* psLogConfigDets = NULL;
            m_ouConfigDetails.bGetData(LOG_CONFIG_DETS, (void**)(&psLogConfigDets));
            //FIRST CALCULATE SIZE REQUIRED
            unSize += sizeof(BYTE);//Configuration version

            if (psLogConfigDets != NULL)
            {
                //Filter info size
                SFILTERAPPLIED_CAN* psFilterConfigured = NULL;
                m_ouConfigDetails.bGetData(FILTER_CONFIG_DETS, (void**)(&psFilterConfigured));
                unSize += sizeof (USHORT); // Log file count

                for (UINT i = 0; i < psLogConfigDets->m_unCount; i++)
                {
                    //log info size
                    SLOGINFO sLogInfo;
                    unSize += sLogInfo.unGetSize();
                    CModuleFilterArray* pModuleFilterArray =
                        (&(psLogConfigDets->m_asLogFileDets[i].m_omFilter));
                    unSize += unGetFilterSize(pModuleFilterArray, psFilterConfigured);
                }

                //CALCULATING SIZE ENDS
                //NOW UPDATE THE VALUES
                pbyConfigData = new BYTE[unSize];
                BYTE* pbyTemp = pbyConfigData;
                BYTE byVersion = 0x1;
                COPY_DATA(pbyTemp, &byVersion, sizeof(BYTE));
                memcpy(pbyTemp, &(psLogConfigDets->m_unCount), sizeof (USHORT));
                pbyTemp += sizeof (USHORT);

                for (UINT i = 0; i < psLogConfigDets->m_unCount; i++)
                {
                    //log info
                    SLOGINFO sLogInfo;
                    vPopulateLogInfo(sLogInfo, psLogConfigDets->m_asLogFileDets[i]);
                    pbyTemp = sLogInfo.pbGetConfigData(pbyTemp);
                    //Filter info size
                    CModuleFilterArray* pomFilterArray = &(psLogConfigDets->m_asLogFileDets[i].m_omFilter);
                    pbyTemp = pbyGetFilterConfig(pbyTemp, pomFilterArray, psFilterConfigured);
                }

                //Now update the parameter out pointer
                lpData = pbyConfigData;
                nStreamLength = unSize;
            }
        }
        break;

        case SIMSYS_SECTION_ID:
        {
            PSSIMSYSARRAY psSimSysArray;
            UINT unSize = 0;
            //FIRST CALCULATE THE SIZE REQUIRED MEANWHILE RETRIEVE THE DATA
            unSize += sizeof(BYTE);//Configuration version
            WINDOWPLACEMENT WndPlacement;
            //retrieve the window placement
            m_ouConfigDetails.bGetDefaultValue(SIMSYS_WND_PLACEMENT,WndPlacement);
            unSize += sizeof(WINDOWPLACEMENT);
            m_ouConfigDetails.bGetData(SIMSYS_LIST, (void**)(&psSimSysArray));
            PSSIMSYSARRAY psTemp = psSimSysArray;
            UINT nCount = 0;
            unSize += sizeof(UINT); // To store count

            while (psTemp != NULL)
            {
                nCount++;
                unSize += (sizeof (char) * MAX_PATH);//File Path
                psTemp = psTemp->psNextSimsys;
            }

            unSize += sizeof (WINDOWPLACEMENT);// Window placement for out window
            //CALCULATE THE SIZE MEANWHILE RETRIEVE THE DATA ENDS
            // ALLOCATE THE MEMORY
            BYTE* pbyConfigData = new BYTE[unSize];
            BYTE* pbyTemp = pbyConfigData;
            //UPDATE THE DATA
            BYTE byVersion = 0x1;
            COPY_DATA(pbyTemp, &byVersion, sizeof(BYTE));
            //update window placement
            COPY_DATA(pbyTemp, &WndPlacement, sizeof(WINDOWPLACEMENT));
            //Update Simsys file path
            psTemp = psSimSysArray;
            COPY_DATA(pbyTemp, &nCount, sizeof(UINT));

            while (psTemp != NULL)
            {
                char acFilePath[MAX_PATH] = {_T('\0')};
                strcpy_s(acFilePath, psTemp->m_omStrSimSysPath.GetBuffer(MAX_PATH));
                COPY_DATA(pbyTemp, acFilePath, (sizeof(char) * MAX_PATH));
                psTemp = psTemp->psNextSimsys;
            }

            //update out window placement
            WINDOWPLACEMENT* pWndPlacement = &WndPlacement;
            m_ouConfigDetails.bGetData(OUT_WND_PLACEMENT, (void**)(&pWndPlacement));
            COPY_DATA(pbyTemp, &WndPlacement, sizeof(WINDOWPLACEMENT));
            //UPDATE THE DATA ENDS
            //FINALLY UPDATE THE OUT PARAM
            lpData = pbyConfigData;
            nStreamLength = unSize;
        }
        break;

        case REPLAY_SECTION_ID:
        {
            UINT unSize = 0;
            BYTE* pbyConfigData = NULL;
            SREPLAYDETS* psRepConfigDets = NULL;
            unSize += sizeof(BYTE);//Configuration version
            m_ouConfigDetails.bGetData(REPLAY_CONFIG_DETS, (void**)(&psRepConfigDets));

            if (psRepConfigDets != NULL)
            {
                //FIRST CALCULATE SIZE REQUIRED
                SFILTERAPPLIED_CAN* psFilterConfigured = NULL;
                m_ouConfigDetails.bGetData(FILTER_CONFIG_DETS, (void**)(&psFilterConfigured));
                unSize += sizeof (INT); //

                for (UINT i = 0; i < psRepConfigDets->m_unCount; i++)
                {
                    unSize += unGetReplayFileSize(psRepConfigDets->m_asReplayFile[i]);
                    unSize += unGetFilterSize(&(psRepConfigDets->m_asReplayFile[i].m_omFilter),
                                              psFilterConfigured);
                }

                unSize += sizeof(WINDOWPLACEMENT);
                //CALCULATING SIZE ENDS
                //NOW UPDATE THE VALUES
                pbyConfigData = new BYTE[unSize];
                BYTE* pbyTemp = pbyConfigData;
                BYTE byVersion = 0x1;
                COPY_DATA(pbyTemp, &byVersion, sizeof(BYTE));
                memcpy(pbyTemp, &(psRepConfigDets->m_unCount), sizeof (INT));
                pbyTemp += sizeof (INT);

                for (UINT i = 0; i < psRepConfigDets->m_unCount; i++)
                {
                    pbyTemp = pbGetReplayFileConfig(psRepConfigDets->m_asReplayFile[i], pbyTemp);
                    //Filter info size
                    pbyTemp = pbyGetFilterConfig(pbyTemp, &(psRepConfigDets->m_asReplayFile[i].m_omFilter),
                                                 psFilterConfigured);
                }

                //Update window placement
                WINDOWPLACEMENT WndPlacement;
                WINDOWPLACEMENT* pWndPlacement = &WndPlacement;
                m_ouConfigDetails.bGetData(REPLAY_WND_PLACEMENT, (void**)(&pWndPlacement));
                memcpy(pbyTemp, &WndPlacement, sizeof(WINDOWPLACEMENT));
                pbyTemp += sizeof(WINDOWPLACEMENT);
                //Now update the parameter out pointer
                lpData = pbyConfigData;
                nStreamLength = unSize;
            }
        }
        break;

        case MSGWND_SECTION_ID:
        {
            UINT unSize = 0;
            BYTE* pbyConfigData = NULL;
            //FIRST CALC SIZE
            unSize += sizeof(BYTE);//Configuration version
            PSMESSAGE_ATTRIB psMsgAttrib = NULL;
            m_ouConfigDetails.bGetData(MSG_ATTRIBUTES, (void**)(&psMsgAttrib));
            unSize += sizeof (UINT);// To store count of MsgAttribs

            if (psMsgAttrib != NULL)
            {
                UINT nCount = psMsgAttrib->m_usMsgCount;
                //Count             To store Msg Name         MsgId        Msg Color
                unSize += (nCount * ((sizeof (char) * MAX_PATH) + sizeof(UINT) + sizeof (COLORREF)));
            }

            INT anMsgBuffSize[defDISPLAY_CONFIG_PARAM] = {0};
            m_ouConfigDetails.bGetData(MSG_BUFFER_SIZE, (void**)(&anMsgBuffSize));
            unSize += (sizeof (INT) * defDISPLAY_CONFIG_PARAM);
            CModuleFilterArray ouModuleFilterArray;
            CModuleFilterArray* pouModuleFilterArray = &ouModuleFilterArray;
            m_ouConfigDetails.bGetData(MSG_DISPLAY_FILTER_DETAILS, (void**)(&pouModuleFilterArray));
            SFILTERAPPLIED_CAN* psFilterConfigured = NULL;
            m_ouConfigDetails.bGetData(FILTER_CONFIG_DETS, (void**)(&psFilterConfigured));
            //Filter size
            unSize += unGetFilterSize(&ouModuleFilterArray, psFilterConfigured);
            //MsgFormat window config data
            unSize += sizeof(BYTE);//Msg frmt windows version information
            unSize += sizeof(UINT);//buffer size
            //CALC SIZE ENDS
            //ALLOCATE THE MEMORY
            pbyConfigData = new BYTE[unSize];
            BYTE* pbyTemp = pbyConfigData;
            //UPDATE THE DATA
            BYTE byVersion = 0x1;
            COPY_DATA(pbyTemp, &byVersion, sizeof(BYTE));

            //Attributes
            if (psMsgAttrib != NULL)
            {
                COPY_DATA(pbyTemp, &(psMsgAttrib->m_usMsgCount), sizeof(UINT));

                for (INT i = 0; i < psMsgAttrib->m_usMsgCount; i++)
                {
                    char acName[MAX_PATH] = {_T('\0')};
                    strcpy_s(acName, psMsgAttrib->m_psMsgAttribDetails[i].omStrMsgname);
                    COPY_DATA(pbyTemp, acName, (sizeof(char) * MAX_PATH));
                    COPY_DATA(pbyTemp, &(psMsgAttrib->m_psMsgAttribDetails[i].unMsgID), sizeof(UINT));
                    COPY_DATA(pbyTemp, &(psMsgAttrib->m_psMsgAttribDetails[i].sColor), sizeof(COLORREF));
                }
            }

            m_ouConfigDetails.vRelease(MSG_ATTRIBUTES, (LPVOID*)(&psMsgAttrib));
            //Display buffer size
            COPY_DATA(pbyTemp, anMsgBuffSize, (sizeof (INT) * defDISPLAY_CONFIG_PARAM));
            //Filters
            pbyTemp = pbyGetFilterConfig(pbyTemp, &ouModuleFilterArray, psFilterConfigured);
            //Msg format window default values
            BYTE byVer = 0x0;//version information
            COPY_DATA(pbyTemp, &byVer, sizeof(BYTE));
            UINT unMsgWndCfgSize = 0;
            COPY_DATA(pbyTemp, &unMsgWndCfgSize, sizeof(UINT));
            //Update the out parameters
            lpData = pbyConfigData;
            nStreamLength = unSize;
        }
        break;

        case SIGWATCH_SECTION_ID:
        {
            UINT unSize = 0;
            BYTE* pbyConfigData = NULL;
            PSSIGNALWATCHLIST psSigWatchList = NULL;
            m_ouConfigDetails.bGetData(SIGNAL_WATCH_LIST, (void**)(&psSigWatchList));
            //Find the Size
            unSize += sizeof(BYTE);//Configuration version
            UINT unMsgcount = 0;
            unSize += sizeof (UINT); // To store Msg Count
            PSSIGNALWATCHLIST psTemp = psSigWatchList;

            while (psTemp != NULL)
            {
                unMsgcount++;
                unSize += sizeof (UINT); // To store Msg ID
                unSize += (sizeof (char) * MAX_PATH);// To store Msg Name
                unSize += sizeof (UINT); //To store selected signal count
                INT nSelCount = psTemp->omCSASignals.GetSize();

                for (INT i = 0; i < nSelCount; i++)
                {
                    unSize += sizeof (UINT); // To store Signal ID
                    unSize += (sizeof (char) * MAX_PATH);// To store Signal Name
                }

                psTemp = psTemp->psNextMessageNode;
            }

            unSize += sizeof (WINDOWPLACEMENT); // window placement size
            //ALLOCATE THE MEMORY
            pbyConfigData = new  BYTE[unSize];
            BYTE* pbyTemp = pbyConfigData;
            //UPDATE THE DATA
            BYTE byVersion = 0x1;
            COPY_DATA(pbyTemp, &byVersion, sizeof(BYTE));
            //Find the Size
            COPY_DATA(pbyTemp, &unMsgcount, sizeof (UINT));
            psTemp = psSigWatchList;

            while (psTemp != NULL)
            {
                COPY_DATA(pbyTemp, &(psTemp->unMsgID), sizeof (UINT));
                char acName[MAX_PATH] = {_T('\0')};
                COPY_DATA(pbyTemp, acName, (sizeof (char) * MAX_PATH));
                UINT unSelCount = psTemp->omCSASignals.GetSize();
                COPY_DATA(pbyTemp, &unSelCount, sizeof (UINT));

                for (UINT i = 0; i < unSelCount; i++)
                {
                    CString omSigName = psTemp->omCSASignals.GetAt(i);
                    UINT unSigId = 0;
                    COPY_DATA(pbyTemp, &(unSigId), sizeof (UINT));
                    strcpy_s(acName, omSigName.GetBuffer(MAX_PATH));
                    COPY_DATA(pbyTemp, acName, (sizeof (char) * MAX_PATH));
                }

                psTemp = psTemp->psNextMessageNode;
            }

            //Signal Window placement
            WINDOWPLACEMENT wndPlacement;
            WINDOWPLACEMENT* pWndPlacement = &wndPlacement;
            m_ouConfigDetails.bGetData(SIGWATCH_WND_PLACEMENT, (void**)(&pWndPlacement));
            COPY_DATA(pbyTemp, &wndPlacement, sizeof (WINDOWPLACEMENT));
            //Update the out parameters
            lpData = pbyConfigData;
            nStreamLength = unSize;
        }
        break;

        case DIL_SECTION_ID:
        {
            PSCONTROLLER_DETAILS psContrlDets;
            BYTE* pbyConfigData = NULL;
            UINT unSize = 0;
            unSize += sizeof(BYTE);//Configuration version
            unSize += sizeof(DWORD);
            unSize += sizeof(BYTE);
            unSize += (sizeof(SCONTROLLER_DETAILS) * defNO_OF_CHANNELS);

            if (m_ouConfigDetails.bGetData(CONTROLLER_DETAILS, (void**)(&psContrlDets)))
            {
                pbyConfigData = new BYTE[unSize];
                BYTE* pbyTemp = pbyConfigData;
                BYTE byVersion = 0x1;
                COPY_DATA(pbyTemp, &byVersion, sizeof(BYTE));
                DWORD dwDriverId = DRIVER_CAN_STUB;
                COPY_DATA(pbyTemp, &dwDriverId, sizeof(DWORD));
                BYTE byContlrMode = defMODE_SIMULATE;
                COPY_DATA(pbyTemp, &byContlrMode, sizeof(BYTE));
                COPY_DATA(pbyTemp, psContrlDets, unSize);
                m_ouConfigDetails.vRelease(CONTROLLER_DETAILS, (LPVOID*)(&psContrlDets));
            }

            lpData = pbyConfigData;
            nStreamLength = unSize;
        }
        break;

        case GRAPH_SECTION_ID:
        {
            BYTE byVersion = 0x1;
            BYTE* pbyConfigData = NULL;
            UINT unSize = 0;
            CGraphList* podGraphList;
            m_ouConfigDetails.bGetData(SIGNAL_GRAPH_LIST, (void**)(&podGraphList));
            //FIRST CALCULATE THE SIZE
            unSize += sizeof(BYTE); //Configuration version

            if (podGraphList != NULL)
            {
                unSize += podGraphList->unGetConfigSize(byVersion);
            }

            unSize += sizeof (WINDOWPLACEMENT);
            unSize += sizeof (SGRAPHSPLITTERDATA); //Splitter data
            //ALLOCATE THE MEMORY
            pbyConfigData = new BYTE[unSize];
            BYTE* pbyTemp = pbyConfigData;
            //UPDATE THE DATA
            COPY_DATA(pbyTemp, &byVersion, sizeof(BYTE));

            if (podGraphList != NULL)
            {
                pbyTemp = podGraphList->pbyGetConfigData(pbyTemp, byVersion);
            }

            //UPDATE GRAPH WINDOW PLACEMENT
            WINDOWPLACEMENT wndPalcement;
            WINDOWPLACEMENT* pWndPalcement = &wndPalcement;
            m_ouConfigDetails.bGetData(GRAPH_WND_PLACEMENT, (void**)(&pWndPalcement));
            COPY_DATA(pbyTemp, &wndPalcement, sizeof (WINDOWPLACEMENT));
            SGRAPHSPLITTERDATA sGraphSplitterData;
            PSGRAPHSPLITTERDATA psGraphSplitterData = &sGraphSplitterData;
            m_ouConfigDetails.bGetData(GRAPH_WND_SPLITTER_DATA, (void**)(&psGraphSplitterData));
            COPY_DATA(pbyTemp, &sGraphSplitterData, sizeof (SGRAPHSPLITTERDATA));
            //UPDATE OUT PARAMS
            lpData = pbyConfigData;
            nStreamLength = unSize;
        }
        break;

        case TXWND_SECTION_ID:
        {
            BYTE* pbyCfgData = NULL;
            UINT unSize = 0;
            //FIRST CALCULATE THE SIZE
            unSize += sizeof(BYTE); //Configuration version
            UINT unBlockCount = 0;
            UINT* punBlockCount = &unBlockCount;
            m_ouConfigDetails.bGetData(MSG_BLOCK_COUNT, (void**)(&punBlockCount));
            unSize += sizeof (UINT); //block count
            PSMSGBLOCKLIST psMsgBlockList = NULL;

            if (m_ouConfigDetails.bGetData(SEND_MULTI_MSGS, (void**)(&psMsgBlockList)))
            {
                PSMSGBLOCKLIST psTemp = psMsgBlockList;

                while (psTemp != NULL)
                {
                    unSize += (sizeof(char) * MAX_PATH); // To store the block name
                    unSize += sizeof(UCHAR); // To store the trigger
                    unSize += sizeof(BOOL); // To store active or not
                    unSize += sizeof(UCHAR); // To store the key value
                    unSize += sizeof (UINT); // to store the timeinterval
                    unSize += sizeof (BOOL); // Type
                    unSize += sizeof (BOOL); // Send All msgs
                    unSize += sizeof(UINT);// To store no of msgs in each block
                    unSize += (psTemp->m_unMsgCount) * sizeof (STXCANMSGDETAILS);
                    psTemp = psTemp->m_psNextMsgBlocksList;
                }
            }

            unSize += sizeof(WINDOWPLACEMENT);
            unSize += sizeof(STXMSGSPLITTERDATA);
            //ALLOCATE THE MEMORY
            pbyCfgData = new BYTE[unSize];
            BYTE* pbyTemp = pbyCfgData;
            BYTE byVersion = 0x1;
            COPY_DATA(pbyTemp, &byVersion, sizeof(BYTE));
            COPY_DATA(pbyTemp, &unBlockCount, sizeof(UINT));
            PSMSGBLOCKLIST psTempBlock = psMsgBlockList;

            while (psTempBlock != NULL)
            {
                CString m_omStrBlockName;
                char acName[MAX_PATH] = {_T('\0')};
                strcpy_s(acName, psTempBlock->m_omStrBlockName.GetBuffer(MAX_PATH));
                COPY_DATA(pbyTemp, acName, (sizeof(char) * MAX_PATH));
                COPY_DATA(pbyTemp, &(psTempBlock->m_ucTrigger), sizeof(UCHAR));
                COPY_DATA(pbyTemp, &(psTempBlock->m_bActive), sizeof(BOOL));
                COPY_DATA(pbyTemp, &(psTempBlock->m_ucKeyValue), sizeof(UCHAR));
                COPY_DATA(pbyTemp, &(psTempBlock->m_unTimeInterval), sizeof(UINT));
                COPY_DATA(pbyTemp, &(psTempBlock->m_bType), sizeof(BOOL));
                COPY_DATA(pbyTemp, &(psTempBlock->m_bTxAllFrame), sizeof(BOOL));
                COPY_DATA(pbyTemp, &(psTempBlock->m_unMsgCount), sizeof(UINT));
                PSTXCANMSGLIST psTempCanList = psTempBlock->m_psTxCANMsgList;

                while (psTempCanList != NULL)
                {
                    COPY_DATA(pbyTemp, &(psTempCanList->m_sTxMsgDetails), sizeof (STXCANMSGDETAILS));
                    psTempCanList = psTempCanList->m_psNextMsgDetails;
                }

                psTempBlock = psTempBlock->m_psNextMsgBlocksList;
            }

            m_ouConfigDetails.vRelease(SEND_MULTI_MSGS, (LPVOID*)&psMsgBlockList);
            //Get the Tx window placement
            WINDOWPLACEMENT WndPlacement;
            WINDOWPLACEMENT* pWndPlacement = &WndPlacement;
            m_ouConfigDetails.bGetData(TX_WND_PLACEMENT, (void**)(&pWndPlacement));
            COPY_DATA(pbyTemp, &WndPlacement, sizeof(WINDOWPLACEMENT));
            //Get the Tx splitter position
            STXMSGSPLITTERDATA sTxSpliiterData;
            STXMSGSPLITTERDATA* psTxSpliiterData = &sTxSpliiterData;
            m_ouConfigDetails.bGetData(TX_MSG_WND_SPLITTER_DATA, (void**)(&psTxSpliiterData));
            COPY_DATA(pbyTemp, &sTxSpliiterData, sizeof(STXMSGSPLITTERDATA));
            //Update the OUT PARAMETERS
            lpData = pbyCfgData;
            nStreamLength = unSize;
        }
        break;

        case DATABASE_SECTION_ID:
        {
            BYTE* pbyCfgData = NULL;
            UINT unSize = 0;
            CStringArray* pomStrDBArray = NULL;
            m_ouConfigDetails.bGetData(DATABASE_FILE_NAME, (void**)(&pomStrDBArray));
            //FIRST CALC SIZE
            unSize += sizeof(BYTE); //Configuration version
            unSize += sizeof (UINT); // To store the count

            if (pomStrDBArray != NULL)
            {
                //To store the stringd
                unSize += (pomStrDBArray->GetSize()) * (sizeof(char) * MAX_PATH);
            }

            //ALLOCATE THE MEMORY
            pbyCfgData = new BYTE[unSize];
            BYTE* pbyTemp = pbyCfgData;
            //UPDATE THE DATA
            BYTE byVersion = 0x1;
            COPY_DATA(pbyTemp, &byVersion, sizeof(BYTE));
            UINT unCount = 0;

            if (pomStrDBArray != NULL)
            {
                unCount = pomStrDBArray->GetSize();
            }

            COPY_DATA(pbyTemp, &unCount, sizeof(UINT));

            for (UINT i =0; i < unCount; i++)
            {
                CString omName = pomStrDBArray->GetAt(i);
                char acName[MAX_PATH] = {_T('\0')};
                strcpy_s(acName, omName.GetBuffer(MAX_PATH));
                COPY_DATA(pbyTemp, acName, (sizeof(char) * MAX_PATH));
            }

            m_ouConfigDetails.vRelease(DATABASE_FILE_NAME,(LPVOID*)&pomStrDBArray);
            //UPDATE THE OUT PARAMETER
            lpData = pbyCfgData;
            nStreamLength = unSize;
        }
        break;

        case FILTER_SECTION_ID:
        {
            BYTE* pbyCfgData = NULL;
            UINT unSize = 0;
            SFILTERAPPLIED_CAN* psFilterConfigured = NULL;
            m_ouConfigDetails.bGetData(FILTER_CONFIG_DETS, (void**)(&psFilterConfigured));

            if (psFilterConfigured != NULL)
            {
                unSize += psFilterConfigured->unGetSize();
            }

            pbyCfgData = new BYTE[unSize];
            BYTE* pbyTemp = pbyCfgData;
            pbyTemp = psFilterConfigured->pbGetConfigData(pbyTemp);
            BYTE byVersion = 0x1;
            memcpy(pbyCfgData, &byVersion, sizeof(BYTE));
            lpData = pbyCfgData;
            nStreamLength = unSize;
        }
        break;

        default:
        {
            ASSERT(FALSE);
        }
        break;
    }

    return bReturn;
}
BOOL CBusEventHandlerDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    CStringArray* pomStrArrayHandlerName = NULL;
    CDialog::OnInitDialog();

    if( m_pDoc != NULL )
    {
        CButton* pomButton       = NULL;
        CString omStrHandlerName = STR_EMPTY ;
        CString omStrControl     = STR_EMPTY ;
        INT nCheck               = 0;
        // get the pointer to CStringArray of error handlers prototypes
        pomStrArrayHandlerName = m_pDoc->pomStrGetBusEventHandlerPrototypes();
        if(pomStrArrayHandlerName != NULL )
        {
            // Check for the handlers already added.
            for(INT  i = 0; i<defBUSEV_HANDLER_NUMBER; i++)
            {
                for(INT j =0; j<pomStrArrayHandlerName->GetSize(); j++)
                {
                    pomButton = (CButton*)GetDlgItem(IDC_CHKB_BUSEV_CONNECT_HANDLER+i);
                    if(pomButton != NULL )
                    {
                        omStrHandlerName = pomStrArrayHandlerName->GetAt(j);
                        pomButton->GetWindowText(omStrControl);
                        omStrControl.Replace(' ','_');
                        omStrControl.Replace('-','_');
                        // The find the control text in added handlers text
                        if( omStrHandlerName.Find(omStrControl) != -1 )
                        {
                            // If the dialog box is invoked for delete, check
                            // the box of already added handlers else check and
                            // disable
                            if(m_bIsDelete == TRUE )
                            {
                                pomButton->SetCheck(TRUE);
                            }
                            else
                            {
                                pomButton->SetCheck(TRUE);
                                pomButton->EnableWindow(FALSE);
                            }
                        }
                    }
                }
            }
        }
        // Disable all other check box corresponding to which the handlers
        // are not added and dialog box in invoked to delete the handlers
        if(m_bIsDelete == TRUE )
        {
            for(INT i = 0; i<defBUSEV_HANDLER_NUMBER; i++)
            {
                pomButton = (CButton*)GetDlgItem(IDC_CHKB_BUSEV_CONNECT_HANDLER+i);
                if(pomButton != NULL )
                {
                    nCheck = pomButton->GetCheck();
                    if(nCheck == 0 )
                    {
                        pomButton->EnableWindow(FALSE);
                    }
                }
            }
            // Set the dialog caption text to indicate user is deleting
            // the handlers
            SetWindowText(defBUSEV_HANDLER_TEXT_DEL);
        }
        else
        {
            // Set the dialog caption text to indicate user is adding
            // the handlers
            SetWindowText(defBUSEV_HANDLER_TEXT_ADD);
        }
    }
    return TRUE;  // return TRUE unless you set the focus to a control
    // EXCEPTION: OCX Property Pages should return FALSE
}
示例#3
0
bool KSFLoader::LoadGlobalData( const CString &sPath, Song &out )
{
    MsdFile msd;
    if( !msd.ReadFile( sPath ) )
        RageException::Throw( "Error opening file \"%s\": %s", sPath.c_str(), msd.GetError().c_str() );

    float BPMPos2 = -1, BPM2 = -1, BPMPos3 = -1, BPM3 = -1;;

    for( unsigned i=0; i < msd.GetNumValues(); i++ )
    {
        const MsdFile::value_t &sParams = msd.GetValue(i);
        CString sValueName = sParams[0];

        // handle the data
        if( 0==stricmp(sValueName,"TITLE") )
            LoadTags(sParams[1], out);
        else if( 0==stricmp(sValueName,"BPM") )
            out.AddBPMSegment( BPMSegment(0, strtof(sParams[1], NULL)) );
        else if( 0==stricmp(sValueName,"BPM2") )
            BPM2 = strtof( sParams[1], NULL );
        else if( 0==stricmp(sValueName,"BPM3") )
            BPM3 = strtof( sParams[1], NULL );
        else if( 0==stricmp(sValueName,"BUNKI") )
            BPMPos2 = strtof( sParams[1], NULL ) / 100.0f;
        else if( 0==stricmp(sValueName,"BUNKI2") )
            BPMPos3 = strtof( sParams[1], NULL ) / 100.0f;
        else if( 0==stricmp(sValueName,"STARTTIME") )
            out.m_Timing.m_fBeat0OffsetInSeconds = -strtof( sParams[1], NULL )/100;
        else if( 0==stricmp(sValueName,"TICKCOUNT") ||
                 0==stricmp(sValueName,"STEP") ||
                 0==stricmp(sValueName,"DIFFICULTY"))
            ; /* Handled in LoadFromKSFFile; don't warn. */
        else
            LOG->Trace( "Unexpected value named '%s'", sValueName.c_str() );
    }

    /* This doesn't work yet: we also need to move the data around, I think, and
     * we should handle more than one BPM change. */
    if( BPM2 > 0 && BPMPos2 > 0 )
    {
        const float BeatsPerSecond = out.GetBPMAtBeat(0) / 60.0f;
        const float beat = BPMPos2 * BeatsPerSecond;
        LOG->Trace("BPM %f, BPS %f, BPMPos2 %f, beat %f",
                   out.GetBPMAtBeat(0), BeatsPerSecond, BPMPos2, beat);
        out.AddBPMSegment( BPMSegment(beat, BPM2) );
    }

    if( BPM3 > 0 && BPMPos3 > 0 )
    {
        const float BeatsPerSecond = out.GetBPMAtBeat(0) / 60.0f;
        const float beat = BPMPos3 * BeatsPerSecond;
        LOG->Trace("BPM %f, BPS %f, BPMPos3 %f, beat %f",
                   out.GetBPMAtBeat(0), BeatsPerSecond, BPMPos3, beat);
        out.AddBPMSegment( BPMSegment(beat, BPM3) );
    }

    /* Try to fill in missing bits of information from the pathname. */
    {
        CStringArray asBits;
        split( sPath, "/", asBits, true);

        ASSERT(asBits.size() > 1);
        LoadTags(asBits[asBits.size()-2], out);
    }

    // search for music with song in the file name
    CStringArray arrayPossibleMusic;
    GetDirListing( out.GetSongDir() + CString("song.mp3"), arrayPossibleMusic );
    GetDirListing( out.GetSongDir() + CString("song.ogg"), arrayPossibleMusic );
    GetDirListing( out.GetSongDir() + CString("song.wav"), arrayPossibleMusic );

    if( !arrayPossibleMusic.empty() )		// we found a match
        out.m_sMusicFile = arrayPossibleMusic[0];

    return true;
}
示例#4
0
void ObjectBarDialog::Refresh(bool layer_changed)
{
	// check for unnecessary refresh
	if (layer_changed && !show_only_selected_layer)
		return;

	// clear all lists
	objects.DeleteAllItems();

	for (int i = 0; i < large_images.GetImageCount(); i++)
		large_images.Remove(0);

	for (int i = 0; i < small_images.GetImageCount(); i++)
		small_images.Remove(0);

	if(folderfilter > -1 && folderfilter >= application->object_folders.size())
		folderfilter = -1;

	CObj*			pObject;
	CObjType*		pObjectType;
	CStringArray	List; // Object list

	//object folders
	if (folderfilter == -1)
	{
		HBITMAP large_image = (HBITMAP) LoadImage(GetModuleHandle(0), MAKEINTRESOURCE(20150), IMAGE_BITMAP, 32, 32, LR_LOADTRANSPARENT);
		HBITMAP small_image = (HBITMAP) LoadImage(GetModuleHandle(0), MAKEINTRESOURCE(20150), IMAGE_BITMAP, 16, 16, LR_LOADTRANSPARENT);
		
		int ImageID = ImageList_Add(large_images.m_hImageList, large_image, NULL);
		ImageList_Add(small_images.m_hImageList, small_image, NULL);
		
		DeleteObject(large_image);
		DeleteObject(small_image);

		for (int i=0; i<application->object_folders.size(); ++i)
		{
			if(application->object_folders[i].name == "Default")
				continue;
			int item = objects.InsertItem(objects.GetItemCount(), application->object_folders[i].name, ImageID);
			objects.SetItemData(item, (DWORD_PTR)(const char*)"-1");
		}
	} // -1 is Default, -2 is disabled
	else if(folderfilter != -2 && application->object_folders[folderfilter].name != "Default")
	{
		HBITMAP large_image = (HBITMAP) LoadImage(GetModuleHandle(0), MAKEINTRESOURCE(20150), IMAGE_BITMAP, 32, 32, LR_LOADTRANSPARENT);
		HBITMAP small_image = (HBITMAP) LoadImage(GetModuleHandle(0), MAKEINTRESOURCE(20150), IMAGE_BITMAP, 16, 16, LR_LOADTRANSPARENT);
		
		int ImageID = ImageList_Add(large_images.m_hImageList, large_image, NULL);
		ImageList_Add(small_images.m_hImageList, small_image, NULL);
		
		DeleteObject(large_image);
		DeleteObject(small_image);

		int item = objects.InsertItem(0,"...\\"+application->object_folders[folderfilter].name, ImageID);
		objects.SetItemData(item, (DWORD_PTR)(const char*)"-1");
	}

	if (layout)
	{
		POSITION LayerPos = layout->layers.GetHeadPosition();

		// For each layer
		while(LayerPos)
		{
			CLayer* pLayer = layout->layers.GetNext(LayerPos);

			if (show_only_selected_layer && pLayer != layout->current_layer)
				continue;

			if (!show_nonlayout_objects && pLayer->m_layerType == LAYER_NONFRAME)
				continue;

			// Loop all objects
			CObjList Objects;
			pLayer->GetEveryObject(Objects, layout);

			POSITION ObjectPos = Objects.GetHeadPosition();

			for (int i = 0; i < Objects.GetCount(); i++) 
			{
				long ID = Objects.GetNext(ObjectPos);
				layout->objects.Lookup(ID, pObject);

				if (pObject->GetGlobalID() != -1) 
				{
					pObjectType = pObject->GetObjectType(application);
					
					// Failed/invalid object type, for some reason
					if(!pObjectType)
						continue;

					//folder filtering
					if(folderfilter ==-1 && pObjectType->GetFolder() != "Default")
						continue;
					else if(folderfilter > -1 && pObjectType->GetFolder()!=application->object_folders[folderfilter].name)
						continue;

					bool bAdd = true;

					for (int j = 0; j < List.GetSize(); j++)
						if (List.GetAt(j) == pObjectType->GetName())
							bAdd = false;

					if (bAdd)
					{
						HBITMAP large_image = pObjectType->m_Image.MakeBitmap();
						HBITMAP small_image = pObjectType->small_image.MakeBitmap();

						int ImageID = ImageList_Add(large_images.m_hImageList, large_image, NULL);
						ImageList_Add(small_images.m_hImageList, small_image, NULL);

						DeleteObject(large_image);
						DeleteObject(small_image);

						int Item = objects.InsertItem(objects.GetItemCount(), pObjectType->GetName(), ImageID);

						objects.SetItemData(Item, (LPARAM)((const char*)pObjectType->GetName()));

						List.Add(pObjectType->GetName());
					}
				} // Iterate each object
			} // Iterate each layer
		}
	}

	else
	{
		POSITION Pos = application->object_types.GetStartPosition();
		CObjType* oT;
		long nKey = 0;

		while (Pos != NULL) 
		{	
			application->object_types.GetNextAssoc(Pos, nKey, oT);
			if(oT && !oT->m_bIsGroupType)
			{
				int ImageID = ImageList_Add(large_images.m_hImageList, oT->m_Image.MakeBitmap(), NULL);
				int Item = objects.InsertItem(objects.GetItemCount(), oT->GetName(), ImageID);

				objects.SetItemData(Item, (DWORD)((LPCSTR)oT->GetName()));

				List.Add(oT->GetName());
			}
		}
	}

	objects.ShowScrollBar(SB_VERT); 

	// Work out if there's a vertical scrollbar. If there is, we'll resize a bit.
	int iListCount = objects.GetItemCount();
	int iListSize = objects.GetCountPerPage();

	if(iListCount < iListSize)
	{
		// Disable the arrows on the vertical scrollbar
		objects.EnableScrollBar(SB_VERT, ESB_DISABLE_BOTH);
		objects.SetScrollRange(SB_VERT, 0, 2);
	}

	else
	{
		// Enable the vertical scrollbar
		objects.EnableScrollBar(SB_VERT, ESB_ENABLE_BOTH);
	}

	if (sorting == ob_sort_az)
		objects.SortItems(ObjectCompare, (LPARAM)&objects);
	if (sorting == ob_sort_za)
		objects.SortItems(ObjectCompareZA, (LPARAM)&objects);

	// now replace the ids
	for (int i = 0; i < objects.GetItemCount(); i++)
	{
		if((const char*)objects.GetItemData(i) == "-1")
		{
			objects.SetItemData(i, -1);
			continue;
		}
		CObjType* type = GetTypeFromName(application, objects.GetItemText(i, 0));
		objects.SetItemData(i, type->ObjectIdentifier);
	}
}
示例#5
0
文件: DLsyn.cpp 项目: DLive/npadBook
bool CDLsyn::upFileToSer(CStringArray &data)
{

	//CStringA abc="[{\"term_id\":\"1\",\"name\":\"\\u672a\\u5206\\u7c7b\"},{\"term_id\":\"4\",\"name\":\"\u7f51\u7edc\u5b89\u5168\"}]";
	//CStringA b;
	//b.Format("%s",abc);
	//char *retdata=abc.GetBuffer();//unicodeToUtf8(m_strHtml.GetBuffer());
	//getClass();
	//return true;
	CDLupToDistancedlg updlg;
	if(updlg.DoModal()!=IDOK){
		return false;
	}
	CStringA status=updlg.m_status;
	//((CComboBox*)updlg.GetDlgItem(IDC_STATUS))->GetCurSel()==0?"draft":"public";
	CConndb db;
	
	CString sqltmp=_T("SELECT a.title,a.distanceID,a.distanceClass,a.id,a.classid,a.addtime,a.txtaddress,c.classname,a.author,a.difficulty,a.artitletype,a.uniquetag,a.content FROM articles AS a,class AS c where a.classid=c.id and a.id=%s");
	CStringA titles,id,addtime,content,locaddress,classname,author,diffiNum,filetype,rid,rclass,classid,uniquetag;
	CString sqlcmd;
	//CString upDatatmp=_T("title=%s&distanceID=%s&distanceClass=%s&id=%s&classid=%s&addtime=%s&artitletype=%s&uniquetag=%s&content=%s");
	
	CString upData;
	for(int j=0;j<data.GetCount();j++){
		sqlcmd.Format(sqltmp,data.GetAt(j));
		db.search(sqlcmd);
		_variant_t var;
		try
		{
			if(db.m_query->eof())
			{
				AfxMessageBox(_T("没有相关文章,请重新搜索"));
				return false;
			}
			int i=0;
			Json::Value root;

			while(!db.m_query->eof())
			{
				var=db.m_query->getStringField(_T("title"));
				if(var.vt!=VT_NULL)
					titles=(LPCSTR)_bstr_t(var);
				var=db.m_query->getIntField(_T("id"));
				if(var.vt!=VT_NULL)
					id=(LPCSTR)_bstr_t(var);
				var=db.m_query->getStringField(_T("addtime"));
				if(var.vt!=VT_NULL)
					addtime=(LPCSTR)_bstr_t(var);
				var=db.m_query->getStringField(_T("txtaddress"));
				if(var.vt!=VT_NULL)
					locaddress=(LPCSTR)_bstr_t(var);
				var=db.m_query->getStringField(_T("classname"));
				if(var.vt!=VT_NULL)
					classname=(LPCSTR)_bstr_t(var);
				var=db.m_query->getStringField(_T("distanceID"));
				if(var.vt!=VT_NULL)
					rid=(LPCSTR)_bstr_t(var);
				var=db.m_query->getStringField(_T("uniquetag"));
				if(var.vt!=VT_NULL)
					uniquetag=(LPCSTR)_bstr_t(var);
				var=db.m_query->getStringField(_T("distanceClass"));
				if(var.vt!=VT_NULL)
					rclass=(LPCSTR)_bstr_t(var);
				var=db.m_query->getStringField(_T("content"));
				if(var.vt!=VT_NULL)
					content=(LPCSTR)_bstr_t(var);
				var=db.m_query->getStringField(_T("author"));
				if(var.vt!=VT_NULL)
					author=(LPCSTR)_bstr_t(var);
				else
					author=_T("");
				var=db.m_query->getIntField(_T("difficulty"));
				if(var.vt!=VT_NULL)
					diffiNum=(LPCSTR)_bstr_t(var);
				else
					diffiNum=_T("");
				var=db.m_query->getStringField(_T("artitletype"));
				if(var.vt!=VT_NULL)
					filetype=(LPCSTR)_bstr_t(var);
				else
					filetype=_T("tit");
				
				Json::Value sartitle;
				//CString upDatatmp=_T("title=%s&distanceID=%s&distanceClass=%s&id=%s&classid=%s&addtime=%s&artitletype=%s&uniquetag=%s&content=%s");
				sartitle["title"] = titles.GetBuffer();
				sartitle["distanceID"] = rid.GetBuffer();
				sartitle["distanceClass"] = rclass.GetBuffer();
				sartitle["id"] = id.GetBuffer();
				sartitle["classid"] = classid.GetBuffer();
				sartitle["addtime"] = addtime.GetBuffer();
				sartitle["artitletype"] = filetype.GetBuffer();
				sartitle["uniquetag"] = uniquetag.GetBuffer();
				sartitle["content"] = content.GetBuffer();
				sartitle["status"]=status.GetBuffer();
				root.append(sartitle);

				db.m_query->nextRow();
			}
			//upData.Format(upDatatmp,titles,rid,rclass,id,classid,addtime,filetype,uniquetag,content);
			Json::FastWriter writer;
			//CStringA sdata="adata=";
			CStringA sdata=writer.write(root).c_str();
			sendData(sdata);
		}
		catch(_com_error *e)
		{
			AfxMessageBox(e->ErrorMessage());
			return false;
		}
	}
	return true;
}
BOOL CSelectFunctions::bFormatFunctionPrototype(CString &omStrFunctionPrototype)
{
    BOOL bReturn = TRUE;
    CStringArray omStrArrayParaType;
    CString omStrReturnType = "";
    CString omStrFuncName   = "";
    if(m_omStrSelectedText.IsEmpty() == 0 )
    {
        CString omStrTemp =    m_omStrSelectedText;
        omStrTemp = omStrTemp.Right(omStrTemp.GetLength() - 
                                    omStrTemp.Find(" ") - 1 );
        omStrTemp.TrimLeft();
        omStrTemp.TrimRight();
        omStrReturnType = m_omStrSelectedText;
        omStrReturnType.Replace(omStrTemp, "");
        INT nIndex = 0;
        nIndex = omStrTemp.Find("(");
        omStrFuncName = omStrTemp.Left(nIndex);
        omStrTemp = omStrTemp.Right(omStrTemp.GetLength() - nIndex - 1);
        omStrTemp = omStrTemp.Left( omStrTemp.Find(")"));
        while(omStrTemp.IsEmpty() == 0)
        {
            nIndex = omStrTemp.Find(",");
            if(nIndex != -1)
            {
                omStrArrayParaType.Add(omStrTemp.Left(nIndex));
            }
            else
            {
                omStrArrayParaType.Add(omStrTemp);
                omStrTemp = "";
            }
            omStrTemp = omStrTemp.Right(omStrTemp.GetLength() - nIndex - 1 );
        }
        omStrReturnType.TrimLeft();
        omStrReturnType.TrimRight();
        omStrFuncName.TrimLeft();
        omStrFuncName.TrimRight();
        if(omStrReturnType.CompareNoCase(_T("void")) !=0)
        {
            omStrFunctionPrototype  = defTODO_FUNCTION_INSERT;
            omStrFunctionPrototype += defNEW_LINE;
            omStrFunctionPrototype += _T("/* ");
            omStrFunctionPrototype += omStrReturnType;
            omStrFunctionPrototype += _T(" ");
            omStrFunctionPrototype += defRETURN_TYPE_NAME;
            omStrFunctionPrototype += _T(" ;*/");
        }
        UINT unCount = (COMMANUINT)omStrArrayParaType.GetSize();
        omStrFuncName += _T("(");
        for(UINT i = 0; i<unCount ;i++)
        {
            omStrTemp = omStrArrayParaType.GetAt(i);
            omStrTemp.TrimLeft();
            omStrTemp.TrimRight();
            omStrFunctionPrototype += defNEW_LINE;
            omStrFunctionPrototype += "/* ";
            omStrFunctionPrototype += omStrTemp;

            omStrTemp               = "";
            omStrTemp.Format(defPARAMETER_NAME,i+1);
            omStrFunctionPrototype += " ";
            omStrFunctionPrototype +=omStrTemp; 
            omStrFunctionPrototype += " ;*/";

            omStrFuncName +=omStrTemp;
            if(i != unCount - 1 )
            {
                omStrFuncName += _T(",");
            }
        }
        omStrFuncName += _T(")");
        if(omStrReturnType.CompareNoCase(_T("void")) !=0)
        {

            omStrFunctionPrototype += defNEW_LINE;
            omStrFunctionPrototype += defRETURN_TYPE_NAME;
            omStrFunctionPrototype += _T(" = ");
        }
        omStrFunctionPrototype += omStrFuncName;
        omStrFunctionPrototype += _T(";");
        omStrFunctionPrototype += defNEW_LINE;
    }

    return bReturn;

}
示例#7
0
文件: Main_Set.cpp 项目: toschkin/KPL
BOOL CMain_Set::SaveToFile(CString strFile)
{	
	CString strBuf,str;
	str.Format("//VER_%d\r\n",m_nVersion);
	strBuf+=str;		
	str.Format("NUM_DIRECT=%d\r\n",m_ProcessInfoArray.GetSize());
	strBuf+=str;
	str.Format("REAL_SIZE_DIRECT_BUFER=%d\r\n",REAL_SIZE_DIRECT_BUFER);
	strBuf+=str;
	str.Format("REAL_NUM_GENFAST_OBJECT=%d\r\n",REAL_NUM_GENFAST_OBJECT);
	strBuf+=str;
	str.Format("AMOUNT_OBJECT=%d\r\n",AMOUNT_OBJECT);
	strBuf+=str;	
	str.Format("AMOUNT_INIOBJECT=%d\r\n",m_IniObjectArray.GetSize());
	strBuf+=str;
	str.Format("AMOUNT_INI_MASKA=%d\r\n",m_IniMaskArray.GetSize());
	strBuf+=str;

	if(m_nVersion > 19)
	{
		CStringArray dest;
		Str2Array(MY_IP, &dest, '.');
		if(dest.GetSize()==4)
		{
			union 
			{
				UINT uIP;
				BYTE byIP[4];
			}IP;
			IP.byIP[0] = (BYTE)atoi(dest[3]);
			IP.byIP[1] = (BYTE)atoi(dest[2]);
			IP.byIP[2] = (BYTE)atoi(dest[1]);
			IP.byIP[3] = (BYTE)atoi(dest[0]);		
			str.Format("MY_IP=%u\r\n",IP.uIP);
		}
		else
			str.Format("MY_IP=%i\r\n",0);
		strBuf+=str;

		Str2Array(MY_IP_MASK, &dest, '.');
		if(dest.GetSize()==4)
		{
			union 
			{
				UINT uIP;
				BYTE byIP[4];
			}IP;
			IP.byIP[0] = (BYTE)atoi(dest[3]);
			IP.byIP[1] = (BYTE)atoi(dest[2]);
			IP.byIP[2] = (BYTE)atoi(dest[1]);
			IP.byIP[3] = (BYTE)atoi(dest[0]);		
			str.Format("MY_IP_MASK=%u\r\n",IP.uIP);
		}
		else
			str.Format("MY_IP_MASK=%i\r\n",0);
		strBuf+=str;

		Str2Array(MY_IP_GW, &dest, '.');
		if(dest.GetSize()==4)
		{
			union 
			{
				UINT uIP;
				BYTE byIP[4];
			}IP;
			IP.byIP[0] = (BYTE)atoi(dest[3]);
			IP.byIP[1] = (BYTE)atoi(dest[2]);
			IP.byIP[2] = (BYTE)atoi(dest[1]);
			IP.byIP[3] = (BYTE)atoi(dest[0]);		
			str.Format("MY_IP_GW=%u\r\n",IP.uIP);
		}
		else
			str.Format("MY_IP_GW=%i\r\n",0);
		strBuf+=str;
	}

	str.Format("//KPL_%s\r\n",KPLType);
	strBuf+=str;		
	str.Format("//_%s\r\n\r\n",m_strPSNAME);
	strBuf+=str;	
	
	
	for(int i =0; i < m_ProcessInfoArray.GetSize(); i++)
	{
		str.Format("MAKE_DIRECT=%d\r\n",i+1);
		strBuf+=str;
		str.Format("TYPE_PROTOKOL=%d\r\n",m_ProcessInfoArray[i].TYPE_PROTOKOL);
		strBuf+=str;
		str.Format("START_ADDRESS_MAP=%d\r\n",m_ProcessInfoArray[i].START_ADDRESS_MAP);
		strBuf+=str;
		str.Format("AMOUNT_SIGNIFICATE=%d\r\n",m_ProcessInfoArray[i].AMOUNT_SIGNIFICATE);
		strBuf+=str;
		str.Format("YESNOLOGALARM=%d\r\n",m_ProcessInfoArray[i].YESNOLOGALARM);
		strBuf+=str;
		str.Format("YESNOLOGPROTOKOL=%d\r\n",m_ProcessInfoArray[i].YESNOLOGPROTOKOL);
		strBuf+=str;	
		str.Format("//%s\r\n\r\n",m_ProcessInfoArray[i].strCOMMENT);
		strBuf+=str;			
	}
	for(int i =0; i < m_IniObjectArray.GetSize(); i++)
	{
		str.Format("NUMBER_INIOBJECT=%d\r\n",i+1);
		strBuf+=str;
		str.Format("TYPE_OBJECT=%d\r\n",m_IniObjectArray[i].TYPE_OBJECT);
		strBuf+=str;
		str.Format("GENTYPE_OBJECT=%d\r\n",m_IniObjectArray[i].GENTYPE_OBJECT);
		strBuf+=str;
		str.Format("START_ADRES_PMZ=%d\r\n",m_IniObjectArray[i].START_ADRES_PMZ);
		strBuf+=str;
		str.Format("NUMBER_OBJECT=%d\r\n",m_IniObjectArray[i].NUMBER_OBJECT);
		strBuf+=str;
		str.Format("NUM_DATE=%d\r\n",m_IniObjectArray[i].NUM_DATE);
		strBuf+=str;
		str.Format("REAL_ADRES=%d\r\n",m_IniObjectArray[i].REAL_ADRES);
		strBuf+=str;
		str.Format("GEN_NUMBYTE=%d\r\n",m_IniObjectArray[i].GEN_NUMBYTE);
		strBuf+=str;
		str.Format("ADRES_ASDU=%d\r\n",m_IniObjectArray[i].ADRES_ASDU);
		strBuf+=str;
		str.Format("YES_NO_FASTBUF=%d\r\n",m_IniObjectArray[i].YES_NO_FASTBUF);
		strBuf+=str;
		str.Format("SIZE_FAST_BUF=%d\r\n",m_IniObjectArray[i].SIZE_FAST_BUF);
		strBuf+=str;
		str.Format("NUMBER_DIRECT=%d\r\n\r\n",m_IniObjectArray[i].NUMBER_DIRECT);
		strBuf+=str;
		if(m_nVersion > 10)
		{
			strBuf.TrimRight("\r\n");
			strBuf+="\r\n";
			str.Format("//IO_%s\r\n\r\n",m_IniObjectArray[i].strCOMMENT);
			strBuf+=str;		
		}
	}
	for(int i =0; i < m_IniMaskArray.GetSize(); i++)
	{
		str.Format("NUMBER_MASKA=%d\r\n",i+1);
		strBuf+=str;
		str.Format("ADRES_MASKA=%d\r\n",m_IniMaskArray[i].ADR_MASKA);
		strBuf+=str;
		str.Format("MASKAINT=%d\r\n",m_IniMaskArray[i].MASKAINT);
		strBuf+=str;
		str.Format("MASKAFLOAT=%d\r\n",m_IniMaskArray[i].MASKAFLOAT);
		strBuf+=str;
		str.Format("VALUE_0=%d\r\n",m_IniMaskArray[i].VALUE_0);
		strBuf+=str;
		str.Format("TYPE_VALUE=%d\r\n",m_IniMaskArray[i].TYPE_VALUE);
		strBuf+=str;
		str.Format("MASKA_VALUE_0=%d\r\n",m_IniMaskArray[i].MASKA_VALUE_0);
		strBuf+=str;				
		str.Format("//MSK_%s\r\n\r\n",m_IniMaskArray[i].strCOMMENT);
		strBuf+=str;
	}
	CFile f;
	try
	{		
		if(!f.Open(strFile,CFile::modeCreate|CFile::modeWrite))
			return FALSE;

		f.Write((void*)strBuf.GetBuffer(),strBuf.GetLength());
		f.Close();		
	}
	catch(...)
	{
		return FALSE;
	}
	return TRUE;
}
示例#8
0
bool NotesLoader::Loadable( CString sPath )
{
	CStringArray list;
	GetApplicableFiles( sPath, list );
	return !list.empty();
}
示例#9
0
// Get the list of database files associated
void CLogObjectCAN::Der_GetDatabaseFiles(CStringArray& omList)
{	
	omList.Append(m_omListDBFiles);
}
示例#10
0
文件: Plot.cpp 项目: adakite/main
//----------------------------------------
void CPlot::GetAxisX(CInternalFiles* yfx,
                     ExpressionValueDimensions* dimVal,
                     CExpressionValue* varX,
                     string* varXName)
{


  if (!m_forcedVarXName.empty())
  {
    if (varXName != NULL)
    {
      *varXName = m_forcedVarXName.c_str();
    }

    GetForcedAxisX(yfx, dimVal, varX);
    return;
  }


  CStringArray axisNames;
  CStringArray::iterator is;
  //ExpressionValueDimensions dimVal;

  yfx->GetAxisVars(axisNames);

  if (axisNames.size() != 1)
  {
    string msg = CTools::Format("CPlot::GetAxisX -  wrong number of axis in file '%s' : %ld"
                                "Correct number is 1",
                                yfx->GetName().c_str(),
                                (long)axisNames.size());
    CException e(msg, BRATHL_INCONSISTENCY_ERROR);
    CTrace::Tracer("%s", e.what());
    throw (e);
  }

  for (is = axisNames.begin(); is != axisNames.end(); is++)
  {
    // Get dim
    if (dimVal != NULL)
    {
      yfx->GetVarDims(*is, *dimVal);
      if ( (dimVal->size() <= 0) || (dimVal->size() > 2) )
      {
        string msg = CTools::Format("CPlot::GetAxisX - '%s' axis -> number of dimensions must be 1 or 2 - Found : %ld",
                                     (*is).c_str(), (long)dimVal->size());
        CException e(msg, BRATHL_INCONSISTENCY_ERROR);
        CTrace::Tracer("%s", e.what());
        throw (e);
      }
    }

    // Get values
    if (varX != NULL)
    {
      /*
      string wantedUnit;

      NetCDFVarKind varKind = yfx->GetVarKind(*is);
      if (varKind == Longitude)
      {
        wantedUnit = CLatLonPoint::m_DEFAULT_UNIT_LONGITUDE;
      }
      else if (varKind == Latitude)
      {
        wantedUnit = CLatLonPoint::m_DEFAULT_UNIT_LATITUDE;
      }
      else
      {
        CUnit unitX = yfx->GetUnit(*varXName);
        wantedUnit = unitX.GetText();
      }

      yfx->ReadVar(*is, *varX, wantedUnit);
      */
      yfx->ReadVar(*is, *varX, yfx->GetUnit(*is).GetText());
    }

    // Get name
    if (varXName != NULL)
    {
      *varXName = (*is);
    }
  }

}
示例#11
0
文件: Plot.cpp 项目: adakite/main
//----------------------------------------
void CPlot::GetInfo()
{

  CUnit unitXRead;
  CUnit unitYRead;

  string unitXStr;
  string unitYStr;

  bool assignYUnit = true;
  bool assignYTitle = true;
  bool assignXUnit = true;
  bool assignXTitle = true;

  CObArray allInternalFiles(false);


  GetAllInternalFiles(allInternalFiles);
  int32_t nrFiles = allInternalFiles.size();

  //int32_t iField = 0;
  int32_t nrFields = m_fields.size();
  CObArray::iterator itField;
  CObArray::iterator itFile;

  CStringArray plotFieldNames;

  for (itField = m_fields.begin() ; itField != m_fields.end() ; itField++)
  {
    CPlotField* field = CPlotField::GetPlotField(*itField);
    string fieldName = (const char *)(field->m_name);

    plotFieldNames.InsertUnique(fieldName);

    if ((field->m_xyProps != NULL) && (m_title.IsEmpty()) )
    {
      m_title = field->m_xyProps->GetTitle();
    }

    for (itFile = field->m_internalFiles.begin() ; itFile != field->m_internalFiles.end() ; itFile++)
    {

      CInternalFiles* yfx = CPlot::GetInternalFiles(*itFile);
      //-----------------------------------
      // Get plot Title --> title of the first file
      //-----------------------------------
      if (m_title.IsEmpty())
      {
        m_title = yfx->GetTitle("").c_str();
      }

      //-----------------------------------
      // Get and control unit of X axis
      //-----------------------------------
      string varXName;
      GetAxisX(yfx, NULL, NULL, &varXName);

      unitXRead = yfx->GetUnit(varXName);


      if (assignXUnit)
      {
        m_unitX = unitXRead;
        unitXStr = m_unitX.AsString();
        m_unitXLabel = "\nUnit:\t" + wxString(m_unitX.GetText().c_str());
        assignXUnit = false;
      }
      else
      {
        string unitXReadStr = unitXRead.AsString();
        if (m_unitX.IsCompatible(unitXRead) == false)
        {
          string msg = CTools::Format("CPlot::CkeckUnits - In group field number %d, X field unit are not in the same way (not compatible)"
                                      "- Expected unit '%s' and found '%s' for axis X - File name is '%s'",
                                       m_groupNumber,
                                       unitXStr.c_str(),
                                       unitXReadStr.c_str(),
                                       yfx->GetName().c_str());
          CException e(msg, BRATHL_INCONSISTENCY_ERROR);
          CTrace::Tracer("%s", e.what());
          throw (e);

        }
        if (unitXStr.compare(unitXReadStr) != 0)
        {
          m_unitXConv = true;
        }
      }
      //-----------------------------------
      // Get title of X axis
      //-----------------------------------
      string titleX;

      if (m_titleX.IsEmpty())
      {
        titleX = yfx->GetTitle(varXName);
        if (titleX.empty())
        {
          titleX = varXName;
        }
      }

      if (assignXTitle)
      {
        m_titleX += titleX.c_str() + m_unitXLabel;
        assignXTitle = false;
      }

      //--------------------------------------------------------
      // Get and control unit of Y axis --> unit of each field
      //---------------------------------------------------------
      unitYRead = yfx->GetUnit(fieldName);

      if ( assignYUnit )
      {
        m_unitY = unitYRead;
        unitYStr = m_unitY.AsString();
        m_unitYLabel = "\nUnit:\t" + wxString(m_unitY.GetText().c_str());
        assignYUnit = false;
      }
      else
      {
        string unitYReadStr = unitYRead.AsString();
        if (m_unitY.IsCompatible(unitYRead) == false)
        {
          string msg = CTools::Format("CXYPlotData::Create - In group field number %d, Y field unit are not in the same way (not compatible)"
                                      "- Expected unit '%s' and found '%s' for axis Y - Field name is '%s' - File name is '%s'",
                                       m_groupNumber,
                                       unitYStr.c_str(),
                                       unitYReadStr.c_str(),
                                       fieldName.c_str(),
                                       yfx->GetName().c_str());
          CException e(msg, BRATHL_INCONSISTENCY_ERROR);
          CTrace::Tracer("%s", e.what());
          throw (e);

        }
        if (unitYStr.compare(unitYReadStr) != 0)
        {
          m_unitYConv = true;
        }
      }

      //-----------------------------------
      // Get title of Y axis (as possible)
      //-----------------------------------

      string titleY;

      if ((nrFields == 1) && (nrFiles <= 1))
      {
        if (m_titleY.IsEmpty())
        {
          titleY = yfx->GetTitle(fieldName);
          if (titleY.empty())
          {
            titleY = fieldName;
          }
        }
      }

      if (assignYTitle)
      {
        m_titleY += titleY.c_str() + m_unitYLabel;
        assignYTitle = false;
      }


    } // end for (itFile = ...

  } //  end for (itField = ...

  //CTrace::GetInstance()->SetTraceLevel(5);
  //plotFieldNames.Dump(*(CTrace::GetInstance()->GetDumpContext()));

  if (plotFieldNames.size() > 0)
  {
    for (itFile = allInternalFiles.begin() ; itFile != allInternalFiles.end() ; itFile++)
    {
      CInternalFiles* yfx = CPlot::GetInternalFiles(*itFile);

      if (yfx == NULL)
      {
        continue;
      }

      CStringArray complement;

      yfx->GetComplementVars(plotFieldNames, complement);

      CStringArray::iterator itStringArray;
      for (itStringArray = complement.begin() ; itStringArray != complement.end(); itStringArray++)
      {
        CNetCDFVarDef* v1Def = yfx->GetNetCDFVarDef(plotFieldNames.at(0));
        CNetCDFVarDef* v2Def = yfx->GetNetCDFVarDef(*itStringArray);

        if ((v1Def == NULL) || (v2Def == NULL))
        {
          continue;
        }


        if (yfx->GetFile()->HaveEqualDimNames(plotFieldNames.at(0), *itStringArray))
        {
          m_nonPlotFieldNames.InsertUnique(*itStringArray);
        }

      }

      //complement.Dump(*(CTrace::GetInstance()->GetDumpContext()));


    }

    //m_nonPlotFieldNames.Dump(*(CTrace::GetInstance()->GetDumpContext()));
  }

/*


  for (iFile = 0 ; iFile < nrFiles ; iFile++)
  {
    CInternalFilesYFX* yfx = GetInternalFilesYFX(allInternalFiles.at(iFile));
    //-----------------------------------
    // Get plot Title --> title of the first file
    //-----------------------------------
    if (m_title.IsEmpty())
    {
      m_title = yfx->GetTitle("").c_str();
    }

    //-----------------------------------
    // Get and control unit of X axis
    //-----------------------------------
    string varXName;
    GetAxisX(yfx, NULL, NULL, &varXName);

    unitXRead = yfx->GetUnit(varXName);



    //--------------------------------------------------------
    // Get and control unit of Y axis --> unit of each field
    //---------------------------------------------------------

    //int32_t iField = 0;
    int32_t nrFields = m_fields.size();
    CObArray::iterator itField;

    for (itField = m_fields.begin() ; itField != m_fields.end() ; itField++)
    {

      if (assignXUnit)
      {
        m_unitX = unitXRead;
        unitXStr = m_unitX.AsString();
        m_unitXLabel = "\nUnit:\t" + wxString(m_unitX.GetText().c_str());
        assignXUnit = false;
      }
      else
      {
        string unitXReadStr = unitXRead.AsString();
        if (m_unitX.IsCompatible(unitXRead) == false)
        {
          string msg = CTools::Format("CPlot::CkeckUnits - In group field number %d, X field unit are not in the same way (not compatible)"
                                      "- Expected unit '%s' and found '%s' for axis X - File name is '%s'",
                                       m_groupNumber,
                                       unitXStr.c_str(),
                                       unitXReadStr.c_str(),
                                       yfx->GetName().c_str());
          CException e(msg, BRATHL_INCONSISTENCY_ERROR);
          CTrace::Tracer(e.what());
          throw (e);

        }
        if (unitXStr.compare(unitXReadStr) != 0)
        {
          m_unitXConv = true;
        }
      }
      //-----------------------------------
      // Get title of X axis
      //-----------------------------------
      string titleX;

      if (m_titleX.IsEmpty())
      {
        titleX = yfx->GetTitle(varXName);
        if (titleX.empty())
        {
          titleX = varXName;
        }
      }

      //if (iFile == 0)
      if (assignXTitle)
      {
        m_titleX += titleX.c_str() + m_unitXLabel;
        assignXTitle = false;
      }


      CPlotField* field = CPlotField::GetPlotField(*itField);
      string fieldName = field->m_name.c_str();

      unitYRead = yfx->GetUnit(fieldName);

      if ( assignYUnit )
      {
        m_unitY = unitYRead;
        unitYStr = m_unitY.AsString();
        m_unitYLabel = "\nUnit:\t" + wxString(m_unitY.GetText().c_str());
        assignYUnit = false;
      }
      else
      {
        string unitYReadStr = unitYRead.AsString();
        if (m_unitY.IsCompatible(unitYRead) == false)
        {
          string msg = CTools::Format("CXYPlotData::Create - In group field number %d, Y field unit are not in the same way (not compatible)"
                                      "- Expected unit '%s' and found '%s' for axis Y - Field name is '%s' - File name is '%s'",
                                       m_groupNumber,
                                       unitYStr.c_str(),
                                       unitYReadStr.c_str(),
                                       fieldName.c_str(),
                                       yfx->GetName().c_str());
          CException e(msg, BRATHL_INCONSISTENCY_ERROR);
          CTrace::Tracer(e.what());
          throw (e);

        }
        if (unitYStr.compare(unitYReadStr) != 0)
        {
          m_unitYConv = true;
        }
      }

      //-----------------------------------
      // Get title of Y axis (as possible)
      //-----------------------------------

      string titleY;

      if ((nrFields == 1) && (nrFiles <= 1))
      {
        if (m_titleY.IsEmpty())
        {
          titleY = yfx->GetTitle(fieldName);
          if (titleY.empty())
          {
            titleY = fieldName;
          }
        }
      }

      if (assignYTitle)
      {
        m_titleY += titleY.c_str() + m_unitYLabel;
        assignYTitle = false;
      }
    }
  }


*/
}
示例#12
0
int CReplayFile::nLoadXMLConfig(xmlNodePtr pNodePtr)
{
    int nRetValue = S_OK;
    xmlNodePtr pTempNode = pNodePtr;
    CStringArray omStrFilters;
    while( NULL != pNodePtr )
    {
        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Log_File_Path")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                if(PathIsRelative((char*)key) == TRUE)
                {
                    std::string omStrConfigFolder;
                    std::string omPath;
                    char configPath[MAX_PATH];
                    AfxGetMainWnd()->SendMessage(MSG_GET_CONFIGPATH, (WPARAM)configPath, 0);
                    CUtilFunctions::nGetBaseFolder(configPath, omStrConfigFolder );
                    char chAbsPath[MAX_PATH];
                    PathCombine(chAbsPath, omStrConfigFolder.c_str(), (char*)key);
                    m_omStrFileName = chAbsPath;
                }
                else
                {
                    m_omStrFileName = (char*)key;
                }
                xmlFree(key);
            }
        }

        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"IsEnabled")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                m_bEnabled = xmlUtils::getBooleanValue((char*)key);
                xmlFree(key);
            }
        }


        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Retain_Recored_Time")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                m_nTimeMode = xmlUtils::getBooleanValue((char*)key);
                xmlFree(key);
            }
        }
        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Message_Delay")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                m_unMsgTimeDelay = atoi((char*)key);
                xmlFree(key);
            }
        }

        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Is_Cyclic_Mode")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                m_nReplayMode = (int)xmlUtils::getBooleanValue((char*)key);
                xmlFree(key);
            }
        }


        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Cyclic_Delay")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                m_unCycleTimeDelay = atoi((char*)key);
                xmlFree(key);
            }
        }
        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"IsInteractive")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                m_bInteractive = (int)xmlUtils::getBooleanValue((char*)key);
                xmlFree(key);
            }
        }
        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Replay_Message_Direction")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                this->m_ouReplayMsgType = xmlUtils::bGetDirection((char*)key);
                xmlFree(key);
            }
        }

        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Filter")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                omStrFilters.Add((char*)key);
                xmlFree(key);
            }
        }
        pNodePtr = pNodePtr->next;
    }
    //Filters

    if( omStrFilters.GetSize() > 0 && pTempNode != NULL)
    {
        SFILTERAPPLIED_CAN sFilterApplied;
        if( sFilterApplied.nSetXMLConfigData(pTempNode->doc) == S_OK)
        {
            sFilterApplied.nGetFiltersFromName(m_sFilterApplied, omStrFilters);
            /*
            int nRealFilters = 0;
            for(int i = 0; i < omStrFilters.GetSize(); i++)
            {
                int nIndex = GetFilterNameIndex((LPCSTR)omStrFilters.GetAt(i), sFilterApplied);
                if(nIndex >= 0)
                {
                    nRealFilters++;
                }
                else
                {
                    omStrFilters.RemoveAt(i);
                }
            }
            m_sFilterApplied.m_bEnabled = sFilterApplied.m_bEnabled;
            m_sFilterApplied.m_ushTotal = omStrFilters.GetSize();
            m_sFilterApplied.m_psFilters = new SFILTERSET[m_sFilterApplied.m_ushTotal];

            for(int i = 0; i < omStrFilters.GetSize(); i++)
            {
                int nIndex = GetFilterNameIndex((LPCSTR)omStrFilters.GetAt(i), sFilterApplied);
                if(nIndex >= 0)
                {
                    m_sFilterApplied.m_psFilters[i].bClone(sFilterApplied.m_psFilters[nIndex]);
                }
            }*/
        }

    }
    return nRetValue;
}
示例#13
0
BOOL CMsgHandlerDlg::bValidateUserSelection(CFunctionEditorDoc* pDoc)

{
    BOOL bReturn              = TRUE;
    BOOL bButtonChecked       = FALSE;
    CString omStrMsgNameForID = _T("");
    CString omStrMsgIDForName = _T("");

    if(pDoc != NULL )
    {
        CString omStrText = _T("");
        CString omStrHandlerType = _T("");
        bButtonChecked =  IsDlgButtonChecked(IDC_RBTN_MSG_NAME);

        CStringArray* pMsgArray = pDoc->omStrGetMessageHandlerPrototypes();

        if(bButtonChecked)
        {
            //COMMENTED BY AK **************
            int nSelection = 0;
            UINT unMsgIDForName = 0;
            CString omStrMsgName = _T("");
            nSelection = m_omListMsgName.GetCurSel();
            m_omListMsgName.GetText(nSelection,omStrMsgName);
            // get the corresponding message ID from the database
           /* unMsgIDForName=CMsgSignal::ouGetMsgSignal().nGetSlotIDFromName(omStrMsgName);
            if(unMsgIDForName != -1)
            {
                omStrMsgIDForName.Format("%x",unMsgIDForName);
                bReturn = bValidateMessageNameAndID( pMsgArray,
                                                     defMSG_NAME_HANDLER,
                                                     omStrMsgIDForName);
            }*/
            m_omStrSelectedItemText = defMSG_NAME_HANDLER;
            m_omStrSelectedItemText += omStrMsgName;
            omStrText = "\""+ omStrMsgName + "\"";
            omStrHandlerType = defMSG_NAME_TEXT;
        }
        else
        {
            bButtonChecked =  IsDlgButtonChecked(IDC_RBTN_MSG_ID);
            if(bButtonChecked != 0)
            {
                UINT unMsgID = 0;
                unMsgID = (UINT)m_odEditMsgID.lGetValue();
                // Get the corresponding message name from the database
                /*omStrMsgNameForID = CMsgSignal::ouGetMsgSignal().
                            omStrGetMessageNameFromSlotID(unMsgID);
                bReturn = bValidateMessageNameAndID( pMsgArray,
                                                     defMSG_ID_HANDLER,
                                                     omStrMsgNameForID);*/
                m_omStrSelectedItemText = defMSG_ID_HANDLER;
                m_omStrSelectedItemText += m_omStrMsgID;
                omStrText = _T("\"")+ m_omStrMsgID + _T("\"");
                omStrHandlerType = defMSG_ID_TEXT;
            }
            else
            {
                bButtonChecked =  IsDlgButtonChecked(IDC_RBTN_MSG_RANGE);
                if(bButtonChecked != 0)
                {
                    UINT unMsgIDFrom = 0;
                    UINT unMsgIDTo   = 0;
                    m_omStrSelectedItemText = defMSG_IDRANGE_HANDLER;
                    m_omStrSelectedItemText += m_omStrMsgIDFrom;
                    m_omStrSelectedItemText += "_";
                    m_omStrSelectedItemText += m_omStrMsgIDTo;
                    unMsgIDTo    = (UINT)m_odEditMsgIDTo.lGetValue();
                    unMsgIDFrom  =(UINT) m_odEditMsgIDFrom.lGetValue();
                    if(unMsgIDFrom < unMsgIDTo)
                    {
                        omStrText = _T("\"")+ m_omStrMsgIDFrom;
                        omStrText += _T("-");
                        omStrText += m_omStrMsgIDTo;
                        omStrText += _T("\"");
                        omStrHandlerType = defMSG_IDRANGE_TEXT;
                    }
                    else
                    {
                        bReturn = FALSE;
                        AfxMessageBox(defSTRMSG_RANGE_INVALID);
                        m_odEditMsgIDFrom.SetFocus();
                    }
                }
                else
                {
                    bButtonChecked =  IsDlgButtonChecked(IDC_RBTN_MSG_ALL);
                    if(bButtonChecked != 0)
                    {
                        m_omStrSelectedItemText = defMSG_ALL;
                        omStrHandlerType = defMSG_ALL_TEXT;
                        omStrText = "message";
                    }
                }
            }

        }

        if(bReturn == TRUE)
        {
            if (pMsgArray)
            {
                CString omStrMsgPro = STR_EMPTY;
                CString omStrMsgCommon = CGlobalObj::omGetBusSpecMsgHndlrName(m_eBus);
                for (int nCount = 0;nCount<pMsgArray->GetSize(); nCount++ )
                {
                    omStrMsgPro = pMsgArray->GetAt( nCount );
                    omStrMsgPro = omStrMsgPro.Right(omStrMsgPro.GetLength()
                                                  - omStrMsgPro.Find(_T(" ")) - 1);
                    omStrMsgPro = omStrMsgPro.Right(omStrMsgPro.GetLength()
                                                  - omStrMsgCommon.GetLength());
                    omStrMsgPro = omStrMsgPro.Left( omStrMsgPro.Find(_T("(")) );
                    omStrMsgPro.TrimLeft();
                    omStrMsgPro.TrimRight();
                    if (omStrMsgPro.Compare(m_omStrSelectedItemText) == 0) 
                    {
                        // Form the message to be dispalyed
                        omStrMsgPro = defMSG_DUPL_MSG_HANDLER;
                        omStrMsgPro.Replace( _T("TYPE"), 
                            omStrHandlerType );
                        omStrMsgPro.Replace( _T("MESSAGENAME"), 
                            omStrText );
                        // Duplicate message hanlder, shout
                        AfxMessageBox( omStrMsgPro, 
                            MB_OK|MB_ICONINFORMATION );
                        nCount = (COMMANINT)pMsgArray->GetSize();
                        bReturn = FALSE;
                       if(omStrHandlerType.Compare(defMSG_NAME_TEXT) ==0 )
                       {
                            m_omListMsgName.SetFocus();  
                       }
                       else if(omStrHandlerType.Compare(defMSG_ID_TEXT) == 0 )
                       {
                            m_odEditMsgID.SetFocus();
                       }
                       else if(
                           omStrHandlerType.Compare(defMSG_IDRANGE_TEXT) == 0 )
                       {
                           m_odEditMsgIDFrom.SetFocus();
                       }

                    }
                }
            }
            else
            {
                bReturn = FALSE;
            }
        }
    }
    else
    {
        bReturn = FALSE;
    }
    // Remove the selected item from the list
    if( bReturn == TRUE && bButtonChecked == TRUE)
    {
        int nIndex = m_omListMsgName.GetCurSel();
        if( nIndex != -1 )
            m_omListMsgName.DeleteString( nIndex );
    }

    return bReturn;
}
示例#14
0
void CMsgHandlerDlg::OnCbtnMsgHandlerApply() 
{

    BOOL bValidateSelection = FALSE;
    UpdateData(TRUE);
    m_omButtonApply.EnableWindow(FALSE);
    m_omButtonOK.EnableWindow(FALSE);
    // Get document pointer
    CFunctionEditorDoc* pDoc = CGlobalObj::ouGetObj(m_eBus).podGetFunctionEditorDoc();
    if (NULL != pDoc)
    {
        SBUS_SPECIFIC_INFO sBusSpecInfo;
        pDoc->bGetBusSpecificInfo(sBusSpecInfo);
        // Validate user selections
        bValidateSelection = bValidateUserSelection(pDoc); 
        if (bValidateSelection == TRUE)
        {
            CString omFunc = CGlobalObj::omGetBusSpecMsgHndlrName(m_eBus);;
            // Add to function editor
            CString omSelectedText = _T("");

            omSelectedText = BUS_FN_HDR; // Start comment section: init
            omSelectedText.Replace(_T("PLACE_HODLER_FOR_BUSNAME"), 
                             sBusSpecInfo.m_omBusName); // Replace the bus name

            omFunc += m_omStrSelectedItemText;
            omSelectedText.Replace( _T("PLACE_HODLER_FOR_FUNCTIONNAME"),
                omFunc );
            pDoc->m_omSourceCodeTextList.AddTail( omSelectedText );
            // Form the function prototype
            omSelectedText  = m_omStrSelectedItemText;
            int nIndex = -1;
            

            // Get the type and set the parameter type
            BOOL bIsMsgSpecificHandler = FALSE;
            //Find out whether the Msg handler is DatabaseMsgName type or ID type
            CString omMsgHandlerType = CGlobalObj::ouGetObj(m_eBus).m_omMsgStructName;
            nIndex = omSelectedText.Find(defSTR_MSG_SPECIFIC_HANDLER);
            
            if( nIndex != -1 )
            {
                bIsMsgSpecificHandler = TRUE;
                // For database message type is equal same as msg name
                omMsgHandlerType = omSelectedText.Mid( nIndex +
                                                     defMESSAGE_NAME_INDEX );
            }
            CString omStrParamtype;
            
            if (bIsMsgSpecificHandler == TRUE && (m_eBus == CAN))
            {
                omStrParamtype = omMsgHandlerType;
            }
            else// For Msg ID, Range and generic messages the type is sTCANDATA
            {
                omStrParamtype = CGlobalObj::ouGetObj(m_eBus).m_omMsgStructName;
            }
            CString omFormatString = m_eBus == CAN ? defDEFAULT_MSG_HANDLER_CODE_CAN : defDEFAULT_MSG_HANDLER_CODE;
            omSelectedText.Format(  omFormatString,
                                    CGlobalObj::omGetBusSpecMsgHndlrName(sBusSpecInfo.m_eBus),
                                    omSelectedText,   // Fun name
                                    omStrParamtype ); // Parameter type

            pDoc->m_omSourceCodeTextList.AddTail( omSelectedText );

            CString omStrPrototype = omSelectedText;
            // Add to tree view
            CFnsTreeView* pomTreeView = CGlobalObj::ouGetObj(m_eBus).podGetFuncsTreeViewPtr();
            if(pomTreeView != NULL )
            {
                // Add the prototype to the tree view
                CTreeCtrl& omTree = pomTreeView->GetTreeCtrl();
                HTREEITEM hItem = omTree.GetSelectedItem();
                HTREEITEM hNew = 
                    omTree.InsertItem( omSelectedText, hItem);
                omTree.SetItemImage( hNew, 5, 5 );
                omTree.SelectItem( hNew );
                // Form the body of the function
                omSelectedText = "{";
                pDoc->m_omSourceCodeTextList.AddTail( omSelectedText );
                if (CGlobalObj::ouGetObj(m_eBus).m_omMsgStructName.IsEmpty())
                {
                    ASSERT(FALSE);
                }
                omSelectedText = defTODO;
                pDoc->m_omSourceCodeTextList.AddTail( omSelectedText );

                // Form the function footer
                omSelectedText = BUS_FN_FOOTER;
                omSelectedText.Replace(_T("PLACE_HODLER_FOR_BUSNAME"), sBusSpecInfo.m_omBusName);
                omSelectedText.Replace( _T("PLACE_HODLER_FOR_FUNCTIONNAME"),
                    omFunc );

                pDoc->m_omSourceCodeTextList.AddTail( omSelectedText );

                CStringArray* pMsgArray = 
                    pDoc->omStrGetMessageHandlerPrototypes();
                if ( pMsgArray != NULL )
                {
                    pMsgArray->Add( omStrPrototype );
                }
                pDoc->UpdateAllViews( NULL );
                pDoc->SetModifiedFlag( TRUE );
            }
        }
    }
    m_omStrSelectedItemText = _T("");
    BOOL bButtonChecked  = FALSE;
    bButtonChecked =  IsDlgButtonChecked(IDC_RBTN_MSG_NAME);
    if(bButtonChecked != FALSE )
    {
         m_omListMsgName.SetCurSel(-1);
    }
}
示例#15
0
/**
 * \brief initialises user selection
 * \return TRUE or FALSE
 *
 * This method will initialise user selection from
 * a configuration module to respective module.
 */
BOOL CCANMonitorApp::bInitialiseConfiguration(BOOL bFromCom)
{
    BOOL bReturn = TRUE;
    CMainFrame* pMainFrame = static_cast<CMainFrame*> (m_pMainWnd);

    if(pMainFrame != nullptr )
    {
        BOOL bIsDatabaseFoundInConfigFile = FALSE;

        if(m_pouMsgSignal != nullptr)
        {
            m_pouMsgSignal->bDeAllocateMemory("");
        }
        else
        {
            m_pouMsgSignal = new CMsgSignal(sg_asDbParams[CAN], m_bFromAutomation);
        }

        if ( m_pouMsgSignal != nullptr )
        {
            //Get the Database names
            CStringArray aomOldDatabases;
            //To keep all the files which are successfully imported
            CStringArray aomNewDatabases;
            aomNewDatabases.RemoveAll();
            m_pouMsgSignal->vGetDataBaseNames(&aomOldDatabases);
            int nFileCount = aomOldDatabases.GetSize();

            if(nFileCount == 0)
            {
                bIsDatabaseFoundInConfigFile = FALSE;
                // Reset corresponding flag
                m_pouFlags->vSetFlagStatus( SELECTDATABASEFILE, FALSE );
            }
            else
            {
                CString omStrDatabase;
                int nDatabaseNotFound = 0;

                for(int nCount = 0; nCount < nFileCount; nCount++)
                {
                    omStrDatabase  = aomOldDatabases.GetAt(nCount);

                    if (omStrDatabase.IsEmpty())
                    {
                        nDatabaseNotFound++;
                        aomOldDatabases.RemoveAt(nCount);
                        --nCount;
                        --nFileCount;
                    }
                    else
                    {
                        bIsDatabaseFoundInConfigFile = TRUE;
                        // Check if the file really exists
                        struct _finddata_t fileinfo;

                        if (_findfirst(omStrDatabase.GetBuffer(MAX_PATH) ,&fileinfo) == -1L)
                        {
                            CString omStrMsg = _("Database File: ");
                            omStrMsg += omStrDatabase;
                            omStrMsg += _(" not found!");

                            if(bFromCom==FALSE)
                            {
                                MessageBox(nullptr,omStrMsg,"BUSMASTER",MB_OK|MB_ICONERROR);
                            }

                            // Remove the file name from configuration file.
                            nDatabaseNotFound++;
                            aomOldDatabases.RemoveAt(nCount);
                            --nCount;
                            --nFileCount;
                        }
                        else
                        {
                            // Reset corresponding flag
                            m_pouFlags->vSetFlagStatus( SELECTDATABASEFILE, TRUE );
                            m_pouMsgSignal->
                            bFillDataStructureFromDatabaseFile(omStrDatabase, PROTOCOL_UNKNOWN);
                            pMainFrame->vPopulateJ1939PGNList();
                            aomNewDatabases.Add(omStrDatabase);
                        }
                    }
                }

                if(nDatabaseNotFound > 0)
                {
                    BYTE* pbyConfigData = nullptr;
                    UINT unSize = 0;
                    unSize += (sizeof (UINT) + ((sizeof(char) *MAX_PATH) * aomNewDatabases.GetSize()));
                    pbyConfigData = new BYTE[unSize];
                    BYTE* pbyTemp = pbyConfigData;
                    UINT nCount = 0;
                    COPY_DATA(pbyTemp, &nCount, sizeof(UINT));

                    for (UINT i = 0; i < nCount; i++)
                    {
                        char acName[MAX_PATH] = { '\0' };
                        CString omDBName = aomNewDatabases.GetAt(i);
                        strcpy_s(acName, MAX_PATH, omDBName.GetBuffer(MAX_PATH));
                        COPY_DATA(pbyTemp, acName, sizeof(char) * MAX_PATH);
                    }

                    CConfigData::ouGetConfigDetailsObject().bSetData(pbyTemp, unSize, SectionName[DATABASE_SECTION_ID]);
                    delete[] pbyConfigData;
                    pbyConfigData = nullptr;
                }

                if(aomNewDatabases.GetSize()== 0)
                {
                    // Reset the flag and prompt user of file not in disk.
                    m_pouFlags->vSetFlagStatus( SELECTDATABASEFILE, FALSE );
                }
            }
        }
        else
        {
            if(bFromCom==FALSE)
                // Display a message and quit the application
                MessageBox(nullptr,
                           _(MSG_MEMORY_CONSTRAINT),
                           "BUSMASTER",
                           MB_OK|MB_ICONINFORMATION);

            bReturn = FALSE;
        }

        //Finally load the default configuration
        pMainFrame->nLoadConfigFile("");
    }

    return bReturn;
}
void CPlayerSubresyncBar::OnRclickList(NMHDR* pNMHDR, LRESULT* pResult)
{
    LPNMLISTVIEW lpnmlv = (LPNMLISTVIEW)pNMHDR;

    if (lpnmlv->iItem >= 0 && lpnmlv->iSubItem >= 0) {
        enum {
            TOGSEP = 1,
            DUPITEM, DELITEM,
            RESETS, SETOS, SETCS, RESETE, SETOE, SETCE,
            STYLEFIRST, STYLELAST = STYLEFIRST + 1000, STYLEEDIT,
            UNICODEYES, UNICODENO,
            LAYERDEC, LAYERINC,
            ACTORFIRST, ACTORLAST = ACTORFIRST + 1000,
            EFFECTFIRST, EFFECTLAST = EFFECTFIRST + 1000
        };

        CStringArray styles;
        CStringArray actors;
        CStringArray effects;

        CMenu m;
        m.CreatePopupMenu();

        if (m_mode == VOBSUB || m_mode == TEXTSUB) {
            m.AppendMenu(MF_STRING | MF_ENABLED, TOGSEP, ResStr(IDS_SUBRESYNC_SEPARATOR));
            m.AppendMenu(MF_SEPARATOR);
            if (m_mode == TEXTSUB) {
                m.AppendMenu(MF_STRING | MF_ENABLED, DUPITEM, ResStr(IDS_SUBRESYNC_DUPLICATE));
            }
            m.AppendMenu(MF_STRING | MF_ENABLED, DELITEM, ResStr(IDS_SUBRESYNC_DELETE));
        }

        switch (lpnmlv->iSubItem) {
            case COL_START:
                if (m_mode == VOBSUB || m_mode == TEXTSUB) {
                    m.AppendMenu(MF_SEPARATOR);
                    m.AppendMenu(MF_STRING | MF_ENABLED, RESETS, ResStr(IDS_SUBRESYNC_RESET) + _T("\tF1"));
                    m.AppendMenu(MF_STRING | MF_ENABLED, SETOS, ResStr(IDS_SUBRESYNC_ORIGINAL) + _T("\tF3"));
                    m.AppendMenu(MF_STRING | MF_ENABLED, SETCS, ResStr(IDS_SUBRESYNC_CURRENT) + _T("\tF5"));
                }
                break;
            case COL_END:
                if (m_mode == TEXTSUB) {
                    m.AppendMenu(MF_SEPARATOR);
                    m.AppendMenu(MF_STRING | MF_ENABLED, RESETE, ResStr(IDS_SUBRESYNC_RESET) + _T("\tF2"));
                    m.AppendMenu(MF_STRING | MF_ENABLED, SETOE, ResStr(IDS_SUBRESYNC_ORIGINAL) + _T("\tF4"));
                    m.AppendMenu(MF_STRING | MF_ENABLED, SETCE, ResStr(IDS_SUBRESYNC_CURRENT) + _T("\tF6"));
                }
                break;
            case COL_STYLE:
                if (m_mode == TEXTSUB) {
                    m.AppendMenu(MF_SEPARATOR);

                    int id = STYLEFIRST;

                    POSITION pos = m_sts.m_styles.GetStartPosition();
                    while (pos && id <= STYLELAST) {
                        CString key;
                        STSStyle* val;
                        m_sts.m_styles.GetNextAssoc(pos, key, val);
                        styles.Add(key);
                        m.AppendMenu(MF_STRING | MF_ENABLED, id++, key);
                    }

                    if (id > STYLEFIRST && m_list.GetSelectedCount() == 1) {
                        m.AppendMenu(MF_SEPARATOR);
                        m.AppendMenu(MF_STRING | MF_ENABLED, STYLEEDIT, ResStr(IDS_SUBRESYNC_EDIT));
                    }
                }
                break;
            case COL_UNICODE:
                if (m_mode == TEXTSUB) {
                    m.AppendMenu(MF_SEPARATOR);
                    m.AppendMenu(MF_STRING | MF_ENABLED, UNICODEYES, m_strYesMenu);
                    m.AppendMenu(MF_STRING | MF_ENABLED, UNICODENO, m_strNoMenu);
                }
                break;
            case COL_LAYER:
                if (m_mode == TEXTSUB) {
                    m.AppendMenu(MF_SEPARATOR);
                    m.AppendMenu(MF_STRING | MF_ENABLED, LAYERDEC, ResStr(IDS_SUBRESYNC_DECREASE));
                    m.AppendMenu(MF_STRING | MF_ENABLED, LAYERINC, ResStr(IDS_SUBRESYNC_INCREASE));
                }
                break;
            case COL_ACTOR:
                if (m_mode == TEXTSUB) {
                    CMapStringToPtr actormap;

                    for (size_t i = 0, j = m_sts.GetCount(); i < j; i++) {
                        actormap[m_sts[i].actor] = nullptr;
                    }

                    actormap.RemoveKey(_T(""));

                    if (!actormap.IsEmpty()) {
                        m.AppendMenu(MF_SEPARATOR);

                        int id = ACTORFIRST;

                        POSITION pos = actormap.GetStartPosition();
                        while (pos && id <= ACTORLAST) {
                            CString key;
                            void* val;
                            actormap.GetNextAssoc(pos, key, val);

                            actors.Add(key);

                            m.AppendMenu(MF_STRING | MF_ENABLED, id++, key);
                        }
                    }
                }
                break;
            case COL_EFFECT:
                if (m_mode == TEXTSUB) {
                    CMapStringToPtr effectmap;

                    for (size_t i = 0, j = m_sts.GetCount(); i < j; i++) {
                        effectmap[m_sts[i].effect] = nullptr;
                    }

                    effectmap.RemoveKey(_T(""));

                    if (!effectmap.IsEmpty()) {
                        m.AppendMenu(MF_SEPARATOR);

                        int id = EFFECTFIRST;

                        POSITION pos = effectmap.GetStartPosition();
                        while (pos && id <= EFFECTLAST) {
                            CString key;
                            void* val;
                            effectmap.GetNextAssoc(pos, key, val);

                            effects.Add(key);

                            m.AppendMenu(MF_STRING | MF_ENABLED, id++, key);
                        }
                    }
                }
                break;
        }

        CPoint p = lpnmlv->ptAction;
        ::MapWindowPoints(pNMHDR->hwndFrom, HWND_DESKTOP, &p, 1);

        UINT id = m.TrackPopupMenu(TPM_LEFTBUTTON | TPM_RETURNCMD, p.x, p.y, this);

        bool bNeedsUpdate = false;

        POSITION pos = m_list.GetFirstSelectedItemPosition();
        while (pos) {
            int iItem = m_list.GetNextSelectedItem(pos);

            SubTime& st = m_subtimes[iItem];

            switch (id) {
                case TOGSEP:
                    m_displayData[iItem].flags ^= TSEP;
                    m_list.Invalidate();
                    bNeedsUpdate = true;
                    break;
                case DUPITEM: {
                    CUIntArray items;
                    pos = m_list.GetFirstSelectedItemPosition();
                    while (pos) {
                        items.Add(m_list.GetNextSelectedItem(pos));
                    }

                    qsort(items.GetData(), items.GetCount(), sizeof(UINT), uintcomp);

                    for (INT_PTR i = 0, l = items.GetCount(); i < l; i++) {
                        iItem = items[i];

                        STSEntry entry = m_sts[iItem];
                        m_sts.InsertAt(iItem + 1, entry);
                        SubTime subtime = m_subtimes[iItem];
                        m_subtimes.InsertAt(iItem + 1, subtime);
                        DisplayData displayData = m_displayData[iItem];
                        m_displayData.InsertAt(iItem + 1, displayData);
                    }

                    m_list.SetItemCount((int)m_sts.GetCount());

                    bNeedsUpdate = true;
                    break;
                }
                case DELITEM: {
                    CUIntArray items;
                    pos = m_list.GetFirstSelectedItemPosition();
                    while (pos) {
                        items.Add(m_list.GetNextSelectedItem(pos));
                    }

                    qsort(items.GetData(), items.GetCount(), sizeof(UINT), uintcomp);

                    for (INT_PTR i = 0, l = items.GetCount(); i < l; i++) {
                        iItem = items[i];
                        m_sts.RemoveAt(iItem);
                        m_subtimes.RemoveAt(iItem);
                        m_displayData.RemoveAt(iItem);
                    }

                    m_list.SetItemCount((int)m_sts.GetCount());

                    iItem = items[items.GetCount() - 1];
                    if (iItem >= m_list.GetItemCount()) {
                        iItem = m_list.GetItemCount() - 1;
                    }
                    m_list.SetSelectionMark(iItem);

                    bNeedsUpdate = true;
                    break;
                }
                case RESETS:
                    ModStart(iItem, st.orgStart, true);
                    bNeedsUpdate = true;
                    break;
                case SETOS:
                    ModStart(iItem, st.orgStart);
                    bNeedsUpdate = true;
                    break;
                case SETCS:
                    ModStart(iItem, (int)(m_rt / 10000));
                    bNeedsUpdate = true;
                    break;
                case RESETE:
                    ModEnd(iItem, st.orgEnd, true);
                    bNeedsUpdate = true;
                    break;
                case SETOE:
                    ModEnd(iItem, st.orgEnd);
                    bNeedsUpdate = true;
                    break;
                case SETCE:
                    ModEnd(iItem, (int)(m_rt / 10000));
                    bNeedsUpdate = true;
                    break;
                default:
                    if (STYLEFIRST <= id && id <= STYLELAST) {
                        CString s = styles[id - STYLEFIRST];
                        if (m_sts[iItem].style != s) {
                            m_sts[iItem].style = s;
                            bNeedsUpdate = true;
                        }
                    } else if (id == STYLEEDIT) {
                        CAutoPtrArray<CPPageSubStyle> pages;
                        CAtlArray<STSStyle*> styles;

                        STSStyle* stss = m_sts.GetStyle(iItem);
                        int iSelPage = 0;

                        POSITION pos = m_sts.m_styles.GetStartPosition();
                        for (int i = 0; pos; i++) {
                            CString key;
                            STSStyle* val;
                            m_sts.m_styles.GetNextAssoc(pos, key, val);

                            CAutoPtr<CPPageSubStyle> page(DEBUG_NEW CPPageSubStyle());
                            page->InitStyle(key, *val);
                            pages.Add(page);
                            styles.Add(val);

                            if (stss == val) {
                                iSelPage = i;
                            }
                        }

                        CPropertySheet dlg(ResStr(IDS_SUBTITLES_STYLES_CAPTION), this, iSelPage);
                        for (size_t i = 0, l = pages.GetCount(); i < l; i++) {
                            dlg.AddPage(pages[i]);
                        }

                        if (dlg.DoModal() == IDOK) {
                            for (size_t j = 0, l = pages.GetCount(); j < l; j++) {
                                pages[j]->GetStyle(*styles[j]);
                            }
                            bNeedsUpdate = true;
                        }
                    } else if (id == UNICODEYES || id == UNICODENO) {
                        m_sts.ConvertUnicode(iItem, id == UNICODEYES);
                        bNeedsUpdate = true;
                    } else if (id == LAYERDEC || id == LAYERINC) {
                        int d = (id == LAYERDEC) ? -1 : 1;
                        m_sts[iItem].layer += d;
                        bNeedsUpdate = true;
                    } else if (ACTORFIRST <= id && id <= ACTORLAST) {
                        CString s = actors[id - ACTORFIRST];
                        if (m_sts[iItem].actor != s) {
                            m_sts[iItem].actor = s;
                            bNeedsUpdate = true;
                        }
                    } else if (EFFECTFIRST <= id && id <= EFFECTLAST) {
                        CString s = effects[id - EFFECTFIRST];
                        if (m_sts[iItem].effect != s) {
                            m_sts[iItem].effect = s;
                            bNeedsUpdate = true;
                        }
                    }
                    break;
            }

            if (bNeedsUpdate) {
                m_list.Update(iItem);
            }
        }

        if (bNeedsUpdate) {
            UpdatePreview();
        }
    }

    *pResult = 0;
}
示例#17
0
CString GetNDCRulFile(CString& sNDC,CString& sMobnum,DWORD& dwMaxLen)
{
	dwMaxLen=0;
	static CFileInfoArray dir;
	static BOOL bAdded=0;
	static CMapStringToString aNDCIndex;
	if(bAdded==0){
		bAdded=1;
		dir.AddDir(GetAppFolder()+"Sms/","*.rul",TRUE,0,FALSE);
		for(int i=0;i<dir.GetSize();i++){
			CString sItemPath=dir[i].GetFilePath();
			CString sContent;
			ReadFile(sItemPath,sContent);
			sContent.Replace("\r","");
			sContent+="\n";
			CString sLen=CDataXMLSaver::GetInstringPart("SmsMaxLength=","\n",sContent);
			CString sNDCs=CDataXMLSaver::GetInstringPart("SmsNdcList=","\n",sContent);
			CString sName=CDataXMLSaver::GetInstringPart("WndTitle=","\n",sContent);
			if(sNDCs!=""){
				CStringArray aNDCs;
				ConvertToArray(sNDCs,aNDCs,',');
				for(int j=0;j<aNDCs.GetSize();j++){
					CString sOld=aNDCIndex[aNDCs[j]];
					if(sOld!=""){
						sOld+="|";
					}
					sOld+=sItemPath+"\t"+sLen+"\t"+sName;
					aNDCIndex.SetAt(aNDCs[j],sOld);
				}
			}
		}
	}
	CString sNDCData=aNDCIndex[sNDC];
	if(sNDCData.Find("|")!=-1){
		// Выбор :(
		CStringArray aOperators;
		ConvertToArray(sNDCData,aOperators,'|');
		CStringArray aOperatorsNames;
		int i=0;
		for(i=0;i<aOperators.GetSize();i++){
			CStringArray aDats;
			ConvertToArray(aOperators[i],aDats,'\t');
			if(aDats.GetSize()>=3){
				aOperatorsNames.Add(aDats[2]);
			}
		}
		i=SelectFromMenu(aOperatorsNames,0);
		if(i>=0){
			sNDCData=aOperators[i];
		}else{
			return "000";
		}
	}
	if(sNDCData!=""){
		CStringArray aDats;
		ConvertToArray(sNDCData,aDats,'\t');
		if(aDats.GetSize()>=2){
			dwMaxLen=atol(aDats[1]);
			return aDats[0];
		}
	}
	// Доверяем гуглу?
	CString sRetFile=GetAppFolder()+"Sms/default.rul";
	if(isFileExist(sRetFile)){
		CString sContent;
		ReadFile(sRetFile,sContent);
		CString sCList=CDataXMLSaver::GetInstringPart("SmsCarriersList=","\n",sContent);
		CStringArray aCarriers;
		ConvertToArray(sCList,aCarriers,',');
		int i=SelectFromMenu(aCarriers,0);
		if(i>0){
			dwMaxLen=1000;
			sMobnum=sNDC+sMobnum;
			sNDC=Format("%i",i);
			return sRetFile;
		}
		if(i<0){
			return "000";
		}
	}
	return "";
}
示例#18
0
void CMuleToolbarCtrl::OnNmRClick(NMHDR* /*pNMHDR*/, LRESULT* pResult)
{
	if (GetKeyState(VK_CONTROL) & 0x8000)
	{
		if (!thePrefs.GetToolbarBitmapSettings().IsEmpty())
			ChangeToolbarBitmap(thePrefs.GetToolbarBitmapSettings(), true);
		if (!thePrefs.GetSkinProfile().IsEmpty())
			theApp.ApplySkin(thePrefs.GetSkinProfile());

		*pResult = TRUE;
		return;
	}


	///////////////////////////////////////////////////////////////////////////
	// "Toolbar Bitmap" sub menu
	//
	CMenu menuBitmaps;
	menuBitmaps.CreateMenu();
	menuBitmaps.AppendMenu(MF_STRING, MP_SELECTTOOLBARBITMAP, GetResString(IDS_SELECTTOOLBARBITMAP));
	menuBitmaps.AppendMenu(MF_STRING, MP_SELECTTOOLBARBITMAPDIR, GetResString(IDS_SELECTTOOLBARBITMAPDIR));
	menuBitmaps.AppendMenu(MF_SEPARATOR);
	menuBitmaps.AppendMenu(MF_STRING, MP_TOOLBARBITMAP, GetResString(IDS_DEFAULT));
	
	m_astrToolbarPaths.RemoveAll();
	CString currentBitmapSettings = thePrefs.GetToolbarBitmapSettings();
	bool checked = false;
	if (currentBitmapSettings.IsEmpty())
	{
		menuBitmaps.CheckMenuItem(MP_TOOLBARBITMAP, MF_CHECKED);
		menuBitmaps.EnableMenuItem(MP_TOOLBARBITMAP, MF_DISABLED);
		checked = true;
	}
	m_astrToolbarPaths.Add(_T("")); // dummy entry for 'Default' menu item
	int i = 1;
	if (!thePrefs.GetMuleDirectory(EMULE_TOOLBARDIR).IsEmpty())
	{
		CStringArray astrToolbarFiles;
		for (int f = 0; f < _countof(s_apszTBFiles); f++)
		{
			WIN32_FIND_DATA FileData;
			HANDLE hSearch = FindFirstFile(thePrefs.GetMuleDirectory(EMULE_TOOLBARDIR) + CString(_T("\\")) + s_apszTBFiles[f], &FileData);
			if (hSearch != INVALID_HANDLE_VALUE)
			{
				do {
					astrToolbarFiles.Add(FileData.cFileName);
				}
				while (astrToolbarFiles.GetCount() < MAX_TOOLBAR_FILES && FindNextFile(hSearch, &FileData));
				FindClose(hSearch);
			}
		}

		if (astrToolbarFiles.GetCount() > 0)
		{
			Sort(astrToolbarFiles);
			for (int f = 0; f < astrToolbarFiles.GetCount(); f++)
			{
				const CString& bitmapFileName = astrToolbarFiles.GetAt(f);
				CString bitmapBaseName;
				LPCTSTR pszTbBaseExt = stristr(bitmapFileName, EMULTB_BASEEXT);
				if (pszTbBaseExt)
					bitmapBaseName = bitmapFileName.Left(pszTbBaseExt - (LPCTSTR)bitmapFileName - 1);
				else
					bitmapBaseName = bitmapFileName;
				menuBitmaps.AppendMenu(MF_STRING, MP_TOOLBARBITMAP + i, bitmapBaseName);
				m_astrToolbarPaths.Add(thePrefs.GetMuleDirectory(EMULE_TOOLBARDIR) + CString(_T("\\")) + bitmapFileName);
				if (!checked && currentBitmapSettings.CompareNoCase(m_astrToolbarPaths[i]) == 0)
				{
					menuBitmaps.CheckMenuItem(MP_TOOLBARBITMAP + i, MF_CHECKED);
					menuBitmaps.EnableMenuItem(MP_TOOLBARBITMAP + i, MF_DISABLED);
					checked = true;
				}
				i++;
			}
		}
		ASSERT( i-1 == astrToolbarFiles.GetCount() );
	}
	if (!checked)
	{
		menuBitmaps.AppendMenu(MF_STRING, MP_TOOLBARBITMAP + i, currentBitmapSettings);
		menuBitmaps.CheckMenuItem(MP_TOOLBARBITMAP + i, MF_CHECKED);
		menuBitmaps.EnableMenuItem(MP_TOOLBARBITMAP + i, MF_DISABLED);
		m_astrToolbarPaths.Add(currentBitmapSettings);
	}


	///////////////////////////////////////////////////////////////////////////
	// "Skin Profile" sub menu
	//
	CMenu menuSkins;
	menuSkins.CreateMenu();
	menuSkins.AppendMenu(MF_STRING, MP_SELECT_SKIN_FILE, GetResString(IDS_SEL_SKIN));
	menuSkins.AppendMenu(MF_STRING, MP_SELECT_SKIN_DIR, GetResString(IDS_SEL_SKINDIR));
	menuSkins.AppendMenu(MF_SEPARATOR);
	menuSkins.AppendMenu(MF_STRING, MP_SKIN_PROFILE,GetResString(IDS_DEFAULT));

	m_astrSkinPaths.RemoveAll();
	CString currentSkin = thePrefs.GetSkinProfile();
	checked = false;
	if (currentSkin.IsEmpty())
	{
		menuSkins.CheckMenuItem(MP_SKIN_PROFILE, MF_CHECKED);
		menuSkins.EnableMenuItem(MP_SKIN_PROFILE, MF_DISABLED);
		checked = true;
	}
	m_astrSkinPaths.Add(_T("")); // dummy entry for 'Default' menu item
	i = 1;
	if (!thePrefs.GetMuleDirectory(EMULE_SKINDIR, false).IsEmpty())
	{
		CStringArray astrSkinFiles;
		for (int f = 0; f < _countof(s_apszSkinFiles); f++)
		{
			WIN32_FIND_DATA FileData;
			HANDLE hSearch = FindFirstFile(thePrefs.GetMuleDirectory(EMULE_SKINDIR, false) + CString(_T("\\")) + s_apszSkinFiles[f], &FileData);
			if (hSearch != INVALID_HANDLE_VALUE)
			{
				do {
					astrSkinFiles.Add(FileData.cFileName);
				}
				while (astrSkinFiles.GetCount() < MAX_SKIN_FILES && FindNextFile(hSearch, &FileData));
				FindClose(hSearch);
			}
		}

		if (astrSkinFiles.GetCount() > 0)
		{
			Sort(astrSkinFiles);
			for (int f = 0; f < astrSkinFiles.GetCount(); f++)
			{
				const CString& skinFileName = astrSkinFiles.GetAt(f);
				CString skinBaseName;
				LPCTSTR pszSkinBaseExt = stristr(skinFileName, _T(".") EMULSKIN_BASEEXT _T(".ini"));
				if (pszSkinBaseExt)
					skinBaseName = skinFileName.Left(pszSkinBaseExt - (LPCTSTR)skinFileName);
				else
					skinBaseName = skinFileName;
				menuSkins.AppendMenu(MF_STRING, MP_SKIN_PROFILE + i, skinBaseName);
				m_astrSkinPaths.Add(thePrefs.GetMuleDirectory(EMULE_SKINDIR, false) + CString(_T("\\")) + skinFileName);
				if (!checked && currentSkin.CompareNoCase(m_astrSkinPaths[i]) == 0)
				{
					menuSkins.CheckMenuItem(MP_SKIN_PROFILE + i, MF_CHECKED);
					menuSkins.EnableMenuItem(MP_SKIN_PROFILE + i, MF_DISABLED);
					checked = true;
				}
				i++;
			}
		}
		ASSERT( i-1 == astrSkinFiles.GetCount() );
	}
	if (!checked)
	{
		menuSkins.AppendMenu(MF_STRING, MP_SKIN_PROFILE + i, currentSkin);
		menuSkins.CheckMenuItem(MP_SKIN_PROFILE + i, MF_CHECKED);
		menuSkins.EnableMenuItem(MP_SKIN_PROFILE + i, MF_DISABLED);
		m_astrSkinPaths.Add(currentSkin);
	}
	

	///////////////////////////////////////////////////////////////////////////
	// "Text Label" sub menu
	//
	CMenu menuTextLabels;
	menuTextLabels.CreateMenu();
	ASSERT( MP_NOTEXTLABELS == MP_TEXTLABELS-1 && MP_NOTEXTLABELS == MP_TEXTLABELSONRIGHT-2 );
	ASSERT( MP_NOTEXTLABELS + (int)NoLabels == MP_NOTEXTLABELS );
	ASSERT( MP_NOTEXTLABELS + (int)LabelsBelow == MP_TEXTLABELS );
	ASSERT( MP_NOTEXTLABELS + (int)LabelsRight == MP_TEXTLABELSONRIGHT );
	menuTextLabels.AppendMenu(MF_STRING | MF_ENABLED, MP_NOTEXTLABELS, GetResString(IDS_NOTEXTLABELS));
	menuTextLabels.AppendMenu(MF_STRING | MF_ENABLED, MP_TEXTLABELS, GetResString(IDS_ENABLETEXTLABELS));
	menuTextLabels.AppendMenu(MF_STRING | MF_ENABLED, MP_TEXTLABELSONRIGHT, GetResString(IDS_TEXTLABELSONRIGHT));
	menuTextLabels.CheckMenuRadioItem(MP_NOTEXTLABELS, MP_TEXTLABELSONRIGHT, MP_NOTEXTLABELS + (int)thePrefs.GetToolbarLabelSettings(), MF_BYCOMMAND);
	menuTextLabels.EnableMenuItem(MP_NOTEXTLABELS + (int)thePrefs.GetToolbarLabelSettings(), MF_BYCOMMAND | MF_DISABLED);

	menuTextLabels.AppendMenu(MF_SEPARATOR);
	menuTextLabels.AppendMenu(MF_STRING, MP_LARGEICONS, GetResString(IDS_LARGEICONS));
	menuTextLabels.AppendMenu(MF_STRING, MP_SMALLICONS, GetResString(IDS_SMALLICONS));
	ASSERT( MP_LARGEICONS == MP_SMALLICONS-1 );
	menuTextLabels.CheckMenuRadioItem(MP_LARGEICONS, MP_SMALLICONS, m_sizBtnBmp.cx == 16 ? MP_SMALLICONS : MP_LARGEICONS, MF_BYCOMMAND);
	menuTextLabels.EnableMenuItem(m_sizBtnBmp.cx == 16 ? MP_SMALLICONS : MP_LARGEICONS, MF_BYCOMMAND | MF_DISABLED);


	///////////////////////////////////////////////////////////////////////////
	// Toolbar context menu
	//
	CMenu menuToolbar;
	menuToolbar.CreatePopupMenu();
	menuToolbar.AppendMenu(MF_STRING | MF_POPUP, (UINT_PTR)menuBitmaps.m_hMenu, GetResString(IDS_TOOLBARSKINS));
	menuToolbar.AppendMenu(MF_STRING | MF_POPUP, (UINT_PTR)menuSkins.m_hMenu, GetResString(IDS_SKIN_PROF));
	menuToolbar.AppendMenu(MF_STRING | MF_POPUP, (UINT_PTR)menuTextLabels.m_hMenu, GetResString(IDS_TEXTLABELS));
	menuToolbar.AppendMenu(MF_STRING, MP_CUSTOMIZETOOLBAR, GetResString(IDS_CUSTOMIZETOOLBAR));
	CPoint point;
	GetCursorPos(&point);
	menuToolbar.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this);

	*pResult = TRUE;
}
void BacktraceNames::FromAddr( const void *p )
{
    int fds[2];
    pid_t pid;
    pid_t ppid = getpid(); /* Do this before fork()ing! */
    
    Offset = 0;
    Address = intptr_t(p);

    if (pipe(fds) != 0)
    {
        fprintf(stderr, "FromAddr pipe() failed: %s\n", strerror(errno));
        return;
    }

    pid = fork();
    if (pid == -1)
    {
        fprintf(stderr, "FromAddr fork() failed: %s\n", strerror(errno));
        return;
    }

    if (pid == 0)
    {
        close(fds[0]);
        for (int fd = 3; fd < 1024; ++fd)
            if (fd != fds[1])
                close(fd);
        dup2(fds[1], fileno(stdout));
        close(fds[1]);

        char *addy;
        asprintf(&addy, "0x%x", long(p));
        char *p;
        asprintf(&p, "%d", ppid);

        execl("/usr/bin/atos", "/usr/bin/atos", "-p", p, addy, NULL);
        
        fprintf(stderr, "execl(atos) failed: %s\n", strerror(errno));
        free(addy);
        free(p);
        _exit(1);
    }
    
    close(fds[1]);
    char f[1024];
    bzero(f, 1024);
    int len = read(fds[0], f, 1024);

    Symbol = "";
    File = "";

    if (len == -1)
    {
        fprintf(stderr, "FromAddr read() failed: %s\n", strerror(errno));
        return;
    }
    CStringArray mangledAndFile;

    split(f, " ", mangledAndFile, true);
    if (mangledAndFile.size() == 0)
        return;
    Symbol = mangledAndFile[0];
    /* eg
     * -[NSApplication run]
     * +[SomeClass initialize]
     */
    if (Symbol[0] == '-' || Symbol[0] == '+')
    {
        Symbol = mangledAndFile[0] + " " + mangledAndFile[1];
        /* eg
         * (crt.c:300)
         * (AppKit)
         */
        if (mangledAndFile.size() == 3)
        {
            File = mangledAndFile[2];
            size_t pos = File.find('(');
            size_t start = (pos == File.npos ? 0 : pos+1);
            pos = File.rfind(')') - 1;
            File = File.substr(start, pos);
        }
        return;
    }
    /* eg
     * __start   -> _start
     * _SDL_main -> SDL_main
     */
    if (Symbol[0] == '_')
        Symbol = Symbol.substr(1);
    
    /* eg, the full line:
     * __Z1Ci (in a.out) (asmtest.cc:33)
     * _main (in a.out) (asmtest.cc:52)
     */
    if (mangledAndFile.size() > 3)
    {
        File = mangledAndFile[3];
        size_t pos = File.find('(');
        size_t start = (pos == File.npos ? 0 : pos+1);
        pos = File.rfind(')') - 1;
        File = File.substr(start, pos);
    }
    /* eg, the full line:
     * _main (SDLMain.m:308)
     * __Z8GameLoopv (crt.c:300)
     */
    else if (mangledAndFile.size() == 3)
        File = mangledAndFile[2].substr(0, mangledAndFile[2].rfind(')'));
}
示例#20
0
// The inverse of EncodeSelection
//
void CDirstatDoc::DecodeSelection(CString s, CString& folder, CStringArray& drives)
{
    folder.Empty();
    drives.RemoveAll();

    // s is either something like "C:\programme"
    // or something like "C:|D:|E:".

    CStringArray sa;
    int i = 0;

    while(i < s.GetLength())
    {
        CString token;
        while(i < s.GetLength() && s[i] != GetEncodingSeparator())
        {
            token += s[i++];
        }

        token.TrimLeft();
        token.TrimRight();
        ASSERT(!token.IsEmpty());
        sa.Add(token);

        if(i < s.GetLength())
        {
            i++;
        }
    }

    ASSERT(sa.GetSize() > 0);

    if(sa.GetSize() > 1)
    {
        for(int i = 0; i < sa.GetSize(); i++)
        {
            CString d = sa[i];
            ASSERT(2 == d.GetLength());
            ASSERT(wds::chrColon == d[1]);

            drives.Add(d + _T("\\"));
        }
    }
    else
    {
        CString f = sa[0];
        if(2 == f.GetLength() && wds::chrColon == f[1])
        {
            drives.Add(f + _T("\\"));
        }
        else
        {
            // Remove trailing backslash, if any and not drive-root.
            if((f.GetLength() > 0) && (wds::strBackslash == f.Right(1)) && (f.GetLength() != 3 || f[1] != wds::chrColon))
            {
                f = f.Left(f.GetLength() - 1);
            }

            folder = f;
        }
    }
}
示例#21
0
/////////////////////////////////////////////
// CED2KFileLink implementation
/////////////////////////////////////////////
CED2KFileLink::CED2KFileLink(const TCHAR* pszName, const TCHAR* pszSize, const TCHAR* pszHash, 
							 const CStringArray& astrParams, const TCHAR* pszSources)
	: m_size(pszSize)
{
	// Here we have a little problem.. Actually the proper solution would be to decode from UTF8,
	// only if the string does contain escape sequences. But if user pastes a raw UTF8 encoded
	// string (for whatever reason), we would miss to decode that string. On the other side, 
	// always decoding UTF8 can give flaws in case the string is valid for Unicode and UTF8
	// at the same time. However, to avoid the pasting of raw UTF8 strings (which would lead
	// to a greater mess in the network) we always try to decode from UTF8, even if the string
	// did not contain escape sequences.
	m_name = OptUtf8ToStr(URLDecode(pszName));
	m_name.Trim();
	if (m_name.IsEmpty())
		throw GetResString(IDS_ERR_NOTAFILELINK);

	SourcesList = NULL;
	m_hashset = NULL;
	m_bAICHHashValid = false;

	if (_tcslen(pszHash) != 32)
		throw GetResString(IDS_ERR_ILLFORMEDHASH);

	if (_tstoi64(pszSize)>=4294967295)
		throw GetResString(IDS_ERR_TOOLARGEFILE);
	if (_tstoi64(pszSize)<=0)
		throw GetResString(IDS_ERR_NOTAFILELINK);
	
	for (int idx = 0; idx < 16; ++idx) {
		m_hash[idx] = FromHexDigit(*pszHash++)*16;
		m_hash[idx] += FromHexDigit(*pszHash++);
	}

	bool bError = false;
	for (int i = 0; !bError && i < astrParams.GetCount(); i++)
	{
		const CString& strParam = astrParams.GetAt(i);
		ASSERT( !strParam.IsEmpty() );

		CString strTok;
		int iPos = strParam.Find(_T('='));
		if (iPos != -1)
			strTok = strParam.Left(iPos);
		if (strTok == _T("s"))
		{
			CString strURL = strParam.Mid(iPos + 1);
			if (!strURL.IsEmpty())
			{
				TCHAR szScheme[INTERNET_MAX_SCHEME_LENGTH];
				TCHAR szHostName[INTERNET_MAX_HOST_NAME_LENGTH];
				TCHAR szUrlPath[INTERNET_MAX_PATH_LENGTH];
				TCHAR szUserName[INTERNET_MAX_USER_NAME_LENGTH];
				TCHAR szPassword[INTERNET_MAX_PASSWORD_LENGTH];
				TCHAR szExtraInfo[INTERNET_MAX_URL_LENGTH];
				URL_COMPONENTS Url = {0};
				Url.dwStructSize = sizeof(Url);
				Url.lpszScheme = szScheme;
				Url.dwSchemeLength = ARRSIZE(szScheme);
				Url.lpszHostName = szHostName;
				Url.dwHostNameLength = ARRSIZE(szHostName);
				Url.lpszUserName = szUserName;
				Url.dwUserNameLength = ARRSIZE(szUserName);
				Url.lpszPassword = szPassword;
				Url.dwPasswordLength = ARRSIZE(szPassword);
				Url.lpszUrlPath = szUrlPath;
				Url.dwUrlPathLength = ARRSIZE(szUrlPath);
				Url.lpszExtraInfo = szExtraInfo;
				Url.dwExtraInfoLength = ARRSIZE(szExtraInfo);
				if (InternetCrackUrl(strURL, 0, 0, &Url) && Url.dwHostNameLength > 0)
				{
					SUnresolvedHostname* hostname = new SUnresolvedHostname;
					hostname->strURL = strURL;
					hostname->strHostname = szHostName;
					m_HostnameSourcesList.AddTail(hostname);
				}
			}
			else
				ASSERT(0);
		}
		else if (strTok == _T("p"))
		{
			CString strPartHashs = strParam.Tokenize(_T("="), iPos);

			if (m_hashset != NULL){
				ASSERT(0);
				bError = true;
				break;
			}

			m_hashset = new CSafeMemFile(256);
			m_hashset->WriteHash16(m_hash);
			m_hashset->WriteUInt16(0);

			int iPartHashs = 0;
			int iPosPH = 0;
			CString strHash = strPartHashs.Tokenize(_T(":"), iPosPH);
			while (!strHash.IsEmpty())
			{
				uchar aucPartHash[16];
				if (!strmd4(strHash, aucPartHash)){
					bError = true;
					break;
				}
				m_hashset->WriteHash16(aucPartHash);
				iPartHashs++;
				strHash = strPartHashs.Tokenize(_T(":"), iPosPH);
			}
			if (bError)
				break;

			m_hashset->Seek(16, CFile::begin);
			m_hashset->WriteUInt16(iPartHashs);
			m_hashset->Seek(0, CFile::begin);
		}
		else if (strTok == _T("h"))
		{
			CString strHash = strParam.Mid(iPos + 1);
			if (!strHash.IsEmpty())
			{
				if (DecodeBase32(strHash, m_AICHHash.GetRawHash(), CAICHHash::GetHashSize()) == CAICHHash::GetHashSize()){
					m_bAICHHashValid = true;
					ASSERT( m_AICHHash.GetString().CompareNoCase(strHash) == 0 );
				}
				else
					ASSERT( false );
			}
			else
				ASSERT( false );
		}
		else
			ASSERT(0);
	}

	if (bError)
	{
		delete m_hashset;
		m_hashset = NULL;
	}

	if (pszSources)
	{
		TCHAR* pNewString = _tcsdup(pszSources);
		autoFree liberator(pNewString);
		TCHAR* pCh = pNewString;
		TCHAR* pEnd;
		TCHAR* pIP;
		TCHAR* pPort;

		bool bAllowSources;
		TCHAR date[3];
		COleDateTime expirationDate;
		int nYear,nMonth,nDay;

		uint16 nCount = 0;
		uint32 dwID;
		uint16 nPort;
		uint32 dwServerIP = 0; 
		uint16 nServerPort = 0;
		unsigned long ul;

		int nInvalid = 0;

		pCh = _tcsstr( pCh, _T("sources") );
		if( pCh != NULL ) {
			pCh = pCh + 7; // point to char after "sources"
			pEnd = pCh;
			while( *pEnd ) pEnd++; // make pEnd point to the terminating NULL
			bAllowSources=true;
			// if there's an expiration date...
			if( *pCh == _T('@') && (pEnd-pCh) > 7 )
			{
				pCh++; // after '@'
				date[2] = 0; // terminate the two character string
				date[0] = *(pCh++); date[1] = *(pCh++);
				nYear = _tcstol( date, 0, 10 ) + 2000;
				date[0] = *(pCh++); date[1] = *(pCh++);
				nMonth = _tcstol( date, 0, 10 );
				date[0] = *(pCh++); date[1] = *(pCh++);
				nDay = _tcstol( date, 0, 10 );
				bAllowSources = ( expirationDate.SetDate(nYear,nMonth,nDay) == 0 );
				if (bAllowSources) bAllowSources=(COleDateTime::GetCurrentTime() < expirationDate);
			}

			// increment pCh to point to the first "ip:port" and check for sources
			if ( bAllowSources && ++pCh < pEnd ) {
				SourcesList = new CSafeMemFile(256);
				SourcesList->WriteUInt16(nCount); // init to 0, we'll fix this at the end.
				// for each "ip:port" source string until the end
				// limit to prevent overflow (uint16 due to CPartFile::AddClientSources)
				while( *pCh != 0 && nCount < MAXSHORT ) {
					pIP = pCh;
					// find the end of this ip:port string & start of next ip:port string.
					if( (pCh = _tcschr(pCh, _T(','))) != NULL ) {
						*pCh = 0; // terminate current "ip:port"
						pCh++; // point to next "ip:port"
					}
					else
						pCh = pEnd;

					// if port is not present for this ip, go to the next ip.
					if( (pPort = _tcschr(pIP, _T(':'))) == NULL )
					{	nInvalid++;	continue;	}

					*pPort = 0;	// terminate ip string
					pPort++;	// point pPort to port string.

					dwID = inet_addr(CStringA(pIP));
					ul = _tcstoul( pPort, 0, 10 );
					nPort = static_cast<uint16>(ul);

					// skip bad ips / ports
					if (ul > 0xFFFF || ul == 0 )	// port
					{	nInvalid++;	continue;	}
					if( dwID == INADDR_NONE) {	// hostname?
						if (_tcslen(pIP) > 512)
						{	nInvalid++;	continue;	}
						SUnresolvedHostname* hostname = new SUnresolvedHostname;
						hostname->nPort = nPort;
						hostname->strHostname = pIP;
						m_HostnameSourcesList.AddTail(hostname);
						continue;
					}
					//TODO: This will filter out *.*.*.0 clients. Is there a nice way to fix?
					if( IsLowID(dwID) )	// ip
					{	nInvalid++;	continue;	}

					SourcesList->WriteUInt32(dwID);
					SourcesList->WriteUInt16(nPort);
					SourcesList->WriteUInt32(dwServerIP);
					SourcesList->WriteUInt16(nServerPort);
					nCount++;
				}
				SourcesList->SeekToBegin();
				SourcesList->WriteUInt16(nCount);
				SourcesList->SeekToBegin();
				if (nCount==0) {
					delete SourcesList;
					SourcesList=NULL;
				}
			}
		}
	}
}
void CClyEditListCtrl::FillHeaderCtrl(CClyHostDoc *pDoc)
{
	
	int i =0;
	int iStrLen = 0;
	HRESULT hr= S_OK;
	_variant_t  str;
	CStringArray ColNameArray;
	BeginWaitCursor() ;
	try
	{ 
		_RecordsetPtr Rs ;
		CString strSQL;
		Rs.CreateInstance("ADODB.Recordset");
		strSQL = _T("select * from 测硫仪实验数据");
		if(Rs->State==adStateOpen)
			Rs->Close();
		//IADORecordBindingPtr pIRB(pRsIED);
		hr = Rs->Open(strSQL.AllocSysString(),
			theApp.pConn.GetInterfacePtr(),
			adOpenStatic,
			adLockOptimistic,
			-1);	
		TESTHR(hr);
		//得到所有字段名称
		GetAllFieldName(Rs,&ColNameArray);
  
		SetRedraw(FALSE);
		//清除所有数据

		DeleteAllItems();
		//清除所有标题
		do
		{
			DeleteColumn(0);
		}
		while(GetHeaderCtrl()->GetItemCount()>0); 
		//写字段标题
		for(i=ColNameArray.GetSize()-1;i>=0;i--)
		{
			CDC *pDC = GetDC();
			iStrLen	= pDC->GetTextExtent(ColNameArray.GetAt(i)).cx*1.5;				
			InsertColumn(0,ColNameArray.GetAt(i),LVCFMT_CENTER,iStrLen ,-1);
			ReleaseDC(pDC);	
		}  
		///////////////////////////////////
		/*
		LONG RecordCount = 0;
		RecordCount = Rs->GetRecordCount();
		SetItemCount(RecordCount);

		if(RecordCount>0)
		{
			if(!Rs->adoEOF)
				Rs->MoveLast();

			while(!Rs->BOF)
			{		
				for(i=0;i<Rs->Fields->Count;i++)
				{
					str = Rs->GetCollect((_bstr_t)ColNameArray.GetAt(i));
					if(i==0)
						InsertItem(0,VariantToStr(str));
					else
						SetItemText(0,i,VariantToStr(str));
				}
				Rs->MovePrevious();
			}  
			Rs->MoveFirst();
		}
		*/
		//////////////////////////////////////
		SetRedraw(TRUE);  
	}
	catch(_com_error &e)
	{
		dump_com_error(e);
	}
	EndWaitCursor();
	
}
示例#23
0
文件: DLsyn.cpp 项目: DLive/npadBook
bool CDLsyn::upFileToLoc(CStringArray &data){
	CConndb db;
	CString gsql;
	CString key;
	for(int j=0;j<data.GetCount();j++){
		key+=data.GetAt(j);
		key+=_T(",");
	}
	key.Delete(key.GetLength()-1,1);
	gsql.Format(_T("select uniquetag from articles where id IN(%s)"),key);
	db.search(gsql);
	if(db.m_query->eof())
	{
		return false;
	}
	int i=0;
	CString uniquetag,uniquetags;
	_variant_t var;
	while(!db.m_query->eof())
	{
		var=db.m_query->getStringField(_T("uniquetag"));
		if(var.vt!=VT_NULL)
			uniquetag=(LPCSTR)_bstr_t(var);
		uniquetags+=_T("'");
		uniquetags+=uniquetag;
		uniquetags+=_T("',");
		db.m_query->nextRow();
	}
	uniquetags.Delete(uniquetags.GetLength()-1,1);
	CString strFormData=_T("ac=upsome&uniques=");
	strFormData+=uniquetags;
	char *tmpdata=unicodeToUtf8(strFormData.GetBuffer());
	BOOL result = m_pFile->SendRequest(m_strHeaders,(LPVOID)tmpdata,strlen(tmpdata));
	if(result == FALSE) return false;
	
	free(tmpdata);
	DWORD dwRet;
	m_pFile->QueryInfoStatusCode(dwRet);
	//返回错误没处理! 哈哈
	CStringA m_strHtml="";
	char szBuff[1024];
	UINT nRead;
	while ((nRead = m_pFile->Read(szBuff,1024))>0)
	{
		m_strHtml+=CStringA(szBuff,nRead);
		memset(szBuff,'\0',1024);
	}
	char *retdata=m_strHtml.GetBuffer();//UTF8ToUnicode(m_strHtml.GetBuffer());//"[{\"term_id\":\"1\",\"name\":\"\u672a\u5206\u7c7b\"},{\"term_id\":\"4\",\"name\":\"\u7f51\u7edc\u5b89\u5168\"}]";//unicodeToUtf8(m_strHtml.GetBuffer());
	Json::Reader reader; 
	Json::Value value; 
	//reader.parse(m_strHtml.GetBuffer(), value);
	if(reader.parse(retdata, value)) 
	{ 
		
		CString sql;
		std::string tmpvalue;
		for(int i=0; i<value.size(); i++) 
		{
			tmpvalue = value[i]["post_title"].asString(); 
			wstring titlename=UTF8ToUnicode(tmpvalue);
			tmpvalue = value[i]["post_content"].asString(); 
			CString contenttext=UTF8ToUnicode(tmpvalue).c_str();
			//tmpvalue = value[i]["name"].asString(); 
			//wstring rclassid=UTF8ToUnicode(tmpvalue);
			//tmpvalue = value[i]["name"].asString(); 
			//wstring data=UTF8ToUnicode(tmpvalue);
			tmpvalue = value[i]["uniquetag"].asString(); 
			wstring uniquetag=UTF8ToUnicode(tmpvalue);
			tmpvalue = value[i]["post_date"].asString(); 
			wstring post_date=UTF8ToUnicode(tmpvalue);
			//tmpvalue = value[i]["name"].asString(); 
			//wstring artype=UTF8ToUnicode(tmpvalue);
			//tmpvalue = value[i]["name"].asString(); 
			//wstring m_keyword=UTF8ToUnicode(tmpvalue);
			contenttext.Replace(_T("'"),_T("''"));

			sql.Format(_T("update articles set title='%s',content='%s',addtime='%s' where uniquetag=%s"),
				titlename.c_str(),contenttext.GetBuffer(),post_date.c_str(),uniquetag.c_str());
			db.excuteSql(sql);
		} 
	} 

	if (dwRet == HTTP_STATUS_OK)
	{
		return true;
	}
	return true;
}
示例#24
0
void CSListView::ExportList( CListExportDlg * pDlg )
{
	ASSERT( pDlg );
	if( NULL == pDlg )
		return;

	int	nColumnCount	=	m_Grid.GetColumnCount();
	ASSERT( nColumnCount > 0 );
	if( nColumnCount <= 0 )
		return;

	CStockContainer & container = AfxGetSListStockContainer();

	// Get Current StockList Time
	DWORD	dwDate;
	CSPTime	sptime;
	CSPTime	time;
	if( container.GetCurrentType( NULL, NULL, &dwDate )
		&& (-1 != dwDate || container.GetLatestTechDate(&dwDate))
		&& sptime.FromStockTimeDay( dwDate ) )
		time	=	CSPTime( sptime.GetTime() );

	// Set Column
	CStringArray	astrColumn;
	CUIntArray		anWidth;
	CUIntArray		anParams;
	for(int nCol = 0; nCol < nColumnCount; nCol ++ )
	{
		astrColumn.Add( m_Grid.GetItemText(0,nCol) );
		anWidth.Add( m_Grid.GetColumnWidth(nCol) );
		anParams.Add( m_Grid.GetItemData(0,nCol) );
	}
	if( ! pDlg->ExportBegin( astrColumn, anWidth, TRUE )
		|| ! pDlg->ExportOpenTable( time, TRUE ) )
		return;

	container.Lock();

	// set Item
	int	nCount = 0, nTotalCount = 0;
	if( pDlg->m_bItemAll )
	{
		nTotalCount	=	m_Grid.GetRowCount()-1;
		pDlg->SetProgressRange( 0, nTotalCount );
		for( int nRow=1; nRow<m_Grid.GetRowCount(); nRow++ )
		{
			CStringArray	astrItemText;
			astrItemText.SetSize( 0, nColumnCount+1 );
			LPARAM	id	=	m_Grid.GetItemData(nRow,0);
			CStockInfo & info	=	container.GetStockInfoByID(id);
			for(nCol=0; nCol<anParams.GetSize(); nCol++ )
			{
				astrItemText.Add( m_Grid.GetItemText( nRow, nCol ) );
			}
			pDlg->ExportAddItem( astrItemText );

			nCount	++;
			pDlg->SetProgress( nCount );
		}
	}
	else if( pDlg->m_bItemSelected )
	{
		nTotalCount	=	m_Grid.GetSelectedCount();
		pDlg->SetProgressRange( 0, nTotalCount );
		for( int nRow=1; nRow<m_Grid.GetRowCount(); nRow++ )
		{
			BOOL	bSelected	=	FALSE;
			for( nCol=0; nCol<m_Grid.GetColumnCount(); nCol ++ )
				bSelected	|=	( m_Grid.GetItemState(nRow,nCol) & GVIS_SELECTED );
			if( !bSelected )
				continue;

			CStringArray	astrItemText;
			astrItemText.SetSize( 0, nColumnCount+1 );
			LPARAM	id	=	m_Grid.GetItemData(nRow,0);
			CStockInfo & info	=	container.GetStockInfoByID(id);
			for(nCol=0; nCol<anParams.GetSize(); nCol++ )
			{
				astrItemText.Add( m_Grid.GetItemText( nRow, nCol ) );
			}
			pDlg->ExportAddItem( astrItemText );

			nCount	++;
			pDlg->SetProgress( nCount );
		}
	}
	else if( pDlg->m_bItemDefine )
	{
		nTotalCount	=	min(m_Grid.GetRowCount()-1,pDlg->m_nItemEnd) - max(1,pDlg->m_nItemBegin) + 1;
		pDlg->SetProgressRange( 0, nTotalCount );
		for( int nRow=max(1,pDlg->m_nItemBegin); nRow<=min(m_Grid.GetRowCount()-1,pDlg->m_nItemEnd); nRow++ )
		{
			CStringArray	astrItemText;
			astrItemText.SetSize( 0, nColumnCount+1 );
			LPARAM	id	=	m_Grid.GetItemData(nRow,0);
			CStockInfo & info	=	container.GetStockInfoByID(id);
			for(nCol=0; nCol<anParams.GetSize(); nCol++ )
			{
				astrItemText.Add( m_Grid.GetItemText( nRow, nCol ) );
			}
			pDlg->ExportAddItem( astrItemText );

			nCount	++;
			pDlg->SetProgress( nCount );
		}
	}

	container.UnLock();

	pDlg->ExportFinish( );
}
BOOL CSD3DDrawingColorCheck::DoAction(void *pData, const CheckData &checkData)
{
	pData;
	CStringArray arrCheckRule;
	double dRed;
	double dGreen;
	double dBlue;
	arrCheckRule.Copy(checkData.checkRule.arrRuleContent);
	int nCount = (int)arrCheckRule.GetSize();
	if (nCount == 3)
	{
		for (int i = 0; i < 1; i++)
		{
			if (!IsNumber(arrCheckRule.GetAt(i)))
			{
				return FALSE;				
			}
			else if (!DEQUAL(_wtof(arrCheckRule.GetAt(i)), 0.0) && !IsPoistive(arrCheckRule.GetAt(i)))
			{
				return FALSE;				
			}
			else if (_wtof(arrCheckRule.GetAt(i)) > 255.0)
			{
				return FALSE;				
			}
		}
		dRed = _wtof(arrCheckRule.GetAt(0));
		dGreen = _wtof(arrCheckRule.GetAt(1));
		dBlue = _wtof(arrCheckRule.GetAt(2));
	}
	else
		return FALSE;

	ProColor color;
	color.value.map.red = dRed/255;
	color.value.map.green = dGreen/255;
	color.value.map.blue = dBlue/255;
	color.method = PRO_COLOR_METHOD_RGB;

	ProModelitem item;
	BOOL bSetError = FALSE;
	for (int i=0, nType=-1; i <checkData.checkResult.arrErrorItems.GetCount(); i++)
	{
		ProTextStyle pTextStyle;
		item.id = checkData.checkResult.arrErrorItems[i].nID;
		item.owner = checkData.checkResult.arrErrorItems[i].pOwner;
		nType = checkData.checkResult.arrErrorItems[i].nType;

		if (PRO_NOTE == nType)	// 注解
		{
			item.type = PRO_NOTE;
			ProNoteTextStyleGet(&item, &pTextStyle);
			ProTextStyleColorSet(pTextStyle, &color);
			if (ProNoteTextStyleSet(&item, pTextStyle) != PRO_TK_NO_ERROR)
				bSetError = TRUE;
		}
		else if (PRO_DIMENSION == nType)	// 尺寸
		{
			item.type = PRO_DIMENSION;
			ProDimensionTextstyleGet(&item, &pTextStyle);
			ProTextStyleColorSet(pTextStyle, &color);
			if (ProDimensionTextstyleSet(&item, pTextStyle) != PRO_TK_NO_ERROR)
				bSetError = TRUE;
			ProDimensionDisplayUpdate(&item);
		}
		else if (PRO_REF_DIMENSION == nType)	// 参考尺寸
		{
			item.type = PRO_REF_DIMENSION;
			ProDimensionTextstyleGet(&item, &pTextStyle);
			ProTextStyleColorSet(pTextStyle, &color);
			if (ProDimensionTextstyleSet(&item, pTextStyle) != PRO_TK_NO_ERROR)
				bSetError = TRUE;
			ProDimensionDisplayUpdate(&item);
		}
		else if (PRO_GTOL == nType)		// 几何公差
		{
			item.type = PRO_GTOL;
			ProGtolTextstyleGet(&item, &pTextStyle);
			ProTextStyleColorSet(pTextStyle, &color);
			if (ProGtolTextstyleSet(&item, pTextStyle) != PRO_TK_NO_ERROR)
				bSetError = TRUE;
			ProAnnotationDisplay(&item, NULL, NULL, NULL);
		}
		else if (PRO_SYMBOL_INSTANCE == nType)	// 符号
		{
			item.type = PRO_SYMBOL_INSTANCE;
			ProDtlsyminstdata pdtldata = NULL;
			ProDtlsyminstDataGet(&item, PRODISPMODE_NUMERIC, &pdtldata);
			ProDtlsyminstdataColorSet(pdtldata, &color);
			if (ProDtlsyminstModify(&item, pdtldata) != PRO_TK_NO_ERROR)
				bSetError = TRUE;
			ProAnnotationDisplay(&item, NULL, NULL, NULL);
		}
		else if (PRO_SURF_FIN == nType)	// 表面光洁度
		{
			item.type = PRO_SURF_FIN;
			ProDtlsyminstdata pdtldata = NULL;
			ProSurffinishDataGet(&item, PRODISPMODE_NUMERIC, &pdtldata);
			ProDtlsyminstdataColorSet(pdtldata, &color);
			if (ProSurffinishModify(&item, pdtldata) != PRO_TK_NO_ERROR)
				bSetError = TRUE;
			ProAnnotationDisplay(&item, NULL, NULL, NULL);
		}
		else if (PRO_SET_DATUM_TAG == nType)	// 基准标签
		{
			item.type = PRO_SET_DATUM_TAG;
			ProSetdatumtagTextstyleGet(&item, &pTextStyle);
			ProTextStyleColorSet(pTextStyle, &color);
			if (ProSetdatumtagTextstyleSet(&item, pTextStyle) != PRO_TK_NO_ERROR)
				bSetError = TRUE;
			ProAnnotationDisplay(&item, NULL, NULL, NULL);
		}

		ProTextStyleFree(&pTextStyle);
	}

	ProWindowRepaint(PRO_VALUE_UNUSED);

	if (bSetError)
		return FALSE;

	return TRUE;
}
示例#26
0
BOOL CDirstatDoc::OnOpenDocument(LPCTSTR lpszPathName)
{
	CDocument::OnNewDocument(); // --> DeleteContents()

	CString spec= lpszPathName;
	CString folder;
	CStringArray drives;
	DecodeSelection(spec, folder, drives);
	
	CStringArray rootFolders;
	if (drives.GetSize() > 0)
	{
		m_showMyComputer= (drives.GetSize() > 1);
		for (int i=0; i < drives.GetSize(); i++)
			rootFolders.Add(drives[i]);
	}
	else
	{
		ASSERT(!folder.IsEmpty());
		m_showMyComputer= false;
		rootFolders.Add(folder);
	}

	CArray<CItem *, CItem *> driveItems;

	if (m_showMyComputer)
	{
		m_rootItem= new CItem((ITEMTYPE)(IT_MYCOMPUTER|ITF_ROOTITEM), LoadString(IDS_MYCOMPUTER));
		for (int i=0; i < rootFolders.GetSize(); i++)
		{
			CItem *drive= new CItem(IT_DRIVE, rootFolders[i]);
			driveItems.Add(drive);
			m_rootItem->AddChild(drive);
		}
	}
	else
	{
		ITEMTYPE type= IsDrive(rootFolders[0]) ? IT_DRIVE : IT_DIRECTORY;
		m_rootItem= new CItem((ITEMTYPE)(type|ITF_ROOTITEM), rootFolders[0], false);
		if (m_rootItem->GetType() == IT_DRIVE)
			driveItems.Add(m_rootItem);
		m_rootItem->UpdateLastChange();
	}
	m_zoomItem= m_rootItem;

	for (int i=0; i < driveItems.GetSize(); i++)
	{
		if (OptionShowFreeSpace())
			driveItems[i]->CreateFreeSpaceItem();
		if (OptionShowUnknown())
			driveItems[i]->CreateUnknownItem();
	}

	SetWorkingItem(m_rootItem);

	GetMainFrame()->MinimizeGraphView();
	GetMainFrame()->MinimizeTypeView();

	UpdateAllViews(NULL, HINT_NEWROOT);
	return true;
}
CString CTemplateFormater::Format()
{
	ASSERT(!m_strSource.IsEmpty());
	CString szTmpl = CString(m_strSource);
	int iIndex, iTableSize;
	CString szKey, szText;
	int iStartPos, iNextPos;
	
	// Translate the keyword table...
	iTableSize = ARRAY_SIZE(s_KeywordTable);
	iIndex     = 0;
	// Iterate through the table
	while (iIndex < iTableSize)
	{
		// What is the keyword?
		szKey = KEYWORD_BEGIN;
		szKey += s_KeywordTable[iIndex].szKeyword;
		szKey += KEYWORD_END;
		
		// Substitute the correct value for the keyword
		szTmpl.Replace(szKey, s_KeywordTable[iIndex].Proc());
		
		// Next
		iIndex++;
	};
	
	// Translate replaceble parameters
	CStringArray ParamTable;
	
	GetReplacebleParams(ParamTable, szTmpl);
	
	iTableSize = ParamTable.GetSize();
	iIndex = 0;
	
	while (iIndex < iTableSize)
	{
		// What is the keyword?
		szKey  = PARAM_BEGIN;
		szKey += ParamTable[iIndex];
		szKey += PARAM_END;
		
		// Substitute the correct value for the keyword
		szTmpl.Replace(szKey, GetParam(ParamTable[iIndex]));
		
		// Next
		iIndex++;
	}
	
	// Translate the format specifiers
	iTableSize = ARRAY_SIZE(s_FormatSpecTable);
	iIndex     = 0;
	// Iterate through the table
	while (iIndex < iTableSize)
	{
		// What is the specifier?
		szKey = FORMAT_BEGIN;
		szKey += s_FormatSpecTable[iIndex].szSpecifier;
		iStartPos = 0;
		
		// Replace each occurrence of the specifier with
		// the new value
		while (GetNextInstance(szTmpl, szKey, iStartPos))
		{
			// Extract the enclosed text
			szText = ExtractText(szTmpl, szKey, iStartPos, iNextPos);
			
			// Replace the specifier and enclosed text with the
			// updated version
			szTmpl = ReplaceSpecifier(szTmpl, iStartPos, iNextPos,
				s_FormatSpecTable[iIndex].Proc(szText));
			
			iStartPos = iNextPos;
		};
		
		// Next
		iIndex++;
	};
	
	return (szTmpl);
}
/******************************************************************************
  Function Name    :  OnBnClickedCbtnDissociate

  Input(s)         :
  Output           :
  Functionality    :  Call the functions to remove the selected Databases
  Member of        :  CDatabaseDissociateDlg
  Friend of        :      -

  Author(s)        :  Anish Kumar
  Date Created     :  06.12.2006
  Modifications    :
******************************************************************************/
void CDatabaseDissociateDlg::OnBnClickedCbtnDissociate()
{
    //TO store the path of files dissociated
    CStringArray aomStrFilesDissociated;
    CMainFrame* pMainFrame = static_cast<CMainFrame*> (theApp.m_pMainWnd);
    // Get the indexes of all the selected items.
    int nCount = m_omDissociateDbLst.GetSelCount();

    if ( nullptr == pMainFrame )
    {
        return;
    }
    if(nCount > 0)
    {
        // Array of selected item's position
        CArray<int,int> aomListBoxSel;
        aomListBoxSel.SetSize(nCount);
        //Pass the array pointer to get the selected item's positions
        m_omDissociateDbLst.GetSelItems(nCount, aomListBoxSel.GetData());
        aomStrFilesDissociated.RemoveAll();

        for(int nTempCnt = 0 ; nTempCnt < nCount ; nTempCnt++)
        {
            BOOL bDBDeleted = FALSE;
            CString omstrDBPath ;
            //Selected file's index
            int nSelectedPos = aomListBoxSel.GetAt(nTempCnt);
            //Find the length of string to pass the buffer to have the selected File path
            int nBufferSize = m_omDissociateDbLst.GetTextLen(nSelectedPos);
            m_omDissociateDbLst.GetText(nSelectedPos,omstrDBPath.GetBuffer(nBufferSize));
            bDBDeleted = (*(CMsgSignal**)(m_sDbParams.m_ppvImportedDBs))->bDeAllocateMemory(omstrDBPath.GetBuffer(0));

            if(TRUE == bDBDeleted)
            {
                aomStrFilesDissociated.Add(omstrDBPath.GetBuffer(0));
            }
        }

        //To remove from theApp class
        CStringArray aomstrDBFiles;
        (*(CMsgSignal**)(m_sDbParams.m_ppvImportedDBs))->vGetDataBaseNames(&aomstrDBFiles);
        //Delete the file path from the List box
        int nTotalCount = aomStrFilesDissociated.GetSize();
        CString omStrTempFile;

        for(int nCount=0 ; nCount<nTotalCount ; nCount++)
        {
            omStrTempFile = aomStrFilesDissociated.GetAt(nCount);
            int nIndex = 0;

            if( (nIndex = m_omDissociateDbLst.FindString(0,
                          omStrTempFile)) != LB_ERR )
            {
                //Delete the file path from the list box
                m_omDissociateDbLst.DeleteString(nIndex);
                int nStoredFile = aomstrDBFiles.GetSize();
                CString omStrTemp;
                BOOL bRemoved = FALSE;

                for(int nTemp = 0 ; nTemp < nStoredFile && bRemoved != TRUE; nTemp++)
                {
                    omStrTemp = aomstrDBFiles.GetAt(nTemp);

                    if(!(omStrTemp.Compare(omStrTempFile)))
                    {
                        aomstrDBFiles.RemoveAt(nTemp);
                        bRemoved = TRUE;
                    }
                }
            }
        }

        //Set the new file name array
        (*(CMsgSignal**)(m_sDbParams.m_ppvImportedDBs))->vSetDataBaseNames(&aomstrDBFiles);
        // Send a message to Tx Window about database change
        if( pMainFrame != nullptr)
        {
            eUSERSELCTION eUserSel = eDATABASEIMPORTCMD;
            pMainFrame->m_objTxHandler.vPostMessageToTxWnd(WM_USER_CMD, (WPARAM)eUserSel,0);
        }
        ////Delete Signal watch list and Graph window list
        //// Check for Signal Watch & DLL load Condition
        //
        BOOL bUserOption = FALSE;
        if(pMainFrame->m_psSignalWatchList != nullptr)
        {
            if(theApp.m_bFromAutomation == FALSE)
                bUserOption = AfxMessageBox(_(defIMPORT_WARNING),
                                            MB_YESNO | MB_DEFBUTTON1 | MB_ICONQUESTION) ==
                              IDYES;
            // If user wants to clear
            if(bUserOption == TRUE )
            {
                // Clear Signal Watch List
                pMainFrame->vUpdateSWList();
            }
        }
        //Added by Arun to update Data Handler Main entry list.
        pMainFrame->vUpdateMainEntryListInWaveDataHandler();
        pMainFrame->vClearSignalInfoList();
        if(!pMainFrame->m_ouWaveTransmitter.bIsBlockEnabled())
        {
            theApp.pouGetFlagsPtr()->vSetFlagStatus( SEND_SIGNAL_MSG, FALSE );
        }

        //Update Message windows
        pMainFrame->vUpdateAllMsgWndInterpretStatus(m_sDbParams.m_eBus, FALSE);

        // Check for Graph list
        for(register int nBusID = CAN; nBusID < AVAILABLE_PROTOCOLS; nBusID++)
        {
            if( pMainFrame->m_odGraphList[nBusID].m_omElementList.GetSize() > 0 )
            {
                // Get the delete confirmation from the user
                if(theApp.m_bFromAutomation == FALSE)
                    bUserOption = AfxMessageBox(_(defIMPORT_WARNING_GRAPH),
                                                MB_YESNO | MB_DEFBUTTON1 | MB_ICONQUESTION) ==
                                  IDYES;

                // If user wants to clear
                if(bUserOption == TRUE )
                {
                    // Clear Graph List for all buses.
                    for(register int nID = CAN; nID < AVAILABLE_PROTOCOLS; nID++)
                    {
                        pMainFrame->m_odGraphList[nID].m_omElementList.RemoveAll();
                    }

                    // Send the Message to the Left View to Update List for all buses
                    if( pMainFrame != nullptr )
                    {
                        pMainFrame->vPostConfigChangeCmdToSigGrphWnds(FALSE);
                    }
                }
                break;
            }
        }
    }
}
示例#29
0
bool KSFLoader::LoadFromKSFFile( const CString &sPath, Steps &out, const Song &song )
{
    LOG->Trace( "Steps::LoadFromKSFFile( '%s' )", sPath.c_str() );

    MsdFile msd;
    if( !msd.ReadFile( sPath ) )
        RageException::Throw( "Error opening file '%s'.", sPath.c_str() );

    int iTickCount = -1;	// this is the value we read for TICKCOUNT
    CStringArray asRows;

    for( unsigned i=0; i<msd.GetNumValues(); i++ )
    {
        const MsdFile::value_t &sParams = msd.GetValue(i);
        CString sValueName = sParams[0];

        // handle the data
        if( 0==stricmp(sValueName,"TICKCOUNT") )
            iTickCount = atoi(sParams[1]);

        else if( 0==stricmp(sValueName,"STEP") )
        {
            CString step = sParams[1];
            TrimLeft(step);
            split( step, "\n", asRows, true );
        }
        else if( 0==stricmp(sValueName,"DIFFICULTY") )
            out.SetMeter(atoi(sParams[1]));
    }

    if( iTickCount == -1 )
    {
        iTickCount = 2;
        LOG->Warn( "\"%s\": TICKCOUNT not found; defaulting to %i", sPath.c_str(), iTickCount );
    }

    NoteData notedata;	// read it into here

    {
        CString sDir, sFName, sExt;
        splitpath( sPath, sDir, sFName, sExt );
        sFName.MakeLower();

        out.SetDescription(sFName);
        if( sFName.Find("crazy")!=-1 )
        {
            out.SetDifficulty(DIFFICULTY_HARD);
            if(!out.GetMeter()) out.SetMeter(8);
        }
        else if( sFName.Find("hard")!=-1 )
        {
            out.SetDifficulty(DIFFICULTY_MEDIUM);
            if(!out.GetMeter()) out.SetMeter(5);
        }
        else if( sFName.Find("easy")!=-1 )
        {
            out.SetDifficulty(DIFFICULTY_EASY);
            if(!out.GetMeter()) out.SetMeter(2);
        }
        else
        {
            out.SetDifficulty(DIFFICULTY_MEDIUM);
            if(!out.GetMeter()) out.SetMeter(5);
        }

        notedata.SetNumTracks( 5 );
        out.m_StepsType = STEPS_TYPE_PUMP_SINGLE;

        /* Check for "halfdouble" before "double". */
        if( sFName.Find("halfdouble") != -1 || sFName.Find("h_double") != -1 )
        {
            notedata.SetNumTracks( 6 );
            out.m_StepsType = STEPS_TYPE_PUMP_HALFDOUBLE;
        }
        else if( sFName.Find("double") != -1 )
        {
            notedata.SetNumTracks( 10 );
            out.m_StepsType = STEPS_TYPE_PUMP_DOUBLE;
        }
        else if( sFName.Find("_2") != -1 )
        {
            notedata.SetNumTracks( 10 );
            out.m_StepsType = STEPS_TYPE_PUMP_COUPLE;
        }
    }

    int iHoldStartRow[13];
    int t;
    for( t=0; t<13; t++ )
        iHoldStartRow[t] = -1;

    for( unsigned r=0; r<asRows.size(); r++ )
    {
        CString& sRowString = asRows[r];
        StripCrnl( sRowString );

        if( sRowString == "" )
            continue;	// skip

        /* All 2s indicates the end of the song. */
        if( sRowString == "2222222222222" )
            break;

        if(sRowString.size() != 13)
        {
            LOG->Warn("File %s had a RowString with an improper length (\"%s\"); corrupt notes ignored",
                      sPath.c_str(), sRowString.c_str());
            return false;
        }

        /* Half-doubles is offset; "0011111100000". */
        if( out.m_StepsType == STEPS_TYPE_PUMP_HALFDOUBLE )
            sRowString.erase( 0, 2 );

        // the length of a note in a row depends on TICKCOUNT
        float fBeatThisRow = r/(float)iTickCount;
        int row = BeatToNoteRow(fBeatThisRow);
        for( int t=0; t < notedata.GetNumTracks(); t++ )
        {
            if( sRowString[t] == '4' )
            {
                /* Remember when each hold starts; ignore the middle. */
                if( iHoldStartRow[t] == -1 )
                    iHoldStartRow[t] = r;

                continue;
            }

            if( iHoldStartRow[t] != -1 )	// this ends the hold
            {
                HoldNote hn (
                    t, /* button */
                    BeatToNoteRow(iHoldStartRow[t]/(float)iTickCount), /* start */
                    BeatToNoteRow((r-1)/(float)iTickCount) /* end */
                );
                notedata.AddHoldNote( hn );
                iHoldStartRow[t] = -1;
            }

            TapNote tap;
            switch(sRowString[t])
            {
            case '0':
                tap = TAP_EMPTY;
                break;
            case '1':
                tap = TAP_ORIGINAL_TAP;
                break;
            default:
                ASSERT(0);
                tap = TAP_EMPTY;
                break;
            }

            notedata.SetTapNote(t, row, tap);
        }
    }

    /* We need to remove holes where the BPM increases. */
//	if( song.m_Timing.m_BPMSegments.size() > 1 )
//		RemoveHoles( notedata, song );

    out.SetNoteData(&notedata);

    out.TidyUpData();

    return true;
}
示例#30
0
BOOL COXEventLog::DeleteApplicationLog(LPCTSTR pszApplicationName)
{
	ASSERT_VALID(this);
	ASSERT(pszApplicationName != NULL);

	if (pszApplicationName == NULL || 
		lstrlen(pszApplicationName) <= 0)
	{
		m_ErrorCode = ERROR_INVALID_PARAMETER;
		return(FALSE);
	}

	COXRegistryItem regItem;
	CString log_key_name(_T("\\LocalMachine\\SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\"));
	log_key_name += pszApplicationName;
	log_key_name += _T("\\");
	regItem.SetFullRegistryItem(log_key_name);
	if (regItem.Delete() == FALSE)
	{
		m_ErrorCode = regItem.GetLastError();
		return FALSE;
	}

	/*
	** Microsoft has a bug in this area. Even though we deleted the application from the
	** HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Application\
	** registry area, they don't provide a way to delete the application from the 
	** HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Application\Sources
	** value. The application name is one of the strings in this REG_MULTI_SZ value. We
	** still need to delete it from there. The names listed in this value appear in the 
	** "Source" combobox of the Event Viewer application View->Filter Events... menu selection.
	*/

	log_key_name = _T("\\LocalMachine\\SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\");
	regItem.SetFullRegistryItem(log_key_name);
	CStringArray sources;
	if (regItem.Open(FALSE) == FALSE ||
		regItem.GetMultiStringValue(sources, _T("Sources")) == FALSE)
	{
		m_ErrorCode = regItem.GetLastError();
		return FALSE;
	}
	
	int index = 0;
	int number_of_sources = PtrToInt(sources.GetSize());
	BOOL application_was_found = FALSE;
	while(index < number_of_sources)
	{
		if (sources[index] == pszApplicationName)
		{
			application_was_found = TRUE;
			sources.RemoveAt(index);
			index = number_of_sources;
		}

		index++;
	}
	if (application_was_found != FALSE)
	{
		regItem.SetMultiStringValue(sources, _T("Sources"));
	}

	return TRUE;
}