Пример #1
0
/*************************************************************************
 * SHFree					[SHELL32.195]
 *
 * Equivalent to CoTaskMemFree. Under Windows 9x this function could use
 * the shell32 built-in "mini-COM" without the need to load ole32.dll -
 * see SHLoadOLE for details. 
 *
 * NOTES
 *     exported by ordinal
 *
 * SEE ALSO
 *     CoTaskMemFree, SHLoadOLE
 */
void WINAPI SHFree(LPVOID pv)
{
	TRACE("%p\n",pv);
	CoTaskMemFree(pv);
}
Пример #2
0
static void DEVENUM_ReadPinTypes(HKEY hkeyPinKey, REGFILTERPINS *rgPin)
{
    HKEY hkeyTypes = NULL;
    DWORD dwMajorTypes, i;
    REGPINTYPES *lpMediaType = NULL;
    DWORD dwMediaTypeSize = 0;

    if (RegOpenKeyExW(hkeyPinKey, wszTypes, 0, KEY_READ, &hkeyTypes) != ERROR_SUCCESS)
        return ;

    if (RegQueryInfoKeyW(hkeyTypes, NULL, NULL, NULL, &dwMajorTypes, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
                != ERROR_SUCCESS)
    {
        RegCloseKey(hkeyTypes);
        return ;
    }

    for (i = 0; i < dwMajorTypes; i++)
    {
        HKEY hkeyMajorType = NULL;
        WCHAR wszMajorTypeName[64];
        DWORD cName = sizeof(wszMajorTypeName) / sizeof(WCHAR);
        DWORD dwMinorTypes, i1;

        if (RegEnumKeyExW(hkeyTypes, i, wszMajorTypeName, &cName, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) continue;

        if (RegOpenKeyExW(hkeyTypes, wszMajorTypeName, 0, KEY_READ, &hkeyMajorType) != ERROR_SUCCESS) continue;

        if (RegQueryInfoKeyW(hkeyMajorType, NULL, NULL, NULL, &dwMinorTypes, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
                    != ERROR_SUCCESS)
        {
            RegCloseKey(hkeyMajorType);
            continue;
        }

        for (i1 = 0; i1 < dwMinorTypes; i1++)
        {
            WCHAR wszMinorTypeName[64];
            CLSID *clsMajorType = NULL, *clsMinorType = NULL;
            HRESULT hr;

            cName = sizeof(wszMinorTypeName) / sizeof(WCHAR);
            if (RegEnumKeyExW(hkeyMajorType, i1, wszMinorTypeName, &cName, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) continue;

            clsMinorType = CoTaskMemAlloc(sizeof(CLSID));
            if (!clsMinorType) continue;

            clsMajorType = CoTaskMemAlloc(sizeof(CLSID));
            if (!clsMajorType) goto error_cleanup_types;

            hr = CLSIDFromString(wszMinorTypeName, clsMinorType);
            if (FAILED(hr)) goto error_cleanup_types;

            hr = CLSIDFromString(wszMajorTypeName, clsMajorType);
            if (FAILED(hr)) goto error_cleanup_types;

            if (rgPin->nMediaTypes == dwMediaTypeSize)
            {
                DWORD dwNewSize = dwMediaTypeSize + (dwMediaTypeSize < 2 ? 1 : dwMediaTypeSize / 2);
                REGPINTYPES *lpNewMediaType;

                lpNewMediaType = CoTaskMemRealloc(lpMediaType, sizeof(REGPINTYPES) * dwNewSize);
                if (!lpNewMediaType) goto error_cleanup_types;

                lpMediaType = lpNewMediaType;
                dwMediaTypeSize = dwNewSize;
             }

            lpMediaType[rgPin->nMediaTypes].clsMajorType = clsMajorType;
            lpMediaType[rgPin->nMediaTypes].clsMinorType = clsMinorType;
            rgPin->nMediaTypes++;
            continue;

            error_cleanup_types:

            if (clsMajorType) CoTaskMemFree(clsMajorType);
            if (clsMinorType) CoTaskMemFree(clsMinorType);
        }

        RegCloseKey(hkeyMajorType);
    }

    RegCloseKey(hkeyTypes);

    if (lpMediaType && !rgPin->nMediaTypes)
    {
        CoTaskMemFree(lpMediaType);
        lpMediaType = NULL;
    }

    rgPin->lpMediaType = lpMediaType;
}
Пример #3
0
static HRESULT DEVENUM_RegisterLegacyAmFilters(void)
{
    HKEY hkeyFilter = NULL;
    DWORD dwFilterSubkeys, i;
    LONG lRet;
    IFilterMapper2 *pMapper = NULL;
    HRESULT hr;

    hr = CoCreateInstance(&CLSID_FilterMapper2, NULL, CLSCTX_INPROC,
                           &IID_IFilterMapper2, (void **) &pMapper);
    if (SUCCEEDED(hr))
    {
        lRet = RegOpenKeyExW(HKEY_CLASSES_ROOT, wszFilterKeyName, 0, KEY_READ, &hkeyFilter);
        hr = HRESULT_FROM_WIN32(lRet);
    }

    if (SUCCEEDED(hr))
    {
        lRet = RegQueryInfoKeyW(hkeyFilter, NULL, NULL, NULL, &dwFilterSubkeys, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
        hr = HRESULT_FROM_WIN32(lRet);
    }

    if (SUCCEEDED(hr))
    {
        for (i = 0; i < dwFilterSubkeys; i++)
        {
            WCHAR wszFilterSubkeyName[64];
            DWORD cName = sizeof(wszFilterSubkeyName) / sizeof(WCHAR);
            HKEY hkeyCategoryBaseKey;
            WCHAR wszRegKey[MAX_PATH];
            HKEY hkeyInstance = NULL;

            if (RegEnumKeyExW(hkeyFilter, i, wszFilterSubkeyName, &cName, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) continue;

            hr = DEVENUM_GetCategoryKey(&CLSID_LegacyAmFilterCategory, &hkeyCategoryBaseKey, wszRegKey, MAX_PATH);
            if (FAILED(hr)) continue;

            strcatW(wszRegKey, wszRegSeparator);
            strcatW(wszRegKey, wszFilterSubkeyName);

            if (RegOpenKeyExW(HKEY_CLASSES_ROOT, wszRegKey, 0, KEY_READ, &hkeyInstance) == ERROR_SUCCESS)
            {
                RegCloseKey(hkeyInstance);
            }
            else
            {
                /* Filter is registered the IFilterMapper(1)-way in HKCR\Filter. Needs to be added to
                 * legacy am filter category. */
                HKEY hkeyFilterClass = NULL;
                REGFILTER2 rgf2;
                CLSID clsidFilter;
                WCHAR wszFilterName[MAX_PATH];
                DWORD Type;
                DWORD cbData;
                HRESULT res;
                IMoniker *pMoniker = NULL;

                TRACE("Registering %s\n", debugstr_w(wszFilterSubkeyName));

                strcpyW(wszRegKey, clsid_keyname);
                strcatW(wszRegKey, wszRegSeparator);
                strcatW(wszRegKey, wszFilterSubkeyName);

                if (RegOpenKeyExW(HKEY_CLASSES_ROOT, wszRegKey, 0, KEY_READ, &hkeyFilterClass) != ERROR_SUCCESS)
                    continue;

                rgf2.dwVersion = 1;
                rgf2.dwMerit = 0;
                rgf2.u.s1.cPins = 0;
                rgf2.u.s1.rgPins = NULL;

                cbData = sizeof(wszFilterName);
                if (RegQueryValueExW(hkeyFilterClass, NULL, NULL, &Type, (LPBYTE)wszFilterName, &cbData) != ERROR_SUCCESS ||
                    Type != REG_SZ)
                    goto cleanup;

                cbData = sizeof(rgf2.dwMerit);
                if (RegQueryValueExW(hkeyFilterClass, wszMeritName, NULL, &Type, (LPBYTE)&rgf2.dwMerit, &cbData) != ERROR_SUCCESS ||
                    Type != REG_DWORD)
                    goto cleanup;

                DEVENUM_ReadPins(hkeyFilterClass, &rgf2);

                res = CLSIDFromString(wszFilterSubkeyName, &clsidFilter);
                if (FAILED(res)) goto cleanup;

                IFilterMapper2_RegisterFilter(pMapper, &clsidFilter, wszFilterName, &pMoniker, NULL, NULL, &rgf2);

                if (pMoniker)
                    IMoniker_Release(pMoniker);

                cleanup:

                if (hkeyFilterClass) RegCloseKey(hkeyFilterClass);

                if (rgf2.u.s1.rgPins)
                {
                    UINT iPin;

                    for (iPin = 0; iPin < rgf2.u.s1.cPins; iPin++)
                    {
                        CoTaskMemFree(rgf2.u.s1.rgPins[iPin].strName);

                        if (rgf2.u.s1.rgPins[iPin].lpMediaType)
                        {
                            UINT iType;

                            for (iType = 0; iType < rgf2.u.s1.rgPins[iPin].nMediaTypes; iType++)
                            {
                                CoTaskMemFree((void*)rgf2.u.s1.rgPins[iPin].lpMediaType[iType].clsMajorType);
                                CoTaskMemFree((void*)rgf2.u.s1.rgPins[iPin].lpMediaType[iType].clsMinorType);
                            }

                            CoTaskMemFree((void*)rgf2.u.s1.rgPins[iPin].lpMediaType);
                        }
                    }

                    CoTaskMemFree((void*)rgf2.u.s1.rgPins);
                }
            }
        }
    }

    if (hkeyFilter) RegCloseKey(hkeyFilter);

    if (pMapper)
        IFilterMapper2_Release(pMapper);

    return S_OK;
}
Пример #4
0
static void WINAPI user_free(void *p)
{
    CoTaskMemFree(p);
}
HRESULT CWIACapabilityManager::AddCapability(const GUID    guidCapability,
                                             UINT          uiNameResourceID,
                                             UINT          uiDescriptionResourceID,
                                             ULONG         ulFlags,
                                             _In_ LPWSTR   wszIcon)
{
    HRESULT hr = S_OK;

    WIA_DEV_CAP_DRV *pWIADeviceCapability = NULL;
    hr = AllocateCapability(&pWIADeviceCapability);
    if((SUCCEEDED(hr)&& (pWIADeviceCapability)))
    {
        pWIADeviceCapability->ulFlags = ulFlags;
        *pWIADeviceCapability->guid   = guidCapability;

        CBasicStringWide cswCapabilityString;

        //
        // Load capability name from resource
        //

        if(cswCapabilityString.LoadString(uiNameResourceID,m_hInstance))
        {
            hr = StringCbCopyW(pWIADeviceCapability->wszName,
                               MAX_CAPABILITY_STRING_SIZE_BYTES,
                               cswCapabilityString.String());
            if(FAILED(hr))
            {
                WIAS_ERROR((g_hInst, "Failed to copy source string (%ws) to destination string, hr = 0x%lx",cswCapabilityString.String(),hr));
            }
        }
        else
        {
            hr = E_FAIL;
            WIAS_ERROR((g_hInst, "Failed to load the device capability name string from DLL resource, hr = 0x%lx",hr));
        }

        //
        // Load capability description from resource
        //

        if(cswCapabilityString.LoadString(uiDescriptionResourceID,m_hInstance))
        {
            hr = StringCbCopyW(pWIADeviceCapability->wszDescription,
                               MAX_CAPABILITY_STRING_SIZE_BYTES,
                               cswCapabilityString.String());
            if(FAILED(hr))
            {
                WIAS_ERROR((g_hInst, "Failed to copy source string (%ws) to destination string, hr = 0x%lx",cswCapabilityString.String(),hr));
            }
        }
        else
        {
            hr = E_FAIL;
            WIAS_ERROR((g_hInst, "Failed to load the device capability description string from DLL resource, hr = 0x%lx",hr));
        }

        //
        // Copy icon location string
        //

        cswCapabilityString = wszIcon;

        if(cswCapabilityString.Length())
        {
            hr = StringCbCopyW(pWIADeviceCapability->wszIcon,
                               MAX_CAPABILITY_STRING_SIZE_BYTES,
                               cswCapabilityString.String());
            if(FAILED(hr))
            {
                WIAS_ERROR((g_hInst, "Failed to copy source string (%ws) to destination string, hr = 0x%lx",cswCapabilityString.String(),hr));
            }
        }
        else
        {
            hr = E_FAIL;
            WIAS_ERROR((g_hInst, "Failed to load the device capability icon location string from DLL resource, hr = 0x%lx",hr));
        }

        if(SUCCEEDED(hr))
        {
            if((pWIADeviceCapability->ulFlags == WIA_NOTIFICATION_EVENT) ||
               (pWIADeviceCapability->ulFlags == WIA_ACTION_EVENT))
            {
                //
                // The capability being added is an event, so always add it to the beginning of the array
                //

                m_CapabilityArray.Insert(*pWIADeviceCapability,0);
            }
            else
            {
                //
                // The capability being added is a command, so always add it to the end of the array
                //

                m_CapabilityArray.Append(*pWIADeviceCapability);
            }
        }

        if(pWIADeviceCapability)
        {
            CoTaskMemFree(pWIADeviceCapability);
            pWIADeviceCapability = NULL;
        }
    }
    return hr;
}
Пример #6
0
/**
 * Checks and retrieves credentials provided by the host + does account lookup on eventually
 * renamed user accounts.
 *
 * @return  IPRT status code.
 */
int VBoxCredProvCredential::RetrieveCredentials(void)
{
    PRTUTF16 pwszUser     = NULL;
    PRTUTF16 pwszPassword = NULL;
    PRTUTF16 pwszDomain   = NULL;

    int rc = VbglR3CredentialsQueryAvailability();
    if (RT_SUCCESS(rc))
    {
        /*
         * Set status to "terminating" to let the host know this module now
         * tries to receive and use passed credentials so that credentials from
         * the host won't be sent twice.
         */
        VBoxCredProvReportStatus(VBoxGuestFacilityStatus_Terminating);

        rc = VbglR3CredentialsRetrieveUtf16(&pwszUser, &pwszPassword, &pwszDomain);

        VBoxCredProvVerbose(0, "VBoxCredProvCredential::RetrieveCredentials: Retrieved credentials with rc=%Rrc\n", rc);
    }

    if (RT_SUCCESS(rc))
    {
        VBoxCredProvVerbose(0, "VBoxCredProvCredential::RetrieveCredentials: Received credentials for user '%ls'\n", pwszUser);

        /*
         * In case we got a "display name" (e.g. "John Doe")
         * instead of the real user name (e.g. "jdoe") we have
         * to translate the data first ...
         */
        PWSTR pwszExtractedName = NULL;
        if (   TranslateAccountName(pwszUser, &pwszExtractedName)
            && pwszExtractedName)
        {
            VBoxCredProvVerbose(0, "VBoxCredProvCredential::RetrieveCredentials: Translated account name '%ls' -> '%ls'\n",
                                pwszUser, pwszExtractedName);

            RTMemWipeThoroughly(pwszUser, (RTUtf16Len(pwszUser) + 1) * sizeof(RTUTF16), 3 /* Passes */);
            RTUtf16Free(pwszUser);

            pwszUser = RTUtf16Dup(pwszExtractedName);

            CoTaskMemFree(pwszExtractedName);
            pwszExtractedName = NULL;
        }
        else
        {
            /*
             * Okay, no display name, but maybe it's a
             * principal name from which we have to extract the domain from?
             * ([email protected] -> jdoe in domain my-domain.sub.net.com.)
             */
            PWSTR pwszExtractedDomain = NULL;
            if (ExtractAccoutData(pwszUser, &pwszExtractedName, &pwszExtractedDomain))
            {
                /* Update user name. */
                if (pwszExtractedName)
                {
                    if (pwszUser)
                    {
                        RTMemWipeThoroughly(pwszUser, (RTUtf16Len(pwszUser) + 1) * sizeof(RTUTF16), 3 /* Passes */);
                        RTUtf16Free(pwszUser);
                    }

                    pwszUser = RTUtf16Dup(pwszExtractedName);

                    CoTaskMemFree(pwszExtractedName);
                    pwszExtractedName = NULL;
                }

                /* Update domain. */
                if (pwszExtractedDomain)
                {
                    if (pwszDomain)
                    {
                        RTMemWipeThoroughly(pwszDomain, (RTUtf16Len(pwszDomain) + 1) * sizeof(RTUTF16), 3 /* Passes */);
                        RTUtf16Free(pwszDomain);
                    }

                    pwszDomain = RTUtf16Dup(pwszExtractedDomain);

                    CoTaskMemFree(pwszExtractedDomain);
                    pwszExtractedDomain = NULL;
                }

                VBoxCredProvVerbose(0, "VBoxCredProvCredential::RetrieveCredentials: Extracted account name '%ls' + domain '%ls'\n",
                                    pwszUser ? pwszUser : L"<NULL>", pwszDomain ? pwszDomain : L"<NULL>");
            }
        }

        m_fHaveCreds = true;
    }

    if (m_fHaveCreds)
    {
        VBoxCredProvVerbose(0, "VBoxCredProvCredential::RetrieveCredentials: Setting fields\n");

        setField(VBOXCREDPROV_FIELDID_USERNAME,   pwszUser,     true /* fNotifyUI */);
        setField(VBOXCREDPROV_FIELDID_PASSWORD,   pwszPassword, true /* fNotifyUI */);
        setField(VBOXCREDPROV_FIELDID_DOMAINNAME, pwszDomain,   true /* fNotifyUI */);
    }

    VBoxCredProvVerbose(0, "VBoxCredProvCredential::RetrieveCredentials: Wiping ...\n");

    VbglR3CredentialsDestroyUtf16(pwszUser, pwszPassword, pwszDomain, 3 /* cPasses */);

    VBoxCredProvVerbose(0, "VBoxCredProvCredential::RetrieveCredentials: Returned rc=%Rrc\n", rc);
    return rc;
}
Пример #7
0
Файл: Ui.c Проект: kichik/nsis-1
static BOOL CALLBACK DirProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  static int dontsetdefstyle;
  page *thispage = g_this_page;
  char *dir = g_usrvars[thispage->parms[4]];
  int browse_text = thispage->parms[3];
  if (uMsg == WM_NOTIFY_INIGO_MONTOYA)
  {
    GetUIText(IDC_DIR,dir);
    validate_filename(dir);
#ifdef NSIS_CONFIG_LOG
#if !defined(NSIS_CONFIG_LOG_ODS) && !defined(NSIS_CONFIG_LOG_STDOUT)
    build_g_logfile();
#endif
    if (GetUIItem(IDC_CHECK1) != NULL)
      log_dolog = IsDlgButtonChecked(hwndDlg,IDC_CHECK1);
#endif
  }
  if (uMsg == WM_INITDIALOG)
  {
    HWND hDir = GetUIItem(IDC_DIR);

#ifdef NSIS_CONFIG_LOG
    if (GetAsyncKeyState(VK_SHIFT)&0x8000)
    {
      HWND h=GetUIItem(IDC_CHECK1);
      SetUITextFromLang(IDC_CHECK1,LANG_LOG_INSTALL_PROCESS);
      ShowWindow(h,SW_SHOWNA);
    }
#endif
    if (validpathspec(dir) && !skip_root(dir))
      addtrailingslash(dir);

    // workaround for bug #1209843
    //
    // m_curwnd is only updated once WM_INITDIALOG returns.
    // my_SetWindowText triggers an EN_CHANGE message that
    // triggers a WM_IN_UPDATEMSG message that uses m_curwnd
    // to get the selected directory (GetUIText).
    // because m_curwnd is still outdated, dir varialble is
    // filled with an empty string. by default, dir points
    // to $INSTDIR.
    //
    // to solve this, m_curwnd is manually set to the correct
    // window handle.

    m_curwnd=hwndDlg;

    my_SetWindowText(hDir,dir);
    SetUITextFromLang(IDC_BROWSE,this_page->parms[2]);
    SetUITextFromLang(IDC_SELDIRTEXT,this_page->parms[1]);
    SetActiveCtl(hDir);

    {
      typedef HRESULT (WINAPI *SHAutoCompletePtr)(HWND, DWORD);
      SHAutoCompletePtr fSHAutoComplete;
      fSHAutoComplete = (SHAutoCompletePtr) myGetProcAddress(MGA_SHAutoComplete);
      if (fSHAutoComplete)
      {
        fSHAutoComplete(hDir, SHACF_FILESYSTEM);
      }
    }
  }
  if (uMsg == WM_COMMAND)
  {
    int id=LOWORD(wParam);
    if (id == IDC_DIR && HIWORD(wParam) == EN_CHANGE)
    {
      uMsg = WM_IN_UPDATEMSG;
    }
    if (id == IDC_BROWSE)
    {
      static char bt[NSIS_MAX_STRLEN];
      BROWSEINFO bi = {0,};
      ITEMIDLIST *idlist;
      bi.hwndOwner = hwndDlg;
      bi.pszDisplayName = g_tmp;
      bi.lpfn = BrowseCallbackProc;
      bi.lParam = (LPARAM)dir;
      bi.lpszTitle = GetNSISString(bt, browse_text);
      bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;
      idlist = SHBrowseForFolder(&bi);
      if (idlist)
      {
        // free idlist
        CoTaskMemFree(idlist);

        addtrailingslash(dir);

        if (g_header->install_directory_auto_append &&
          dir == state_install_directory) // only append to $INSTDIR (bug #1174184)
        {
          const char *post_str = ps_tmpbuf;
          GetNSISStringTT(g_header->install_directory_auto_append);
          // display name gives just the folder name
          if (lstrcmpi(post_str, g_tmp))
          {
            mystrcat(dir, post_str);
          }
        }

        dontsetdefstyle++;
        SetUITextNT(IDC_DIR,dir);
      }
      else
      {
        uMsg = WM_IN_UPDATEMSG;
      }
    }
  }
  if (uMsg == WM_IN_UPDATEMSG || uMsg == WM_NOTIFY_START)
  {
    static char s[NSIS_MAX_STRLEN];
    int error = 0;
    int available_set = 0;
    unsigned total, available;

    GetUIText(IDC_DIR,dir);
    if (!is_valid_instpath(dir))
      error = NSIS_INSTDIR_INVALID;

    /**
     * This part is tricky. We need to make sure a few things:
     *
     *   1. GetDiskFreeSpaceEx is always called at least once for large HD.
     *        Even if skip_root() returned NULL (e.g. "C:").
     *        Note that trimslashtoend() will nullify "C:".
     *   2. GetDiskFreeSpaceEx is called with the deepest valid directory.
     *        e.g. C:\drive when the user types C:\drive\folder1\folder2.
     *        This makes sure NTFS mount points are treated properly (#1946112).
     *   3. `s' stays valid after the loop for GetDiskFreeSpace.
     *        This means there is no cutting beyond what skip_root() returns.
     *        Or `s' could be recreated when GetDiskFreeSpace is called.
     *   4. If GetDiskFreeSpaceEx doesn't exist, GetDiskFreeSpace is used.
     *   5. Both functions require a trailing backslash
     *   6. `dir' is never modified.
     *
     */

    mystrcpy(s,dir);

    // Test for and use the GetDiskFreeSpaceEx API
    {
      BOOL (WINAPI *GDFSE)(LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER) =
          myGetProcAddress(MGA_GetDiskFreeSpaceExA);
      if (GDFSE)
      {
        ULARGE_INTEGER available64;
        ULARGE_INTEGER a, b;
        char *p;
        WORD *pw = NULL;
        while ((char *) pw != s) // trimslashtoend() cut the entire string
        {
          if (GDFSE(s, &available64, &a, &b))
          {
#ifndef _NSIS_NO_INT64_SHR
            available = (int)(available64.QuadPart >> 10);
#else
            available = (int)(Int64ShrlMod32(available64.QuadPart, 10));
#endif
            available_set++;
            break;
          }

          if (pw)
            // if pw was set, remove the backslash so trimslashtoend() will cut a new one
            *pw = 0;

          p = trimslashtoend(s); // trim last backslash
          pw = (LPWORD) (p - 1);
          *pw = CHAR2_TO_WORD('\\', 0); // bring it back, but make the next char null
        }
      }
    }

    if (!available_set)
    {
      DWORD spc, bps, fc, tc;
      char *root;

      // GetDiskFreeSpaceEx accepts any path, but GetDiskFreeSpace accepts only the root
      mystrcpy(s,dir);
      root=skip_root(s);
      if (root)
        *root=0;

      // GetDiskFreeSpaceEx is not available
      if (GetDiskFreeSpace(s, &spc, &bps, &fc, &tc))
      {
        available = (int)MulDiv(bps * spc, fc, 1 << 10);
        available_set++;
      }
    }

    total = (unsigned) sumsecsfield(size_kb);

    if (available_set && available < total)
      error = NSIS_INSTDIR_NOT_ENOUGH_SPACE;

    if (LANG_STR_TAB(LANG_SPACE_REQ)) {
      SetSizeText(IDC_SPACEREQUIRED,LANG_SPACE_REQ,total);
      if (available_set)
        SetSizeText(IDC_SPACEAVAILABLE,LANG_SPACE_AVAIL,available);
      else
        SetUITextNT(IDC_SPACEAVAILABLE,"");
    }

    g_exec_flags.instdir_error = error;

#ifdef NSIS_SUPPORT_CODECALLBACKS
    if (!error)
      error = ExecuteCallbackFunction(CB_ONVERIFYINSTDIR);
#endif

    if (thispage->flags & PF_DIR_NO_BTN_DISABLE)
      error = 0;

    EnableNext(!error);
    if (!error && !dontsetdefstyle)
      SetNextDef();
    dontsetdefstyle = 0;
  }
Пример #8
0
/**************************************************************************
*  IExtractIconW_Constructor
*/
IExtractIconW* IExtractIconW_Constructor(LPCITEMIDLIST pidl)
{
    CComPtr<IDefaultExtractIconInit>    initIcon;
    IExtractIconW *extractIcon;
    GUID const * riid;
    int icon_idx;
    UINT flags;
    CHAR sTemp[MAX_PATH];
    WCHAR wTemp[MAX_PATH];
    LPITEMIDLIST pSimplePidl = ILFindLastID(pidl);
    HRESULT hr;

    hr = SHCreateDefaultExtractIcon(IID_PPV_ARG(IDefaultExtractIconInit,&initIcon));
    if (FAILED(hr))
        return NULL;

    hr = initIcon->QueryInterface(IID_PPV_ARG(IExtractIconW,&extractIcon));
    if (FAILED(hr))
        return NULL;

    if (_ILIsDesktop(pSimplePidl))
    {
        initIcon->SetNormalIcon(swShell32Name, -IDI_SHELL_DESKTOP);
    }
    else if ((riid = _ILGetGUIDPointer(pSimplePidl)))
    {
        /* my computer and other shell extensions */
        static const WCHAR fmt[] = { 'C', 'L', 'S', 'I', 'D', '\\',
                                     '{', '%', '0', '8', 'l', 'x', '-', '%', '0', '4', 'x', '-', '%', '0', '4', 'x', '-',
                                     '%', '0', '2', 'x', '%', '0', '2', 'x', '-', '%', '0', '2', 'x', '%', '0', '2', 'x',
                                     '%', '0', '2', 'x', '%', '0', '2', 'x', '%', '0', '2', 'x', '%', '0', '2', 'x', '}', 0
                                   };
        WCHAR xriid[50];

        swprintf(xriid, fmt,
                 riid->Data1, riid->Data2, riid->Data3,
                 riid->Data4[0], riid->Data4[1], riid->Data4[2], riid->Data4[3],
                 riid->Data4[4], riid->Data4[5], riid->Data4[6], riid->Data4[7]);

        const WCHAR* iconname = NULL;
        if (_ILIsBitBucket(pSimplePidl))
        {
            static const WCHAR szFull[] = {'F','u','l','l',0};
            static const WCHAR szEmpty[] = {'E','m','p','t','y',0};
            IEnumIDList *EnumIDList = NULL;
            CoInitialize(NULL);

            IShellFolder2 *psfRecycleBin = NULL;
            IShellFolder *psfDesktop = NULL;
            hr = SHGetDesktopFolder(&psfDesktop);

            if (SUCCEEDED(hr))
                hr = psfDesktop->BindToObject(pSimplePidl, NULL, IID_IShellFolder2, (void**) &psfRecycleBin);
            if (SUCCEEDED(hr))
                hr = psfRecycleBin->EnumObjects(NULL, SHCONTF_FOLDERS | SHCONTF_NONFOLDERS, &EnumIDList);

            ULONG itemcount;
            LPITEMIDLIST pidl = NULL;
            if (SUCCEEDED(hr) && (hr = EnumIDList->Next(1, &pidl, &itemcount)) == S_OK)
            {
                CoTaskMemFree(pidl);
                iconname = szFull;
            } else {
                iconname = szEmpty;
            }

            if (psfDesktop)
                psfDesktop->Release();
            if (psfRecycleBin)
                psfRecycleBin->Release();
            if (EnumIDList)
                EnumIDList->Release();
        }

        if (HCR_GetIconW(xriid, wTemp, iconname, MAX_PATH, &icon_idx))
        {
            initIcon->SetNormalIcon(wTemp, icon_idx);
        }
        else
        {
            if (IsEqualGUID(*riid, CLSID_MyComputer))
                initIcon->SetNormalIcon(swShell32Name, -IDI_SHELL_MY_COMPUTER);
            else if (IsEqualGUID(*riid, CLSID_MyDocuments))
                initIcon->SetNormalIcon(swShell32Name, -IDI_SHELL_MY_DOCUMENTS);
            else if (IsEqualGUID(*riid, CLSID_NetworkPlaces))
                initIcon->SetNormalIcon(swShell32Name, -IDI_SHELL_MY_NETWORK_PLACES);
            else
                initIcon->SetNormalIcon(swShell32Name, -IDI_SHELL_FOLDER);
        }
    }

    else if (_ILIsDrive (pSimplePidl))
    {
        static const WCHAR drive[] = { 'D', 'r', 'i', 'v', 'e', 0 };
        int icon_idx = -1;

        if (_ILGetDrive(pSimplePidl, sTemp, MAX_PATH))
        {
            switch(GetDriveTypeA(sTemp))
            {
                case DRIVE_REMOVABLE:
                    icon_idx = IDI_SHELL_FLOPPY;
                    break;
                case DRIVE_CDROM:
                    icon_idx = IDI_SHELL_CDROM;
                    break;
                case DRIVE_REMOTE:
                    icon_idx = IDI_SHELL_NETDRIVE;
                    break;
                case DRIVE_RAMDISK:
                    icon_idx = IDI_SHELL_RAMDISK;
                    break;
                case DRIVE_NO_ROOT_DIR:
                    icon_idx = IDI_SHELL_CDROM;
                    break;
            }
        }

        if (icon_idx != -1)
        {
            initIcon->SetNormalIcon(swShell32Name, -icon_idx);
        }
        else
        {
            if (HCR_GetIconW(drive, wTemp, NULL, MAX_PATH, &icon_idx))
                initIcon->SetNormalIcon(wTemp, icon_idx);
            else
                initIcon->SetNormalIcon(swShell32Name, -IDI_SHELL_DRIVE);
        }
    }

    else if (_ILIsFolder (pSimplePidl))
    {
        if (SUCCEEDED(getIconLocationForFolder(
                          pidl, 0, wTemp, MAX_PATH,
                          &icon_idx,
                          &flags)))
        {
            initIcon->SetNormalIcon(wTemp, icon_idx);
            // FIXME: if/when getIconLocationForFolder does something for 
            //        GIL_FORSHORTCUT, code below should be uncommented. and
            //        the following line removed.
            initIcon->SetShortcutIcon(wTemp, icon_idx);
        }
        if (SUCCEEDED(getIconLocationForFolder(
                          pidl, GIL_DEFAULTICON, wTemp, MAX_PATH,
                          &icon_idx,
                          &flags)))
        {
            initIcon->SetDefaultIcon(wTemp, icon_idx);
        }
        // if (SUCCEEDED(getIconLocationForFolder(
        //                   pidl, GIL_FORSHORTCUT, wTemp, MAX_PATH,
        //                   &icon_idx,
        //                   &flags)))
        // {
        //     initIcon->SetShortcutIcon(wTemp, icon_idx);
        // }
        if (SUCCEEDED(getIconLocationForFolder(
                          pidl, GIL_OPENICON, wTemp, MAX_PATH,
                          &icon_idx,
                          &flags)))
        {
            initIcon->SetOpenIcon(wTemp, icon_idx);
        }
    }
    else
    {
        BOOL found = FALSE;

        if (_ILIsCPanelStruct(pSimplePidl))
        {
            if (SUCCEEDED(CPanel_GetIconLocationW(pSimplePidl, wTemp, MAX_PATH, &icon_idx)))
                found = TRUE;
        }
        else if (_ILGetExtension(pSimplePidl, sTemp, MAX_PATH))
        {
            if (HCR_MapTypeToValueA(sTemp, sTemp, MAX_PATH, TRUE)
                    && HCR_GetIconA(sTemp, sTemp, NULL, MAX_PATH, &icon_idx))
            {
                if (!lstrcmpA("%1", sTemp)) /* icon is in the file */
                {
                    SHGetPathFromIDListW(pidl, wTemp);
                    icon_idx = 0;
                }
                else
                {
                    MultiByteToWideChar(CP_ACP, 0, sTemp, -1, wTemp, MAX_PATH);
                }

                found = TRUE;
            }
            else if (!lstrcmpiA(sTemp, "lnkfile"))
            {
                /* extract icon from shell shortcut */
                CComPtr<IShellFolder>        dsf;
                CComPtr<IShellLinkW>        psl;

                if (SUCCEEDED(SHGetDesktopFolder(&dsf)))
                {
                    HRESULT hr = dsf->GetUIObjectOf(NULL, 1, (LPCITEMIDLIST*)&pidl, IID_IShellLinkW, NULL, (LPVOID *)&psl);

                    if (SUCCEEDED(hr))
                    {
                        hr = psl->GetIconLocation(wTemp, MAX_PATH, &icon_idx);

                        if (SUCCEEDED(hr) && *sTemp)
                            found = TRUE;

                    }
                }
            }
        }

        if (!found)
            /* default icon */
            initIcon->SetNormalIcon(swShell32Name, 0);
        else
            initIcon->SetNormalIcon(wTemp, icon_idx);
    }

    return extractIcon;
}
Пример #9
0
STDMETHODIMP CCUBRIDRowset::GetPendingRows(HCHAPTER hReserved, DBPENDINGSTATUS dwRowStatus,
				DBCOUNTITEM *pcPendingRows, HROW **prgPendingRows,
				DBPENDINGSTATUS **prgPendingStatus)
{
	ATLTRACE(atlTraceDBProvider, 2, "CCUBRIDRowset::GetPendingRows\n");

	ClearError();
	if(m_nStatus==1) return RaiseError(E_UNEXPECTED, 1, __uuidof(IRowsetUpdate), L"This object is in a zombie state");

	bool bPending = false;
	CCUBRIDRowsetRow *pRow = NULL;

	if(pcPendingRows)
	{
		*pcPendingRows = 0;
		if(prgPendingRows) *prgPendingRows = NULL;
		if(prgPendingStatus) *prgPendingStatus = NULL;
	}

	// Validate input parameters
	if ((dwRowStatus & 
		~(DBPENDINGSTATUS_NEW | DBPENDINGSTATUS_CHANGED | DBPENDINGSTATUS_DELETED)) != 0)
		return E_INVALIDARG;

	// Determine how many rows we'll need to return

	POSITION pos = m_rgRowHandles.GetStartPosition();
	while( pos != NULL )
	{
		MapClass::CPair* pPair = m_rgRowHandles.GetNext( pos );
		ATLASSERT( pPair != NULL );

		// Check to see if a row has a pending status
		pRow = pPair->m_value;

		if (pRow->m_status & dwRowStatus)
		{
			if (pcPendingRows != NULL)
				(*pcPendingRows)++;
			bPending = true;
		}
	}

	// In this case, there are no pending rows that match, just exit out
	if (!bPending)
	{
		// There are no pending rows so exit immediately
		return S_FALSE;
	}
	else
	{
		// Here' the consumer just wants to see if there are pending rows
		// we know that so we can exit
		if (pcPendingRows == NULL)
			return S_OK;
	}

	// Allocate arrays for pending rows
	{
		if (prgPendingRows != NULL)
		{
			*prgPendingRows = (HROW*)CoTaskMemAlloc(*pcPendingRows * sizeof(HROW));
			if (*prgPendingRows == NULL)
			{
				*pcPendingRows = 0;
				return E_OUTOFMEMORY;
			}
		}

		if (prgPendingStatus != NULL)
		{
			*prgPendingStatus = (DBPENDINGSTATUS*)CoTaskMemAlloc(*pcPendingRows * sizeof(DBPENDINGSTATUS));
			if (*prgPendingStatus == NULL)
			{
				*pcPendingRows = 0;
				CoTaskMemFree(*prgPendingRows);
				*prgPendingRows = NULL;
				return E_OUTOFMEMORY;
			}
			memset(*prgPendingStatus, 0, *pcPendingRows * sizeof(DBPENDINGSTATUS));
		}
	}

	if (prgPendingRows || prgPendingStatus)
	{
		ULONG ulRows = 0;
		pos = m_rgRowHandles.GetStartPosition();
		while( pos != NULL )
		{
			MapClass::CPair* pPair = m_rgRowHandles.GetNext( pos );
			ATLASSERT( pPair != NULL );

			pRow = pPair->m_value;
			if (pRow->m_status & dwRowStatus)
			{
				// Add the output row
				pRow->AddRefRow();
				if (prgPendingRows)
					((*prgPendingRows)[ulRows]) = /*(HROW)*/pPair->m_key;
				if (prgPendingStatus)
					((*prgPendingStatus)[ulRows]) = (DBPENDINGSTATUS)pRow->m_status;
				ulRows++;
			}
		}
		if (pcPendingRows != NULL)
			*pcPendingRows = ulRows;
	}

	// Return code depending on
	return S_OK;
}
Пример #10
0
/*
 * Tests if clicking the "Make New Folder" button in a SHBrowseForFolder
 * dialog box creates a new folder. (Bug 17986).
 *
 * Here follows a description of what happens on W2K,Vista, W2K8, W7:
 * When the "Make New Folder" button is clicked a new folder is created and
 * inserted into the tree. The folder is given a default name that depends on
 * the locale (e.g. "New Folder"). The folder name is selected and the dialog
 * waits for the user to type in a new name. The folder is renamed when the user
 * types in a name and presses enter.
 *
 * Note that XP and W2K3 do not select the folder name or wait for the user
 * to type in a new folder name. This behavior is considered broken as most
 * users would like to give the folder a name after creating it. The fact that
 * it originally waited for the user to type in a new folder name(W2K), and then
 * again was changed back wait for the new folder name(Vista, W2K8, W7),
 * indicates that MS also believes that it was broken in XP and W2K3.
 */
static void test_click_make_new_folder_button(void)
{
    HRESULT resCoInit, hr;
    BROWSEINFO bi;
    LPITEMIDLIST pidl = NULL;
    LPITEMIDLIST test_folder_pidl;
    IShellFolder *test_folder_object;
    char test_folder_path[MAX_PATH];
    WCHAR test_folder_pathW[MAX_PATH];
    CHAR new_folder_path[MAX_PATH];
    CHAR new_folder_pidl_path[MAX_PATH];
    char selected_folder[MAX_PATH];
    const CHAR title[] = "test_click_make_new_folder_button";
    int number_of_folders = -1;
    SHFILEOPSTRUCT shfileop;

    if (does_folder_or_file_exist(title))
    {
        skip("The test folder already exists.\n");
        return;
    }

    /* Must initialize COM if using the NEWDIAlOGSTYLE according to MSDN. */
    resCoInit = CoInitialize(NULL);
    if(!(resCoInit == S_OK || resCoInit == S_FALSE))
    {
        skip("COM could not be initialized %u\n", GetLastError());
        return;
    }

    /* Leave room for concatenating title, two backslashes, and an extra NULL. */
    if (!GetCurrentDirectoryA(MAX_PATH-strlen(title)-3, test_folder_path))
    {
        skip("GetCurrentDirectoryA failed %u\n", GetLastError());
    }
    strncat(test_folder_path, "\\", 1);
    strncat(test_folder_path, title, MAX_PATH-1);
    strncat(test_folder_path, "\\", 1);

    /* Avoid conflicts by creating a test folder. */
    if (!CreateDirectoryA(title, NULL))
    {
        skip("CreateDirectoryA failed %u\n", GetLastError());
        return;
    }

    /* Initialize browse info struct for SHBrowseForFolder */
    bi.hwndOwner = NULL;
    bi.pszDisplayName = (LPTSTR) &selected_folder;
    bi.lpszTitle = (LPTSTR) title;
    bi.ulFlags = BIF_NEWDIALOGSTYLE;
    bi.lpfn = create_new_folder_callback;
    /* Use test folder as the root folder for dialog box */
    MultiByteToWideChar(CP_UTF8, 0, test_folder_path, MAX_PATH,
        test_folder_pathW, MAX_PATH);
    hr = SHGetDesktopFolder(&test_folder_object);
    ok (SUCCEEDED(hr), "SHGetDesktopFolder failed with hr 0x%08x\n", hr);
    if (FAILED(hr)) {
        skip("SHGetDesktopFolder failed - skipping\n");
        return;
    }
    test_folder_object->lpVtbl->ParseDisplayName(test_folder_object, NULL, NULL,
        test_folder_pathW, 0UL, &test_folder_pidl, 0UL);
    bi.pidlRoot = test_folder_pidl;

    /* Display dialog box and let callback click the buttons */
    pidl = SHBrowseForFolder(&bi);

    number_of_folders = get_number_of_folders(test_folder_path);
    ok(number_of_folders == 1 || broken(number_of_folders == 0) /* W95, W98 */,
        "Clicking \"Make New Folder\" button did not result in a new folder.\n");

    /* There should be a new folder foo inside the test folder */
    strcpy(new_folder_path, test_folder_path);
    strcat(new_folder_path, new_folder_name);
    ok(does_folder_or_file_exist(new_folder_path)
        || broken(!does_folder_or_file_exist(new_folder_path)) /* W95, W98, XP, W2K3 */,
        "The new folder did not get the name %s\n", new_folder_name);

    /* Dialog should return a pidl pointing to the new folder */
    ok(SHGetPathFromIDListA(pidl, new_folder_pidl_path),
        "SHGetPathFromIDList failed for new folder.\n");
    ok(strcmp(new_folder_path, new_folder_pidl_path) == 0
        || broken(strcmp(new_folder_path, new_folder_pidl_path) != 0) /* earlier than Vista */,
        "SHBrowseForFolder did not return the pidl for the new folder. "
        "Expected '%s' got '%s'\n", new_folder_path, new_folder_pidl_path);

    /* Remove test folder and any subfolders created in this test */
    shfileop.hwnd = NULL;
    shfileop.wFunc = FO_DELETE;
    /* Path must be double NULL terminated */
    test_folder_path[strlen(test_folder_path)+1] = '\0';
    shfileop.pFrom = test_folder_path;
    shfileop.pTo = NULL;
    shfileop.fFlags = FOF_NOCONFIRMATION|FOF_NOERRORUI|FOF_SILENT;
    SHFileOperation(&shfileop);

    if (pidl)
        CoTaskMemFree(pidl);
    if (test_folder_pidl)
        CoTaskMemFree(test_folder_pidl);
    test_folder_object->lpVtbl->Release(test_folder_object);

    CoUninitialize();
}
Пример #11
0
bool CSoundComponent::InitXACT(const char* engine_xgs)
{
	HRESULT hr;
	CoInitializeEx( NULL, COINIT_MULTITHREADED );  // COINIT_APARTMENTTHREADED will work too
	//TODO("Create the XACT engine");
	hr=XACT3CreateEngine(0, &mpXEngine);

	if( FAILED( hr ) || mpXEngine == NULL )
	{
		FAIL("Problems creating XACT engine","InitXACT Failed");
		return false;
	}

	// Load the global settings file and pass it into XACTInitialize
	VOID* pGlobalSettingsData = NULL;
	DWORD dwGlobalSettingsFileSize = 0;
	bool bSuccess = false;
	HANDLE hFile = CreateFile( engine_xgs, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
	if( hFile!=INVALID_HANDLE_VALUE )
	{
		dwGlobalSettingsFileSize = GetFileSize( hFile, NULL );
		if( dwGlobalSettingsFileSize != INVALID_FILE_SIZE )
		{
			pGlobalSettingsData = CoTaskMemAlloc( dwGlobalSettingsFileSize );
			if( pGlobalSettingsData )
			{
				DWORD dwBytesRead;
				if( 0 != ReadFile( hFile, pGlobalSettingsData, dwGlobalSettingsFileSize, &dwBytesRead, NULL ) )
				{
					bSuccess = true;
				}
			}
		}
		CloseHandle( hFile );
	}
	if( !bSuccess )
	{
		if( pGlobalSettingsData )
			CoTaskMemFree( pGlobalSettingsData );
		pGlobalSettingsData = NULL;
		dwGlobalSettingsFileSize = 0;
		FAIL(engine_xgs,"Problems opening engine file");
		return false;
	}

	// Initialize & create the XACT runtime 
	XACT_RUNTIME_PARAMETERS xrParams = {0};
	xrParams.lookAheadTime = XACT_ENGINE_LOOKAHEAD_DEFAULT;
	xrParams.pGlobalSettingsBuffer = pGlobalSettingsData;
	xrParams.globalSettingsBufferSize = dwGlobalSettingsFileSize;
	xrParams.globalSettingsFlags = XACT_FLAG_GLOBAL_SETTINGS_MANAGEDATA; // this will tell XACT to delete[] the buffer when its unneeded
	//TODO(Initalise the XACT engine);
	hr=mpXEngine->Initialize(&xrParams);
	if( FAILED( hr ) )
	{
		FAIL(engine_xgs,"Problems Initalising XACT engine");
		return false;
	}

	X3DAUDIO_EMITTER emitter = {0};
	X3DAUDIO_LISTENER listener = {0};

	listener.OrientFront = D3DXVECTOR3( 0, 0, 1 );
	listener.OrientTop = D3DXVECTOR3( 0, 1, 0 );
	listener.Position = D3DXVECTOR3( 0, 0, 0 );
	listener.Velocity = D3DXVECTOR3( 0, 0, 0 );

	// the following need to be orthonormal
	emitter.OrientFront = D3DXVECTOR3( 0, 0, 1 );
	emitter.OrientTop = D3DXVECTOR3( 0, 1, 0 );
	emitter.Position = D3DXVECTOR3( 0, 0, 0 );
	emitter.Velocity = D3DXVECTOR3( 0, 0, 0 ); // needs to not be zero if you want to hear Doppler effect

	// emitter ChannelCount and DSP Setting's SrcChannelCount must match
	emitter.ChannelCount = 2;   

	// this will be set by XACT3DCalculate if ChannelCount > 1.
	emitter.ChannelRadius = 1.0f;   

	// will be set by XACT3DCalculate
	emitter.pChannelAzimuths = NULL;

	// will be set by XACT3DCalculate
	emitter.pVolumeCurve = emitter.pLFECurve
		= emitter.pLPFDirectCurve
		= emitter.pLPFReverbCurve
		= emitter.pReverbCurve
		= NULL;

	emitter.CurveDistanceScaler = 1.0;
	emitter.DopplerScaler = 1.0f;

	hr = XACT3DInitialize(mpXEngine, xact3dInstance);

	if( FAILED( hr ) )
	{
		FAIL(engine_xgs,"Problems Initalising XACT 3D engine");
		return false;
	}

	// check how many output channels are supported
	WAVEFORMATEXTENSIBLE format;
	hr = mpXEngine->GetFinalMixFormat(&format);
	if(FAILED(hr))
	{
		FAIL("BLABLBA");
	}
	// fill the DSP
	ZeroMemory(&dspSettings,sizeof(dspSettings));
	// different code's seem to suggest 1 or 2 channels for the emitter
	dspSettings.SrcChannelCount = 1;
	dspSettings.DstChannelCount = format.Format.nChannels;  // as supported 
	dspSettings.pMatrixCoefficients = new FLOAT32[dspSettings.SrcChannelCount * dspSettings.DstChannelCount];
	ZeroMemory(dspSettings.pMatrixCoefficients ,sizeof(FLOAT32)*dspSettings.SrcChannelCount * dspSettings.DstChannelCount);

	return true;
}
HRESULT FindRFCOMMChannel (unsigned char *pStream, int cStream,
			   unsigned long *nChannel)
{
	ISdpRecord **pRecordArg = NULL;
	int cRecordArg          = 0;
	ISdpStream *pIStream    = NULL;
	HRESULT hr              = 0;
	ULONG ulError           = 0;

	*nChannel = 0;

	hr = CoCreateInstance(__uuidof(SdpStream),NULL,
		CLSCTX_INPROC_SERVER,
		__uuidof(ISdpStream),(LPVOID *)
		&pIStream);

	if ( FAILED(hr) || pIStream == NULL )
		return hr;

	hr = pIStream->Validate (pStream, cStream,&ulError);

	if (SUCCEEDED(hr))
	{
		hr = pIStream->VerifySequenceOf(pStream, cStream,
			SDP_TYPE_SEQUENCE,NULL,
			(ULONG *)&cRecordArg);

		if (SUCCEEDED(hr) && cRecordArg > 0)
		{
			pRecordArg =
				(ISdpRecord **) CoTaskMemAlloc(sizeof(ISdpRecord*)
				* cRecordArg);

			if (pRecordArg != NULL)
			{
				hr =
					pIStream->RetrieveRecords(pStream, cStream,
					pRecordArg,(ULONG *)
					&cRecordArg);

				if ( FAILED(hr) )
				{
					CoTaskMemFree(pRecordArg);
					pRecordArg = NULL;
					cRecordArg = 0;
				}
			}
			else
			{
				hr = E_OUTOFMEMORY;
			}
		}
	}

	if (pIStream != NULL)
	{
		pIStream->Release();
		pIStream = NULL;
	}

	if ( FAILED(hr) )
		return hr;

	for (int i = 0; (*nChannel == 0) && (i < cRecordArg); i++)
	{
		ISdpRecord *pRecord = pRecordArg[i];
		// contains SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST data,
		// if available
		NodeData protocolList;

		if (ERROR_SUCCESS !=
			pRecord->GetAttribute(SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST,
			&protocolList) ||
			(protocolList.type !=
			SDP_TYPE_CONTAINER))
		{
			if (protocolList.type == SDP_TYPE_STRING)
				CoTaskMemFree(protocolList.u.str.val);
			else if (protocolList.type == SDP_TYPE_URL)
				CoTaskMemFree(protocolList.u.url.val);
			continue;
		}

		ISdpNodeContainer *pRecordContainer = protocolList.u.container;
		int cProtocols = 0;
		NodeData protocolDescriptor;

		pRecordContainer->GetNodeCount((DWORD *)&cProtocols);
		for (int j = 0; (nChannel == 0) && (j < cProtocols); j++)
		{
			pRecordContainer->GetNode(j,&protocolDescriptor);

			if (protocolDescriptor.type != SDP_TYPE_CONTAINER)
				continue;

			ISdpNodeContainer *pProtocolContainer =
				protocolDescriptor.u.container;
			int cProtocolAtoms = 0;
			pProtocolContainer->GetNodeCount((DWORD *)&cProtocolAtoms);

			for (int k = 0; (nChannel == 0) && (k < cProtocolAtoms); k++)
			{
				NodeData nodeAtom;
				pProtocolContainer->GetNode(k,&nodeAtom);

				if (IsRfcommUuid(&nodeAtom))
				{
					if (k+1 == cProtocolAtoms)
					{
						// Error: Channel ID should follow RFCOMM uuid
						break;
					}

					NodeData channelID;
					pProtocolContainer->GetNode(k+1,&channelID);

					switch(channelID.specificType)
					{
					case SDP_ST_UINT8:
						*nChannel = channelID.u.uint8;
						break;
					case SDP_ST_INT8:
						*nChannel = channelID.u.int8;
						break;
					case SDP_ST_UINT16:
						*nChannel = channelID.u.uint16;
						break;
					case SDP_ST_INT16:
						*nChannel = channelID.u.int16;
						break;
					case SDP_ST_UINT32:
						*nChannel = channelID.u.uint32;
						break;
					case SDP_ST_INT32:
						*nChannel = channelID.u.int32;
						break;
					default:
						*nChannel = 0;
					}
					break;
				}
			}
		}
		if (protocolList.type == SDP_TYPE_STRING)
			CoTaskMemFree(protocolList.u.str.val);
		else if (protocolList.type == SDP_TYPE_URL)
			CoTaskMemFree(protocolList.u.url.val);
	}

	// cleanup
	for (int i = 0; i < cRecordArg; i++)
		pRecordArg[i]->Release();
	CoTaskMemFree(pRecordArg);

	return (*nChannel != 0) ? S_OK : S_FALSE;
}
Пример #13
0
void CDSMMuxerFilter::MuxHeader(IBitStream* pBS)
{
	CString muxer;
	muxer.Format(_T("DSM Muxer (%s)"), CString(__TIMESTAMP__));

	SetProperty(L"MUXR", CStringW(muxer));
	SetProperty(L"DATE", CStringW(CTime::GetCurrentTime().FormatGmt(_T("%Y-%m-%d %H:%M:%S"))));

	MuxFileInfo(pBS);

	POSITION pos = m_pPins.GetHeadPosition();
	while(pos)
	{
		CBaseMuxerInputPin* pPin = m_pPins.GetNext(pos);
		const CMediaType& mt = pPin->CurrentMediaType();

		ASSERT((mt.lSampleSize >> 30) == 0); // you don't need >1GB samples, do you?

		MuxPacketHeader(pBS, DSMP_MEDIATYPE, 5 + sizeof(GUID)*3 + mt.FormatLength());
		pBS->BitWrite(pPin->GetID(), 8);
		pBS->ByteWrite(&mt.majortype, sizeof(mt.majortype));
		pBS->ByteWrite(&mt.subtype, sizeof(mt.subtype));
		pBS->BitWrite(mt.bFixedSizeSamples, 1);
		pBS->BitWrite(mt.bTemporalCompression, 1);
		pBS->BitWrite(mt.lSampleSize, 30);
		pBS->ByteWrite(&mt.formattype, sizeof(mt.formattype));
		pBS->ByteWrite(mt.Format(), mt.FormatLength());
		
		MuxStreamInfo(pBS, pPin);
	}

	// resources & chapters

	CInterfaceList<IDSMResourceBag> pRBs;
	pRBs.AddTail(this);

	CComQIPtr<IDSMChapterBag> pCB = (IUnknown*)(INonDelegatingUnknown*)this;

	pos = m_pPins.GetHeadPosition();
	while(pos)
	{
		for(CComPtr<IPin> pPin = m_pPins.GetNext(pos)->GetConnected(); pPin; pPin = GetUpStreamPin(GetFilterFromPin(pPin)))
		{
			if(m_fAutoRes)
			{
				CComQIPtr<IDSMResourceBag> pPB = GetFilterFromPin(pPin);
				if(pPB && !pRBs.Find(pPB)) pRBs.AddTail(pPB);
			}

			if(m_fAutoChap)
			{
				if(!pCB || pCB->ChapGetCount() == 0) pCB = GetFilterFromPin(pPin);				
			}
		}
	}

	// resources

	pos = pRBs.GetHeadPosition();
	while(pos)
	{
		IDSMResourceBag* pRB = pRBs.GetNext(pos);

		for(DWORD i = 0, j = pRB->ResGetCount(); i < j; i++)
		{
			CComBSTR name, desc, mime;
			BYTE* pData = NULL;
			DWORD len = 0;
			if(SUCCEEDED(pRB->ResGet(i, &name, &desc, &mime, &pData, &len, NULL)))
			{
				CStringA utf8_name = UTF16To8(name);
				CStringA utf8_desc = UTF16To8(desc);
				CStringA utf8_mime = UTF16To8(mime);

				MuxPacketHeader(pBS, DSMP_RESOURCE, 
					1 + 
					utf8_name.GetLength()+1 + 
					utf8_desc.GetLength()+1 + 
					utf8_mime.GetLength()+1 + 
					len);

				pBS->BitWrite(0, 2);
				pBS->BitWrite(0, 6); // reserved
				pBS->ByteWrite(utf8_name, utf8_name.GetLength()+1);
				pBS->ByteWrite(utf8_desc, utf8_desc.GetLength()+1);
				pBS->ByteWrite(utf8_mime, utf8_mime.GetLength()+1);
				pBS->ByteWrite(pData, len);

				CoTaskMemFree(pData);
			}
		}
	}

	// chapters

	if(pCB)
	{
		CAtlList<CDSMChapter> chapters;
		REFERENCE_TIME rtPrev = 0;
		int len = 0;

		pCB->ChapSort();

		for(DWORD i = 0; i < pCB->ChapGetCount(); i++)
		{
			CDSMChapter c;
			CComBSTR name;
			if(SUCCEEDED(pCB->ChapGet(i, &c.rt, &name)))
			{
				REFERENCE_TIME rtDiff = c.rt - rtPrev; rtPrev = c.rt; c.rt = rtDiff;
				c.name = name;
				len += 1 + GetByteLength(myabs(c.rt)) + UTF16To8(c.name).GetLength()+1;
				chapters.AddTail(c);
			}
		}

		if(chapters.GetCount())
		{
			MuxPacketHeader(pBS, DSMP_CHAPTERS, len);

			pos = chapters.GetHeadPosition();
			while(pos)
			{
				CDSMChapter& c = chapters.GetNext(pos);
				CStringA name = UTF16To8(c.name);
				int irt = GetByteLength(myabs(c.rt));
				pBS->BitWrite(c.rt < 0, 1);
				pBS->BitWrite(irt, 3);
				pBS->BitWrite(0, 4);
				pBS->BitWrite(myabs(c.rt), irt<<3);
				pBS->ByteWrite((LPCSTR)name, name.GetLength()+1);
			}
		}
	}
}
Пример #14
0
BOOL CPPageFormats::SetFileAssociation(CString strExt, CString strProgID, bool fRegister)
{
	CString extoldreg, extOldIcon;
	CRegKey key;
	HRESULT hr = S_OK;
	TCHAR   buff[256];
	ULONG   len = sizeof(buff)/sizeof(buff[0]);
	memset(buff, 0, sizeof(buff));

	if (m_pAAR == NULL) {
		// Default manager (requiered at least Vista)
		HRESULT hr = CoCreateInstance(CLSID_ApplicationAssociationRegistration,
									  NULL,
									  CLSCTX_INPROC,
									  __uuidof(IApplicationAssociationRegistration),
									  (void**)&m_pAAR);
		UNUSED_ALWAYS(hr);
	}

	if (m_pAAR) {
		// The Vista way
		CString strNewApp;
		if (fRegister) {
			// Create non existing file type
			if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strExt)) {
				return false;
			}

			WCHAR*		pszCurrentAssociation;
			// Save current application associated
			if (SUCCEEDED (m_pAAR->QueryCurrentDefault (strExt, AT_FILEEXTENSION, AL_EFFECTIVE, &pszCurrentAssociation))) {
				if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID)) {
					return false;
				}

				key.SetStringValue(g_strOldAssoc, pszCurrentAssociation);

				// Get current icon for file type
				/*
				if (ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, CString(pszCurrentAssociation) + _T("\\DefaultIcon")))
				{
					len = sizeof(buff);
					memset(buff, 0, len);
					if (ERROR_SUCCESS == key.QueryStringValue(NULL, buff, &len) && !CString(buff).Trim().IsEmpty())
					{
						if (ERROR_SUCCESS == key.Create(HKEY_CLASSES_ROOT, strProgID + _T("\\DefaultIcon")))
							key.SetStringValue (NULL, buff);
					}
				}
				*/
				CoTaskMemFree (pszCurrentAssociation);
			}
			strNewApp = g_strRegisteredAppName;
		} else {
			if (ERROR_SUCCESS != key.Open(HKEY_CLASSES_ROOT, strProgID)) {
				return false;
			}

			if (ERROR_SUCCESS == key.QueryStringValue(g_strOldAssoc, buff, &len)) {
				strNewApp = buff;
			}

			// TODO : retrieve registered app name from previous association (or find Bill function for that...)
		}

		hr = m_pAAR->SetAppAsDefault(strNewApp, strExt, AT_FILEEXTENSION);
	} else {
		// The 2000/XP way
		if (fRegister) {
			// Set new association
			if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strExt)) {
				return false;
			}

			len = sizeof(buff)/sizeof(buff[0]);
			memset(buff, 0, sizeof(buff));
			if (ERROR_SUCCESS == key.QueryStringValue(NULL, buff, &len) && !CString(buff).Trim().IsEmpty()) {
				extoldreg = buff;
			}
			if (ERROR_SUCCESS != key.SetStringValue(NULL, strProgID)) {
				return false;
			}

			// Get current icon for file type
			/*
			if (!extoldreg.IsEmpty())
			{
				if (ERROR_SUCCESS == key.Open(HKEY_CLASSES_ROOT, extoldreg + _T("\\DefaultIcon")))
				{
					len = sizeof(buff);
					memset(buff, 0, len);
					if (ERROR_SUCCESS == key.QueryStringValue(NULL, buff, &len) && !CString(buff).Trim().IsEmpty())
						extOldIcon = buff;
				}
			}
			*/

			// Save old association
			if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID)) {
				return false;
			}
			key.SetStringValue(g_strOldAssoc, extoldreg);

			/*
			if (!extOldIcon.IsEmpty() && (ERROR_SUCCESS == key.Create(HKEY_CLASSES_ROOT, strProgID + _T("\\DefaultIcon"))))
				key.SetStringValue (NULL, extOldIcon);
			*/
		} else {
			// Get previous association
			len = sizeof(buff)/sizeof(buff[0]);
			memset(buff, 0, sizeof(buff));
			if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strProgID)) {
				return false;
			}
			if (ERROR_SUCCESS == key.QueryStringValue(g_strOldAssoc, buff, &len) && !CString(buff).Trim().IsEmpty()) {
				extoldreg = buff;
			}

			// Set previous association
			if (ERROR_SUCCESS != key.Create(HKEY_CLASSES_ROOT, strExt)) {
				return false;
			}
			key.SetStringValue(NULL, extoldreg);
		}

	}

	return SUCCEEDED (hr);
}
Пример #15
0
HRESULT CMenuSFToolbar::FillToolbar(BOOL clearFirst)
{
    HRESULT hr;

    CComPtr<IEnumIDList> eidl;
    hr = m_shellFolder->EnumObjects(GetToolbar(), SHCONTF_FOLDERS | SHCONTF_NONFOLDERS, &eidl);
    if (FAILED_UNEXPECTEDLY(hr))
        return hr;

    HDPA dpaSort = DPA_Create(10);

    LPITEMIDLIST item = NULL;
    hr = eidl->Next(1, &item, NULL);
    while (hr == S_OK)
    {
        if (m_menuBand->_CallCBWithItemPidl(item, 0x10000000, 0, 0) == S_FALSE)
        {
            DPA_AppendPtr(dpaSort, ILClone(item));
        }

        hr = eidl->Next(1, &item, NULL);
    }

    // If no items were added, show the "empty" placeholder
    if (DPA_GetPtrCount(dpaSort) == 0)
    {
        DPA_Destroy(dpaSort);
        return AddPlaceholder();
    }

    TRACE("FillToolbar added %d items to the DPA\n", DPA_GetPtrCount(dpaSort));

    DPA_Sort(dpaSort, PidlListSort, (LPARAM) m_shellFolder.p);

    for (int i = 0; i<DPA_GetPtrCount(dpaSort);)
    {
        PWSTR MenuString;

        INT index = 0;
        INT indexOpen = 0;

        STRRET sr = { STRRET_CSTR, { 0 } };

        item = (LPITEMIDLIST)DPA_GetPtr(dpaSort, i);

        hr = m_shellFolder->GetDisplayNameOf(item, SIGDN_NORMALDISPLAY, &sr);
        if (FAILED_UNEXPECTEDLY(hr))
        {
            DPA_Destroy(dpaSort);
            return hr;
        }

        StrRetToStr(&sr, NULL, &MenuString);

        index = SHMapPIDLToSystemImageListIndex(m_shellFolder, item, &indexOpen);

        LPCITEMIDLIST itemc = item;

        SFGAOF attrs = SFGAO_FOLDER;
        hr = m_shellFolder->GetAttributesOf(1, &itemc, &attrs);

        DWORD_PTR dwData = reinterpret_cast<DWORD_PTR>(item);

        // Fetch next item already, so we know if the current one is the last
        i++;

        AddButton(i, MenuString, attrs & SFGAO_FOLDER, index, dwData, i >= DPA_GetPtrCount(dpaSort));

        CoTaskMemFree(MenuString);
    }

    DPA_Destroy(dpaSort);
    return hr;
}
Пример #16
0
STDMETHODIMP CCUBRIDRowset::Undo(HCHAPTER hReserved, DBCOUNTITEM cRows, const HROW rghRows[],
				DBCOUNTITEM *pcRowsUndone, HROW **prgRowsUndone, DBROWSTATUS **prgRowStatus)
{
	ATLTRACE(atlTraceDBProvider, 2, "CCUBRIDRowset::Undo\n");

	ClearError();
	if(m_nStatus==1) return RaiseError(E_UNEXPECTED, 1, __uuidof(IRowsetUpdate), L"This object is in a zombie state");
	CHECK_RESTART(__uuidof(IRowsetUpdate));

	DBCOUNTITEM ulRows = 0; // undo할 row 수
	bool bNotIgnore = true; // prgRowsUndone, prgRowStatus를 무시할지 여부를 나타냄

	// the following lines are used to fix the two _alloca calls below.  Those calls are risky 
	// because we may be allocating huge amounts of data.  So instead I'll allocate that data on heap.
	// But if you use _alloca you don't have to worry about cleaning this memory.  So we will use these
	// temporary variables to allocate memory on heap.  As soon as we exit the function, the memory will
	// be cleaned up, just as if we were using alloca. So now, instead of calling alloca, I'll alloc
	// memory on heap using the two smnart pointers below, and then assing it to the actual pointers.
	CHeapPtr<HROW> spTempRowsUndone;
	CHeapPtr<DBROWSTATUS> spTempRowStatus;

	if(cRows || pcRowsUndone)
	{
		if(prgRowsUndone) *prgRowsUndone = NULL;
		if(prgRowStatus) *prgRowStatus = NULL;		
	}
	else
	{
		bNotIgnore = false;		// Don't do status or row arrays
	}

	// Check to see how many changes we'll undo 
	if(pcRowsUndone)
	{
		*pcRowsUndone = NULL;
		if(prgRowsUndone==NULL) return E_INVALIDARG;
	}

	if(cRows)
	{
		if(rghRows==NULL) return E_INVALIDARG;
		ulRows = cRows;
	}
	else
		ulRows = (DBCOUNTITEM)m_rgRowHandles.GetCount();

	// NULL out pointers
	{
		if(prgRowsUndone && ulRows && bNotIgnore)
		{
			// Make a temporary buffer as we may not fill up everything
			// in the case where cRows == 0
			if(cRows)
				*prgRowsUndone = (HROW*)CoTaskMemAlloc(ulRows * sizeof(HROW));
			else
			{
				spTempRowsUndone.Allocate(ulRows);
				*prgRowsUndone = spTempRowsUndone;
			}
			if (*prgRowsUndone==NULL) return E_OUTOFMEMORY;
		}

		if(prgRowStatus && ulRows && bNotIgnore)
		{
			if(cRows)
				*prgRowStatus = (DBROWSTATUS*)CoTaskMemAlloc(ulRows * sizeof(DBROWSTATUS));
			else
			{
				spTempRowStatus.Allocate(ulRows);
				*prgRowStatus = spTempRowStatus;
			}
			if(*prgRowStatus==NULL)
			{
				if(cRows) CoTaskMemFree(*prgRowsUndone);
				*prgRowsUndone = NULL;
				return E_OUTOFMEMORY;
			}
		}
	}

	bool bSucceeded = false;
	bool bFailed = false;
	ULONG ulUndone = 0; // undo된 row 수
	POSITION pos = m_rgRowHandles.GetStartPosition();
	for (ULONG ulUndoRow = 0; ulUndoRow < ulRows; ulUndoRow++)
	{
		ULONG ulCurrentRow = ulUndone;

		HROW hRowUndo = NULL; // 현재 undo할 row의 handle
		{
			if(cRows)
			{	// row handle이 주어졌음
				hRowUndo = rghRows[ulUndoRow];
			}
			else
			{	// 모든 row에 대해 undo
				// ATLASSERT(ulUndoRow < (ULONG)m_rgRowHandles.GetCount()); // delete된 row가 있으면 성립하지 않는다.
				ATLASSERT( pos != NULL );
				MapClass::CPair* pPair = m_rgRowHandles.GetNext(pos);
				ATLASSERT( pPair != NULL );
				hRowUndo = pPair->m_key;
			}
		}

		if(prgRowsUndone && bNotIgnore)
			(*prgRowsUndone)[ulCurrentRow] = hRowUndo;

		// Fetch the RowClass and determine if it is valid
		CCUBRIDRowsetRow *pRow;
		{
			bool bFound = m_rgRowHandles.Lookup((ULONG)hRowUndo, pRow);
			if (!bFound || pRow == NULL)
			{
				if (prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_E_INVALID;
				bFailed = true;
				ulUndone++;
				continue;
			}
		}

		// If cRows is zero we'll go through all rows fetched.  We shouldn't
		// increment the count for rows that haven't been modified.
		if (cRows != 0 || (pRow != NULL &&
			pRow->m_status != 0 && pRow->m_status != DBPENDINGSTATUS_UNCHANGED
			&& pRow->m_status != DBPENDINGSTATUS_INVALIDROW))
			ulUndone++;
		else
			continue;

		if(cRows==0)
			pRow->AddRefRow();

		switch (pRow->m_status)
		{
		case DBPENDINGSTATUS_INVALIDROW:
			// 메모리와 storage 모두 존재하지 않는 row
			{
				// provider templates에서는 DELETED인데
				// INVALID가 더 맞지 않을까 싶기도 한다.
				if(prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_E_DELETED;
				bFailed = true;
			}
			break;
		case DBPENDINGSTATUS_NEW:
			// 메모리 상에만 존재하는 row
			{
				// If the row is newly inserted, go ahead and mark its
				// row as INVALID (according to the specification).

				if(prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_S_OK;

				MakeRowInvalid(this, pRow);

				bSucceeded = true;
			}
			break;
		case DBPENDINGSTATUS_CHANGED:
		case DBPENDINGSTATUS_DELETED:
			// storage의 데이터를 가져와야 하는 경우
			// delete 된 경우 메모리에 데이터가 있지만, CHANGED->DELETED 인 경우도 있을 수 있다.
			{
				// read data back
				pRow->ReadData(GetRequestHandle());
				pRow->m_status = DBPENDINGSTATUS_UNCHANGED;

				if(prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_S_OK;
				bSucceeded = true;
			}
			break;
		default: // 0, DBPENDINGSTATUS_UNCHANGED, 
			// storage의 데이터를 가져올 필요가 없는 경우
			{
				pRow->m_status = DBPENDINGSTATUS_UNCHANGED;

				if(prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_S_OK;
				bSucceeded = true;
			}
			break;
		}

		// Check if we need to release the row because it's ref was 0
		// See the IRowset::ReleaseRows section in the spec for more
		// information
		if (pRow->m_dwRef == 0)
		{
			pRow->AddRefRow();	// Artifically bump this to remove it
			if( FAILED( RefRows(1, &hRowUndo, NULL, NULL, false) ) )
				return E_FAIL;
		}
	}

	// Set the output for rows undone.
	if(pcRowsUndone) *pcRowsUndone = ulUndone;

	if(ulUndone==0)
	{
		if(prgRowsUndone)
		{
			CoTaskMemFree(*prgRowsUndone);
			*prgRowsUndone = NULL;
		}

		if(prgRowStatus)
		{
			CoTaskMemFree(*prgRowStatus);
			*prgRowStatus = NULL;
		}
	}
	else if(cRows==0)
	{
		// In the case where cRows == 0, we need to allocate the final
		// array of data.
		if(prgRowsUndone && bNotIgnore)
		{
			HROW *prgRowsTemp = (HROW *)CoTaskMemAlloc(ulUndone*sizeof(HROW));
			if(prgRowsTemp==NULL) return E_OUTOFMEMORY;
			memcpy(prgRowsTemp, *prgRowsUndone, ulUndone*sizeof(HROW));
			*prgRowsUndone = prgRowsTemp;
		}

		if(prgRowStatus && bNotIgnore)
		{
			DBROWSTATUS *prgRowStatusTemp = (DBROWSTATUS *)CoTaskMemAlloc(ulUndone*sizeof(DBROWSTATUS));
			if(prgRowStatusTemp==NULL)
			{
				CoTaskMemFree(*prgRowsUndone);
				*prgRowsUndone = NULL;
				return E_OUTOFMEMORY;
			}
			memcpy(prgRowStatusTemp, *prgRowStatus, ulUndone*sizeof(DBROWSTATUS));
			*prgRowStatus = prgRowStatusTemp;
		}
	}

	// Send the return value
	if(!bFailed)
		return S_OK;
	else
	{
		return bSucceeded ? DB_S_ERRORSOCCURRED : DB_E_ERRORSOCCURRED;
	}
}
Пример #17
0
STDMETHODIMP CXvidDecoder::FreePages(CAUUID * pPages)
{
	DPRINTF("FreePages");
	CoTaskMemFree(pPages->pElems);
	return S_OK;
}
Пример #18
0
STDMETHODIMP CCUBRIDRowset::Update(HCHAPTER hReserved, DBCOUNTITEM cRows, const HROW rghRows[],
				DBCOUNTITEM *pcRows, HROW **prgRows, DBROWSTATUS **prgRowStatus)
{
	ATLTRACE(atlTraceDBProvider, 2, "CCUBRIDRowset::Update\n");

	ClearError();
	if(m_nStatus==1) return RaiseError(E_UNEXPECTED, 1, __uuidof(IRowsetUpdate), L"This object is in a zombie state");
	CHECK_RESTART(__uuidof(IRowsetUpdate));

	DBCOUNTITEM ulRows = 0; // update할 row 수
	bool bNotIgnore = true; // prgRows, prgRowStatus를 무시할지 여부를 나타냄

	// the following lines are used to fix the two _alloca calls below.  Those calls are risky 
	// because we may be allocating huge amounts of data.  So instead I'll allocate that data on heap.
	// But if you use _alloca you don't have to worry about cleaning this memory.  So we will use these
	// temporary variables to allocate memory on heap.  As soon as we exit the function, the memory will
	// be cleaned up, just as if we were using alloca. So now, instead of calling alloca, I'll alloc
	// memory on heap using the two smnart pointers below, and then assing it to the actual pointers.
	CHeapPtr<HROW> spTempRows;
	CHeapPtr<DBROWSTATUS> spTempRowStatus;

	if(cRows || pcRows)
	{
		if(prgRows) *prgRows = NULL;
		if(prgRowStatus) *prgRowStatus = NULL;		
	}
	else
	{
		bNotIgnore = false;		// Don't do status or row arrays
	}

	// Check to see how many changes we'll undo 
	if(pcRows)
	{
		*pcRows = NULL;
		if(prgRows==NULL) return E_INVALIDARG;
	}

	if(cRows)
	{
		if(rghRows==NULL) return E_INVALIDARG;
		ulRows = cRows;
	}
	else
		ulRows = (DBCOUNTITEM)m_rgRowHandles.GetCount();

	int hConn = GetSessionPtr()->GetConnection();
	UINT uCodepage = GetSessionPtr()->GetCodepage();
	// NULL out pointers
	{
		if(prgRows && ulRows && bNotIgnore)
		{
			// Make a temporary buffer as we may not fill up everything
			// in the case where cRows == 0
			if(cRows)
				*prgRows = (HROW*)CoTaskMemAlloc(ulRows * sizeof(HROW));
			else
			{
				spTempRows.Allocate(ulRows);
				*prgRows = spTempRows;
			}
			if (*prgRows==NULL) return E_OUTOFMEMORY;
		}

		if(prgRowStatus && ulRows && bNotIgnore)
		{
			if(cRows)
				*prgRowStatus = (DBROWSTATUS*)CoTaskMemAlloc(ulRows * sizeof(DBROWSTATUS));
			else
			{
				spTempRowStatus.Allocate(ulRows);
				*prgRowStatus = spTempRowStatus;
			}
			if(*prgRowStatus==NULL)
			{
				if(cRows) CoTaskMemFree(*prgRows);
				*prgRows = NULL;
				return E_OUTOFMEMORY;
			}
		}
	}

	bool bSucceeded = false;
	bool bFailed = false;
	ULONG ulCount = 0; // update된 row 수
	POSITION pos = m_rgRowHandles.GetStartPosition();
	for (ULONG ulRow = 0; ulRow < ulRows; ulRow++)
	{
		ULONG ulCurrentRow = ulCount;
		bool bDupRow = false; // 중복된 row
		ULONG ulAlreadyProcessed = 0; // 중복된 row의 handle의 위치

		HROW hRowUpdate = NULL; // 현재 update할 row의 handle
		{
			if(cRows)
			{	// row handle이 주어졌음
				hRowUpdate = rghRows[ulRow];
				for (ULONG ulCheckDup = 0; ulCheckDup < ulRow; ulCheckDup++)
				{
					if (hRowUpdate==rghRows[ulCheckDup] ||
						IsSameRow(hRowUpdate, rghRows[ulCheckDup]) == S_OK)
					{
						ulAlreadyProcessed = ulCheckDup;
						bDupRow = true;
						break;
					}
				}
			}
			else
			{	// 모든 row에 대해 update
				//ATLASSERT(ulRow < (ULONG)m_rgRowHandles.GetCount()); // delete된 row가 있으면 성립하지 않는다.
				ATLASSERT( pos != NULL );
				MapClass::CPair* pPair = m_rgRowHandles.GetNext(pos);
				ATLASSERT( pPair != NULL );
				hRowUpdate = pPair->m_key;
			}
		}

		if(prgRows && bNotIgnore)
			(*prgRows)[ulCurrentRow] = hRowUpdate;

		if(bDupRow)
		{
			// We've already set the row before, just copy status and
			// continue processing
			if(prgRowStatus && bNotIgnore)
				(*prgRowStatus)[ulCurrentRow] = (*prgRowStatus)[ulAlreadyProcessed];
			ulCount++;
			continue;
		}

		// Fetch the RowClass and determine if it is valid
		CCUBRIDRowsetRow *pRow;
		{
			bool bFound = m_rgRowHandles.Lookup((ULONG)hRowUpdate, pRow);
			if (!bFound || pRow == NULL)
			{
				if (prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_E_INVALID;
				bFailed = true;
				ulCount++;
				continue;
			}
		}

		// If cRows is zero we'll go through all rows fetched.  We
		// shouldn't increment the attempted count for rows that are
		// not changed
		if (cRows != 0 || (pRow != NULL &&
			pRow->m_status != 0 && pRow->m_status != DBPENDINGSTATUS_UNCHANGED
			&& pRow->m_status != DBPENDINGSTATUS_INVALIDROW))
			ulCount++;
		else
			continue;

		if(cRows==0)
			pRow->AddRefRow();

		switch (pRow->m_status)
		{
		case DBPENDINGSTATUS_INVALIDROW:	// Row is bad or deleted
			{
				if(prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_E_DELETED;
				bFailed = true;
			}
			break;
		case DBPENDINGSTATUS_UNCHANGED:
		case 0:
			{
				// If the row's status is not changed, then just put S_OK
				// and continue.  The spec says we should not transmit the
				// request to the data source (as nothing would change).
				if(prgRowStatus && bNotIgnore)
					(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_S_OK;
				bSucceeded = true;
			}
			break;
		default:
			{
				DBORDINAL cCols;
				ATLCOLUMNINFO *pColInfo = GetColumnInfo(this, &cCols);
				HRESULT hr = pRow->WriteData(hConn, uCodepage, GetRequestHandle(), m_strTableName);
				if(FAILED(hr))
				{
					DBROWSTATUS stat = DBROWSTATUS_E_FAIL;
					if(hr==DB_E_INTEGRITYVIOLATION) stat = DBROWSTATUS_E_INTEGRITYVIOLATION;
					if(prgRowStatus && bNotIgnore)
						(*prgRowStatus)[ulCurrentRow] = stat;
					bFailed = true;
				}
				else
				{
					//// m_iRowset을 적당히 조정한다.
					//if(pRow->m_status==DBPENDINGSTATUS_NEW)
					//{
					//	// NEW인 row는 항상 rowset의 뒤에 몰려있다.
					//	// 그 row 중 가장 작은 m_iRowset이 update 된 row의 m_iRowset이 되면 된다.
					//	CCUBRIDRowsetRow::KeyType key = pRow->m_iRowset;
					//	POSITION pos = m_rgRowHandles.GetStartPosition();
					//	while(pos)
					//	{
					//		CCUBRIDRowset::MapClass::CPair *pPair = m_rgRowHandles.GetNext(pos);
					//		ATLASSERT(pPair);
					//		CCUBRIDRowsetRow *pCheckRow = pPair->m_value;
					//		if( pCheckRow && pCheckRow->m_iRowset < key )
					//		{
					//			if(pCheckRow->m_iRowset<pRow->m_iRowset)
					//				pRow->m_iRowset = pCheckRow->m_iRowset;
					//			pCheckRow->m_iRowset++;
					//		}
					//	}

					//	// TODO: 북마크 업데이트가 필요한데 어떻게 해야 할지 모르겠다.

					//	// 새로 추가된 Row의 OID를 읽어들인다.
					//	pRow->ReadData(GetRequestHandle(), true);
					//}

					if(pRow->m_status==DBPENDINGSTATUS_DELETED)
						MakeRowInvalid(this, pRow);
					else
						pRow->m_status = DBPENDINGSTATUS_UNCHANGED;

					if(prgRowStatus && bNotIgnore)
						(*prgRowStatus)[ulCurrentRow] = DBROWSTATUS_S_OK;
					bSucceeded = true;

					// Check if we need to release the row because it's ref was 0
					// See the IRowset::ReleaseRows section in the spec for more
					// information
					if (pRow->m_dwRef == 0)
					{
						pRow->AddRefRow();	// Artifically bump this to remove it
						if( FAILED( RefRows(1, &hRowUpdate, NULL, NULL, false) ) )
							return E_FAIL;
					}
				}
			}
			break;
		}
	}

	// Set the output for rows undone.
	if(pcRows) *pcRows = ulCount;

	if(ulCount==0)
	{
		if(prgRows)
		{
			CoTaskMemFree(*prgRows);
			*prgRows = NULL;
		}

		if(prgRowStatus)
		{
			CoTaskMemFree(*prgRowStatus);
			*prgRowStatus = NULL;
		}
	}
	else if(cRows==0)
	{
		// In the case where cRows == 0, we need to allocate the final
		// array of data.
		if(prgRows && bNotIgnore)
		{
			HROW *prgRowsTemp = (HROW *)CoTaskMemAlloc(ulCount*sizeof(HROW));
			if(prgRowsTemp==NULL) return E_OUTOFMEMORY;
			memcpy(prgRowsTemp, *prgRows, ulCount*sizeof(HROW));
			*prgRows = prgRowsTemp;
		}

		if(prgRowStatus && bNotIgnore)
		{
			DBROWSTATUS *prgRowStatusTemp = (DBROWSTATUS *)CoTaskMemAlloc(ulCount*sizeof(DBROWSTATUS));
			if(prgRowStatusTemp==NULL)
			{
				CoTaskMemFree(*prgRows);
				*prgRows = NULL;
				return E_OUTOFMEMORY;
			}
			memcpy(prgRowStatusTemp, *prgRowStatus, ulCount*sizeof(DBROWSTATUS));
			*prgRowStatus = prgRowStatusTemp;
		}
	}

	DoCommit(this); // commit

	// Send the return value
	if(!bFailed)
		return S_OK;
	else
	{
		return bSucceeded ? DB_S_ERRORSOCCURRED : DB_E_ERRORSOCCURRED;
	}
}
Пример #19
0
int controlyPlugin::launchItem(QList<InputData>* id, CatItem* item)
{
	item = item; // Compiler warning

	if (id->count() == 1) {
		// no parameters, just the item itsef

		QString path = item->fullPath;

		if (path.contains(",@")) {
			// dll cpl item indexing containing items, e.g. 'main.cpl,@1'

			runProgram("control.exe", item->fullPath); //runProgram(cmd, args);
			// use toNativeSeparators()?
		} else if ((path.startsWith("csidl:", Qt::CaseInsensitive)) && (path.endsWith(".controly", Qt::CaseSensitive))) {
			// Constant special item ID list (CSIDL)

			// shell instance object (special shell extension folder), e.g. 'csidl:0x0014.controly' ('shellinstance:0x0014')
			QString folderId = path.mid(strlen("csidl:"), strlen(path.toAscii())-strlen("csidl:")-strlen(".controly")); // e.g. 0x0014 = CSIDL_FONTS;
			bool ok;
			int folderIdx = folderId.toLong(&ok, 16);
			if (ok) {
				LPITEMIDLIST pidl;
				HRESULT hres = SHGetFolderLocation(NULL, folderIdx, NULL, 0, &pidl);
				if (hres == S_OK) {
					SHELLEXECUTEINFO sei;
					memset(&sei, 0, sizeof(sei));
					sei.cbSize = sizeof(SHELLEXECUTEINFO);
					sei.fMask = SEE_MASK_IDLIST;
					sei.hwnd = NULL;
					sei.lpVerb = NULL;
					sei.lpFile = NULL;
					sei.lpParameters = NULL;
					sei.lpDirectory = NULL;
					sei.nShow = SW_SHOW;
					sei.hInstApp = NULL;
					sei.lpIDList = pidl;
					sei.hProcess = NULL;
					//it seems we don't need CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
					ShellExecuteEx(&sei);

					CoTaskMemFree((void*)pidl); // needs objbase.h/ole32.lib
				}
			}
		} else {
			// exe cpl item with command line parameters, e.g. 'rundll32.exe shell32.dll,Options_RunDLL 1'
			// or item defined via application name, e.g. 'control.exe /name Microsoft.WindowsUpdate'

			QStringList spl = path.split(".exe ");
			if (spl.size() == 2) {
				// split size currently is always 2, as assured above
				QString executable = spl[0] + ".exe";
				QString parameters = spl[1];
				runProgram(executable, parameters);
			} else {
				runProgram(path, "");
			}
		}

		return 1;
	}

	if (id->count() != 2)
		return 1;

	CatItem last = id->last().getTopResult();
	QSettings* set = *settings;
	if (set == NULL) return 1;
	if (last.shortName == "Options") {
		set->setValue("controly/OptionsCount", set->value("controly/OptionsCount",0).toInt() + 1);
		return MSG_CONTROL_OPTIONS;
	}
	else if (last.shortName == "Rebuild Index") {
		set->setValue("controly/RebuildCount", set->value("controly/RebuildCount",0).toInt() + 1);
		return MSG_CONTROL_REBUILD;
	}
	else if (last.shortName == "Exit") {
		set->setValue("controly/ExitCount", set->value("controly/ExitCount",0).toInt() + 1);
		return MSG_CONTROL_EXIT;
	}
	return 1;

}
/// \param[in] configSection @copydoc initArg1
/// \param[in] configFile @copydoc initArg2
/// \param[in] host @copydoc initArg3
/// \param[in] options @copydoc initArg4
/// \param[in] progid @copydoc initArg5
/// \param[in] username @copydoc initArg6
/// \param[in] password @copydoc initArg7
lvDCOMInterface::lvDCOMInterface(const char *configSection, const char* configFile, const char* host, int options, const char* progid, const char* username, const char* password) : 
m_configSection(configSection), m_pidentity(NULL), m_pxmldom(NULL), m_options(options), 
	m_progid(progid != NULL? progid : ""), m_username(username != NULL? username : ""), m_password(password != NULL ? password : ""),
	m_mac_env(NULL)
	
{
	epicsThreadOnce(&onceId, initCOM, NULL);
	if (host != NULL && host[0] != '\0') 
	{
		m_host = host;
	}
	else
	{
		//		char name_buffer[MAX_COMPUTERNAME_LENGTH + 1];
		//		DWORD name_size = MAX_COMPUTERNAME_LENGTH + 1;
		//		if ( GetComputerNameEx(ComputerNameNetBIOS, name_buffer, &name_size) != 0 )
		//		{
		//			m_host = name_buffer;
		//		}
		//		else
		//		{
		//			m_host = "localhost";
		//		}			
		m_host = "localhost";
	}
	if (macCreateHandle(&m_mac_env, NULL) != 0)
	{
		throw std::runtime_error("Cannot create mac handle");
	}
	// load current environment into m_mac_env, this is so we can create a macEnvExpand() equivalent 
	// but tied to the environment at a specific time. It is useful if we want to load the same 
	// XML file twice but with a macro defined differently in each case 
	for(char** cp = environ; *cp != NULL; ++cp)
	{
		char* str_tmp = strdup(*cp);
		char* equals_loc = strchr(str_tmp, '='); // split   name=value   string
		if (equals_loc != NULL)
		{
		    *equals_loc = '\0';
		    macPutValue(m_mac_env, str_tmp, equals_loc + 1);
		}
		free(str_tmp);
	}
	//	m_doc = new TiXmlDocument;
	//	if ( !m_doc->LoadFile(configFile) )
	//	{
	//		delete m_doc;
	//		m_doc = NULL;
	//		throw std::runtime_error("Cannot load " + std::string(configFile) + ": load failure");
	//	}
	//	m_root = m_doc->RootElement();
	DomFromCOM();
	short sResult = FALSE;
	char* configFile_expanded = envExpand(configFile);
	m_configFile = configFile_expanded;
	HRESULT hr = m_pxmldom->load(_variant_t(configFile_expanded), &sResult);
	free(configFile_expanded);
	if(FAILED(hr))
	{
		throw std::runtime_error("Cannot load XML \"" + m_configFile + "\" (expanded from \"" + std::string(configFile) + "\"): load failure");
	}
	if (sResult != VARIANT_TRUE)
	{
		throw std::runtime_error("Cannot load XML \"" + m_configFile + "\" (expanded from \"" + std::string(configFile) + "\"): load failure");
	}
	std::cerr << "Loaded XML config file \"" << m_configFile << "\" (expanded from \"" << configFile << "\")" << std::endl;
	m_extint = doPath("/lvinput/extint/@path").c_str();
	epicsAtExit(epicsExitFunc, this);
	if (m_progid.size() > 0)
	{
		if ( CLSIDFromProgID(CT2W(m_progid.c_str()), &m_clsid) != S_OK )
		{
			throw std::runtime_error("Cannot find progId " + m_progid);
		}
	}
	else
	{
		m_clsid = LabVIEW::CLSID_Application;
		wchar_t* progid_str = NULL;
		if ( ProgIDFromCLSID(m_clsid, &progid_str) == S_OK )
		{
			m_progid = CW2CT(progid_str);
			CoTaskMemFree(progid_str);
		}
		else
		{
			m_progid = "LabVIEW.Application";
		}
	}
	wchar_t* clsid_str = NULL;
	if ( StringFromCLSID(m_clsid, &clsid_str) == S_OK )
	{
		std::cerr << "Using ProgID \"" << m_progid << "\" CLSID " << CW2CT(clsid_str) << std::endl;
		CoTaskMemFree(clsid_str);
	}
	else
	{
		std::cerr << "Using ProgID \"" << m_progid << "\" but StringFromCLSID() failed" << std::endl;
	}
}
Пример #21
0
static HRESULT WINAPI FileProtocol_Start(IInternetProtocol *iface, LPCWSTR szUrl,
        IInternetProtocolSink *pOIProtSink, IInternetBindInfo *pOIBindInfo,
        DWORD grfPI, DWORD dwReserved)
{
    FileProtocol *This = PROTOCOL_THIS(iface);
    BINDINFO bindinfo;
    DWORD grfBINDF = 0;
    LARGE_INTEGER size;
    DWORD len;
    LPWSTR url, mime = NULL, file_name;
    WCHAR null_char = 0;
    BOOL first_call = FALSE;
    HRESULT hres;

    static const WCHAR wszFile[]  = {'f','i','l','e',':'};

    TRACE("(%p)->(%s %p %p %08x %d)\n", This, debugstr_w(szUrl), pOIProtSink,
            pOIBindInfo, grfPI, dwReserved);

    memset(&bindinfo, 0, sizeof(bindinfo));
    bindinfo.cbSize = sizeof(BINDINFO);
    hres = IInternetBindInfo_GetBindInfo(pOIBindInfo, &grfBINDF, &bindinfo);
    if(FAILED(hres)) {
        WARN("GetBindInfo failed: %08x\n", hres);
        return hres;
    }

    ReleaseBindInfo(&bindinfo);

    if(!szUrl || !*szUrl)
        return E_INVALIDARG;

    if(lstrlenW(szUrl) < sizeof(wszFile)/sizeof(WCHAR)
            || memcmp(szUrl, wszFile, sizeof(wszFile)))
        return MK_E_SYNTAX;

    len = lstrlenW(szUrl)+16;
    url = heap_alloc(len*sizeof(WCHAR));
    hres = CoInternetParseUrl(szUrl, PARSE_ENCODE, 0, url, len, &len, 0);
    if(FAILED(hres)) {
        heap_free(url);
        return hres;
    }

    if(!(grfBINDF & BINDF_FROMURLMON))
        IInternetProtocolSink_ReportProgress(pOIProtSink, BINDSTATUS_DIRECTBIND, NULL);

    if(!This->file) {
        WCHAR *ptr;

        first_call = TRUE;

        IInternetProtocolSink_ReportProgress(pOIProtSink, BINDSTATUS_SENDINGREQUEST, &null_char);

        file_name = url+sizeof(wszFile)/sizeof(WCHAR);
        if(file_name[0] == '/' && file_name[1] == '/')
            file_name += 2;
        if(*file_name == '/')
            file_name++;

        for(ptr = file_name; *ptr; ptr++) {
            if(*ptr == '?' || *ptr == '#') {
                *ptr = 0;
                break;
            }
        }

        if(file_name[1] == '|')
            file_name[1] = ':';

        This->file = CreateFileW(file_name, GENERIC_READ, FILE_SHARE_READ, NULL,
                                 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

        if(This->file == INVALID_HANDLE_VALUE) {
            This->file = NULL;
            IInternetProtocolSink_ReportResult(pOIProtSink, INET_E_RESOURCE_NOT_FOUND,
                    GetLastError(), NULL);
            heap_free(url);
            return INET_E_RESOURCE_NOT_FOUND;
        }

        IInternetProtocolSink_ReportProgress(pOIProtSink,
                BINDSTATUS_CACHEFILENAMEAVAILABLE, file_name);

        hres = FindMimeFromData(NULL, url, NULL, 0, NULL, 0, &mime, 0);
        if(SUCCEEDED(hres)) {
            IInternetProtocolSink_ReportProgress(pOIProtSink,
                    (grfBINDF & BINDF_FROMURLMON) ?
                    BINDSTATUS_VERIFIEDMIMETYPEAVAILABLE : BINDSTATUS_MIMETYPEAVAILABLE,
                    mime);
            CoTaskMemFree(mime);
        }
    }

    heap_free(url);

    if(GetFileSizeEx(This->file, &size))
        IInternetProtocolSink_ReportData(pOIProtSink,
                BSCF_FIRSTDATANOTIFICATION|BSCF_LASTDATANOTIFICATION,
                size.u.LowPart, size.u.LowPart);

    if(first_call)
        IInternetProtocolSink_ReportResult(pOIProtSink, S_OK, 0, NULL);

    return S_OK;
}
/******************************************************************************
* CounterPaneProc *
*-----------------*
*   Description:
*       Handles messages specifically for the counter (order) pane.
*
******************************************************************************/
LRESULT CounterPaneProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
    HRESULT hr;
    
    switch ( message )
    {
        case WM_ESPRESSOORDER:
        {
            ID_TEXT *pulIds = (ID_TEXT *) lParam;
            _ASSERTE( pulIds );
            if ( pulIds == NULL )
            {
                return 0;
            }
            KillTimer( hWnd, 0 );
            int i = 0, ilen = 0;
            TCHAR szTempBuf[NORMAL_LOADSTRING];
            TCHAR szSpace[] =  _T(" ");
            int iTemplen;
            
            g_szCounterDisplay[0] = '\0';

            // Sort the array
            while ( 0 != pulIds[i].ulId )
            {
                i++;
            }
            for ( int j = 0; j < i; j++ )
            {
                int iminIndex = j;               
                for ( int k = j; k < i; k++ )
                {
                    if ( pulIds[iminIndex].ulId > pulIds[k].ulId )
                    {
                        iminIndex = k;
                    }
                }
                ULONG ulId = pulIds[iminIndex].ulId;
                WCHAR *pwstr = pulIds[iminIndex].pwstrCoMemText;
                pulIds[iminIndex].pwstrCoMemText = pulIds[j].pwstrCoMemText;
                pulIds[j].pwstrCoMemText = pwstr;
                pulIds[iminIndex].ulId = pulIds[j].ulId;
                pulIds[j].ulId = ulId;
            }
            
            i = 0;
            // Put in the first order words if we actually have an order
            if ( 0 != pulIds[0].ulId )
            {
                iTemplen = LoadString( g_hInst, IDS_ORDERBEGIN, szTempBuf, NORMAL_LOADSTRING );                
                _tcscat_s( g_szCounterDisplay + ilen, _countof(g_szCounterDisplay) - ilen, szTempBuf );
                ilen += iTemplen;
            }
            while ( i < MAX_ID_ARRAY && 0 != pulIds[i].ulId )
            {
                CW2T pTempStr( pulIds[i].pwstrCoMemText );

                iTemplen = lstrlen( pTempStr );
                // We'll quit now so we dont overrun the buffer
                if ( ilen + iTemplen >= MAX_LOADSTRING )
                {
                    break;
                }
                if ( i > 0 )
                {
                    _tcscat_s( g_szCounterDisplay + ilen, _countof(g_szCounterDisplay) - ilen, szSpace );
                    ilen += 1;
                }
                _tcscat_s( g_szCounterDisplay, _countof(g_szCounterDisplay), pTempStr );
                ilen += iTemplen;
                i++;
            }
            // Put the thank you on this order
            if ( 0 < i )
            {
                iTemplen = LoadString( g_hInst, IDS_ORDEREND, szTempBuf, NORMAL_LOADSTRING );                
                if ( ilen + iTemplen < MAX_LOADSTRING )
                {
                    _tcscat_s( g_szCounterDisplay + ilen, _countof(g_szCounterDisplay) - ilen, szTempBuf );
                    ilen += iTemplen;
                }
            }

            InvalidateRect( hWnd, NULL, TRUE );
            SetTimer( hWnd, 0, TIMEOUT, NULL );

            // Delete the CoTaskMem we were given initially by ISpPhrase->GetText
            i = 0;
            while ( i < MAX_ID_ARRAY && 0 != pulIds[i].ulId )
            {
                CoTaskMemFree( pulIds[i].pwstrCoMemText );
                i++;
            }
            delete [] pulIds;
            return ( 1 );
        }
        case WM_PAINT:
            CounterPanePaint( hWnd, g_szCounterDisplay );
            return ( 1 );

        case WM_INITPANE:
            LoadString( g_hInst, IDS_PLEASEORDER, g_szCounterDisplay, MAX_LOADSTRING );
            // Set the rule recognizing an espresso order to active, now that we are ready for it
            g_cpCmdGrammar->SetRuleIdState( VID_EspressoDrinks, SPRS_ACTIVE );
            // Set our interests to include false recognitions
            hr = g_cpRecoCtxt->SetInterest( SPFEI(SPEI_RECOGNITION)|SPFEI(SPEI_FALSE_RECOGNITION),
                                                    SPFEI(SPEI_RECOGNITION)|SPFEI(SPEI_FALSE_RECOGNITION) );
            _ASSERTE( SUCCEEDED( hr ) );

            return ( 1 );

        case WM_TIMER:
            // Revert back to 'go ahead and order' message
            LoadString( g_hInst, IDS_PLEASEORDER, g_szCounterDisplay, MAX_LOADSTRING );
            InvalidateRect( hWnd, NULL, TRUE );
            KillTimer( hWnd, 0 );
            return ( 1 );

        case WM_GOTOOFFICE:
            KillTimer( hWnd, 0 );
            // Set the rule recognizing an espresso order to inactive
            // since you cant order from the office
            g_cpCmdGrammar->SetRuleIdState( VID_EspressoDrinks, SPRS_INACTIVE );
            // Set our interests to include only recognitions
            hr = g_cpRecoCtxt->SetInterest( SPFEI(SPEI_RECOGNITION),SPFEI(SPEI_RECOGNITION) );
            _ASSERTE( SUCCEEDED( hr ) );
            
            // Set the right message handler and repaint
            g_fpCurrentPane = OfficePaneProc;
            PostMessage( hWnd, WM_INITPANE, NULL, NULL );
            InvalidateRect( hWnd, NULL, TRUE );
            return ( 1 );

        case WM_DIDNTUNDERSTAND:
            KillTimer( hWnd, 0 );
            LoadString( g_hInst, IDS_DIDNTUNDERSTAND, g_szCounterDisplay, MAX_LOADSTRING );
            InvalidateRect( hWnd, NULL, TRUE );
            SetTimer( hWnd, 0, TIMEOUT, NULL );
            return ( 1 );

    }
    return ( 0 );
}
Пример #23
0
/* note: only works when loopback is 48khz 2 channel floating*/
void audio_detect(void)
{
    HRESULT hr;
    REFERENCE_TIME hnsRequestedDuration = REFTIMES_PER_SEC;
    //REFERENCE_TIME hnsActualDuration;
    UINT32 bufferFrameCount;
    IMMDeviceEnumerator *pEnumerator = NULL;
    IMMDevice *pDevice = NULL;
    IMMDeviceCollection *pDeviceCollection = NULL;
    //BOOL bDone = FALSE;
    UINT count;
    //HANDLE hEvent = NULL;

    CoInitialize(NULL);

    hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &IID_IMMDeviceEnumerator, (void**)&pEnumerator);
    EXIT_ON_ERROR(hr)

    hr = pEnumerator->lpVtbl->EnumAudioEndpoints(pEnumerator, eAll, DEVICE_STATE_ACTIVE, &pDeviceCollection);
    EXIT_ON_ERROR(hr)

    hr = pDeviceCollection->lpVtbl->GetCount(pDeviceCollection, &count);
    EXIT_ON_ERROR(hr)

    printf("%u\n", count);

    hr = pEnumerator->lpVtbl->GetDefaultAudioEndpoint(pEnumerator, eRender, eConsole, &pDevice);
    EXIT_ON_ERROR(hr)

    hr = pDevice->lpVtbl->Activate(pDevice, &IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioClient);
    EXIT_ON_ERROR(hr)

    hr = pAudioClient->lpVtbl->GetMixFormat(pAudioClient, &pwfx);
    EXIT_ON_ERROR(hr)

    printf("default format: %u %u %u %lu %lu %u %u\n", WAVE_FORMAT_PCM, pwfx->wFormatTag, pwfx->nChannels, pwfx->nSamplesPerSec, pwfx->nAvgBytesPerSec, pwfx->wBitsPerSample, pwfx->nBlockAlign);

    if(pwfx->nSamplesPerSec != 48000 || pwfx->nChannels != 2 || pwfx->wFormatTag != WAVE_FORMAT_EXTENSIBLE) {
        printf("unsupported format for loopback\n");
        goto Exit;
    }

    WAVEFORMATEXTENSIBLE *wfx = (void*)pwfx;
    if(memcmp(&KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, &wfx->SubFormat, sizeof(wfx->SubFormat)) != 0) {
        goto Exit;
    }

        /* if(memcmp(&KSDATAFORMAT_SUBTYPE_PCM, &wfx->SubFormat, sizeof(wfx->SubFormat)) == 0) {
            printf("pcm\n");
        } else {
            printf("unknown\n");
        }*/

    hr = pAudioClient->lpVtbl->Initialize(pAudioClient, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK, hnsRequestedDuration, 0, pwfx, NULL);
    EXIT_ON_ERROR(hr)

    /*AUDCLNT_STREAMFLAGS_EVENTCALLBACK
    hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (hEvent == NULL)
    {
        hr = E_FAIL;
        goto Exit;
    }

    hr = pAudioClient->lpVtbl->
    EXIT_ON_ERROR(hr)*/

    // Get the size of the allocated buffer.
    hr = pAudioClient->lpVtbl->GetBufferSize(pAudioClient, &bufferFrameCount);
    EXIT_ON_ERROR(hr)

    hr = pAudioClient->lpVtbl->GetService(pAudioClient, &IID_IAudioCaptureClient_utox, (void**)&pCaptureClient);
    EXIT_ON_ERROR(hr)

    printf("%u %lu\n", bufferFrameCount, pwfx->nSamplesPerSec);

    postmessage(NEW_AUDIO_IN_DEVICE, STR_AUDIO_IN_DEFAULT_LOOPBACK, 0, (void*)(size_t)1);
    return;

Exit:
    CoTaskMemFree(pwfx);
    SAFE_RELEASE(pEnumerator)
    SAFE_RELEASE(pDevice)
    SAFE_RELEASE(pAudioClient)
    SAFE_RELEASE(pCaptureClient)

    printf("audio_init fail: %lu\n", hr);

}
Пример #24
0
void audio_thread(void *args)
{
    HRESULT hr;
    HANDLE event = 0;
    WAVEFORMATEX *fmt;
    IMMDeviceEnumerator *penum;
    IMMDevice *pdev;
    IAudioClient *acl = 0;
    IAudioRenderClient *rcl = 0;
    uint32_t padding, buf_size;
    REFERENCE_TIME defp, minp;
    //sample_t buf[audio_buffersize];
    uint8_t *data;

    CoInitialize(0);

    hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, 0, CLSCTX_ALL, &IID_IMMDeviceEnumerator,
                          (void**)&penum);
    check(hr);

    hr = penum->lpVtbl->GetDefaultAudioEndpoint(penum, eRender, eConsole, &pdev);
    release(penum);

    check(hr);

    hr = pdev->lpVtbl->Activate(pdev, &IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&acl);
    release(pdev);
    check(hr);

    hr = acl->lpVtbl->GetMixFormat(acl, &fmt);
    check(hr);

    if (fmt->wFormatTag != WAVE_FORMAT_EXTENSIBLE || fmt->nChannels != 2 ||
        fmt->nSamplesPerSec != 44100 ||
        memcmp(&KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, &((WAVEFORMATEXTENSIBLE*)fmt)->SubFormat, sizeof(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))) {
        printf("warning: unsupported output format: %u %u %lu %u\n", fmt->wFormatTag, fmt->nChannels, fmt->nSamplesPerSec, fmt->wBitsPerSample);
        goto failure;
    }

    hr = acl->lpVtbl->Initialize(acl, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
                                 500000 /* 50ms */, 0, fmt, 0);
    check(hr);

    CoTaskMemFree(fmt);

    event = CreateEvent(NULL, FALSE, FALSE, NULL);
    assert(event);

    hr = acl->lpVtbl->SetEventHandle(acl, event);
    check(hr);

    hr = acl->lpVtbl->GetBufferSize(acl, &buf_size);
    check(hr);

    hr = acl->lpVtbl->GetDevicePeriod(acl, &defp, &minp);
    check(hr);

    hr = acl->lpVtbl->GetCurrentPadding(acl, &padding);
    check(hr);

    hr = acl->lpVtbl->GetService(acl, &IID_IAudioRenderClient, (void**)&rcl);
    check(hr);

    hr = acl->lpVtbl->Start(acl);
    check(hr);

    printf("%u %u\n", buf_size, (int)defp);

    do {
        hr = acl->lpVtbl->GetCurrentPadding(acl, &padding);
        check(hr);

        if (buf_size - padding >= audio_buffersize) {
            hr = rcl->lpVtbl->GetBuffer(rcl, audio_buffersize, &data);
            check(hr);

            audio_getsamples(&audio, (sample_t*)data, audio_buffersize);

            hr = rcl->lpVtbl->ReleaseBuffer(rcl, audio_buffersize, 0);
            check(hr);
        }
    } while (WaitForSingleObject(event, 2000) == WAIT_OBJECT_0);

    printf("audio thread exit\n");

failure:
    if (rcl) release(rcl);
    if (acl) release(acl);
    if (event) CloseHandle(event);

    return;
}
Пример #25
0
// this implementation was pretty much copied verbatime from 
// Tony Robinson's code in nsExternalProtocolWin.cpp
nsresult
nsMIMEInfoWin::LoadUriInternal(nsIURI * aURL)
{
  nsresult rv = NS_OK;

  // 1. Find the default app for this protocol
  // 2. Set up the command line
  // 3. Launch the app.

  // For now, we'll just cheat essentially, check for the command line
  // then just call ShellExecute()!

  if (aURL)
  {
    // extract the url spec from the url
    nsCAutoString urlSpec;
    aURL->GetAsciiSpec(urlSpec);
 
    // Unescape non-ASCII characters in the URL
    nsCAutoString urlCharset;
    nsAutoString utf16Spec;
    rv = aURL->GetOriginCharset(urlCharset);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsITextToSubURI> textToSubURI = do_GetService(NS_ITEXTTOSUBURI_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = textToSubURI->UnEscapeNonAsciiURI(urlCharset, urlSpec, utf16Spec);
    NS_ENSURE_SUCCESS(rv, rv);

    static const PRUnichar cmdVerb[] = L"open";
    SHELLEXECUTEINFOW sinfo;
    memset(&sinfo, 0, sizeof(sinfo));
    sinfo.cbSize   = sizeof(sinfo);
    sinfo.fMask    = SEE_MASK_FLAG_DDEWAIT |
      SEE_MASK_FLAG_NO_UI;
    sinfo.hwnd     = NULL;
    sinfo.lpVerb   = (LPWSTR)&cmdVerb;
    sinfo.nShow    = SW_SHOWNORMAL;
    
    LPITEMIDLIST pidl = NULL;
    SFGAOF sfgao;
    
    // Bug 394974
    if (SUCCEEDED(SHParseDisplayName(utf16Spec.get(),NULL, &pidl, 0, &sfgao))) {
      sinfo.lpIDList = pidl;
      sinfo.fMask |= SEE_MASK_INVOKEIDLIST;
    } else {
      // SHParseDisplayName failed. Bailing out as work around for
      // Microsoft Security Bulletin MS07-061
      rv = NS_ERROR_FAILURE;
    }
    if (NS_SUCCEEDED(rv)) {
      BOOL result = ShellExecuteExW(&sinfo);
      if (!result || ((LONG_PTR)sinfo.hInstApp) < 32)
        rv = NS_ERROR_FAILURE;
    }
    if (pidl)
      CoTaskMemFree(pidl);
  }
  
  return rv;
}
Пример #26
0
static HRESULT GetSplitter(MediaDetImpl *This)
{
    IFileSourceFilter *file;
    LPOLESTR name;
    AM_MEDIA_TYPE mt;
    GUID type[2];
    IFilterMapper2 *map;
    IEnumMoniker *filters;
    IMoniker *mon;
    VARIANT var;
    GUID clsid;
    IBaseFilter *splitter;
    IEnumPins *pins;
    IPin *source_pin, *splitter_pin;
    HRESULT hr;

    hr = CoCreateInstance(&CLSID_FilterMapper2, NULL, CLSCTX_INPROC_SERVER,
                          &IID_IFilterMapper2, (void **) &map);
    if (FAILED(hr))
        return hr;

    hr = IBaseFilter_QueryInterface(This->source, &IID_IFileSourceFilter,
                                    (void **) &file);
    if (FAILED(hr))
    {
        IFilterMapper2_Release(map);
        return hr;
    }

    hr = IFileSourceFilter_GetCurFile(file, &name, &mt);
    IFileSourceFilter_Release(file);
    CoTaskMemFree(name);
    if (FAILED(hr))
    {
        IFilterMapper2_Release(map);
        return hr;
    }
    type[0] = mt.majortype;
    type[1] = mt.subtype;
    CoTaskMemFree(mt.pbFormat);

    hr = IFilterMapper2_EnumMatchingFilters(map, &filters, 0, TRUE,
                                            MERIT_UNLIKELY, FALSE, 1, type,
                                            NULL, NULL, FALSE, TRUE,
                                            0, NULL, NULL, NULL);
    IFilterMapper2_Release(map);
    if (FAILED(hr))
        return hr;

    hr = E_NOINTERFACE;
    while (IEnumMoniker_Next(filters, 1, &mon, NULL) == S_OK)
    {
        hr = GetFilterInfo(mon, &clsid, &var);
        IMoniker_Release(mon);
        if (FAILED(hr))
            continue;

        hr = CoCreateInstance(&clsid, NULL, CLSCTX_INPROC_SERVER,
                              &IID_IBaseFilter, (void **) &splitter);
        if (FAILED(hr))
        {
            VariantClear(&var);
            continue;
        }

        hr = IGraphBuilder_AddFilter(This->graph, splitter, V_BSTR(&var));
        VariantClear(&var);
        This->splitter = splitter;
        if (FAILED(hr))
            goto retry;

        hr = IBaseFilter_EnumPins(This->source, &pins);
        if (FAILED(hr))
            goto retry;
        IEnumPins_Next(pins, 1, &source_pin, NULL);
        IEnumPins_Release(pins);

        hr = IBaseFilter_EnumPins(splitter, &pins);
        if (FAILED(hr))
        {
            IPin_Release(source_pin);
            goto retry;
        }
        IEnumPins_Next(pins, 1, &splitter_pin, NULL);
        IEnumPins_Release(pins);

        hr = IPin_Connect(source_pin, splitter_pin, NULL);
        IPin_Release(source_pin);
        IPin_Release(splitter_pin);
        if (SUCCEEDED(hr))
            break;

retry:
        IBaseFilter_Release(splitter);
        This->splitter = NULL;
    }

    IEnumMoniker_Release(filters);
    if (FAILED(hr))
        return hr;

    return S_OK;
}
Пример #27
0
static void DEVENUM_ReadPins(HKEY hkeyFilterClass, REGFILTER2 *rgf2)
{
    HKEY hkeyPins = NULL;
    DWORD dwPinsSubkeys, i;
    REGFILTERPINS *rgPins = NULL;

    if (RegOpenKeyExW(hkeyFilterClass, wszPins, 0, KEY_READ, &hkeyPins) != ERROR_SUCCESS)
        return ;

    if (RegQueryInfoKeyW(hkeyPins, NULL, NULL, NULL, &dwPinsSubkeys, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
                != ERROR_SUCCESS)
    {
        RegCloseKey(hkeyPins);
        return ;
    }

    if (dwPinsSubkeys)
    {
        rgPins = CoTaskMemAlloc(sizeof(REGFILTERPINS) * dwPinsSubkeys);
        if (!rgPins)
        {
            RegCloseKey(hkeyPins);
            return ;
        }
    }

    for (i = 0; i < dwPinsSubkeys; i++)
    {
        HKEY hkeyPinKey = NULL;
        WCHAR wszPinName[MAX_PATH];
        DWORD cName = sizeof(wszPinName) / sizeof(WCHAR);
        DWORD Type, cbData;
        REGFILTERPINS *rgPin = &rgPins[rgf2->u.s1.cPins];
        LONG lRet;

        rgPin->strName = NULL;
        rgPin->clsConnectsToFilter = &GUID_NULL;
        rgPin->strConnectsToPin = NULL;
        rgPin->nMediaTypes = 0;
        rgPin->lpMediaType = NULL;

        if (RegEnumKeyExW(hkeyPins, i, wszPinName, &cName, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) continue;

        if (RegOpenKeyExW(hkeyPins, wszPinName, 0, KEY_READ, &hkeyPinKey) != ERROR_SUCCESS) continue;

        rgPin->strName = CoTaskMemAlloc((strlenW(wszPinName) + 1) * sizeof(WCHAR));
        if (!rgPin->strName) goto error_cleanup;

        strcpyW(rgPin->strName, wszPinName);

        cbData = sizeof(rgPin->bMany);
        lRet = RegQueryValueExW(hkeyPinKey, wszAllowedMany, NULL, &Type, (LPBYTE)&rgPin->bMany, &cbData);
        if (lRet != ERROR_SUCCESS || Type != REG_DWORD)
            goto error_cleanup;

        cbData = sizeof(rgPin->bZero);
        lRet = RegQueryValueExW(hkeyPinKey, wszAllowedZero, NULL, &Type, (LPBYTE)&rgPin->bZero, &cbData);
        if (lRet != ERROR_SUCCESS || Type != REG_DWORD)
            goto error_cleanup;

        cbData = sizeof(rgPin->bOutput);
        lRet = RegQueryValueExW(hkeyPinKey, wszDirection, NULL, &Type, (LPBYTE)&rgPin->bOutput, &cbData);
        if (lRet != ERROR_SUCCESS || Type != REG_DWORD)
            goto error_cleanup;

        cbData = sizeof(rgPin->bRendered);
        lRet = RegQueryValueExW(hkeyPinKey, wszIsRendered, NULL, &Type, (LPBYTE)&rgPin->bRendered, &cbData);
        if (lRet != ERROR_SUCCESS || Type != REG_DWORD)
            goto error_cleanup;

        DEVENUM_ReadPinTypes(hkeyPinKey, rgPin);

        ++rgf2->u.s1.cPins;
        continue;

        error_cleanup:

        RegCloseKey(hkeyPinKey);
        if (rgPin->strName) CoTaskMemFree(rgPin->strName);
    }

    RegCloseKey(hkeyPins);

    if (rgPins && !rgf2->u.s1.cPins)
    {
        CoTaskMemFree(rgPins);
        rgPins = NULL;
    }

    rgf2->u.s1.rgPins = rgPins;
}
Пример #28
0
void AudioClient::checkPeakValues() {
    // prepare the windows environment
    CoInitialize(NULL);

    // if disabled, clean up active clients
    if (!_enablePeakValues) {
        activeClients.clear();
        return;
    }

    // lock the devices so the _inputDevices list is static
    std::unique_lock<std::mutex> lock(_deviceMutex);
    HRESULT result;

    // initialize the payload
    QList<float> peakValueList;
    for (int i = 0; i < _inputDevices.size(); ++i) {
        peakValueList.push_back(0.0f);
    }

    std::shared_ptr<IMMDeviceEnumerator> enumerator;
    {
        IMMDeviceEnumerator* pEnumerator;
        result = CoCreateInstance(
            __uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER,
            __uuidof(IMMDeviceEnumerator), (void**)&pEnumerator);
        RETURN_ON_FAIL(result);
        enumerator = std::shared_ptr<IMMDeviceEnumerator>(pEnumerator, &release<IMMDeviceEnumerator>);
    }

    std::shared_ptr<IMMDeviceCollection> endpoints;
    {
        IMMDeviceCollection* pEndpoints;
        result = enumerator->EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE, &pEndpoints);
        RETURN_ON_FAIL(result);
        endpoints = std::shared_ptr<IMMDeviceCollection>(pEndpoints, &release<IMMDeviceCollection>);
    }

    UINT count;
    {
        result = endpoints->GetCount(&count);
        RETURN_ON_FAIL(result);
    }

    IMMDevice* pDevice;
    std::shared_ptr<IMMDevice> device;
    IAudioMeterInformation* pMeterInfo;
    std::shared_ptr<IAudioMeterInformation> meterInfo;
    IAudioClient* pAudioClient;
    std::shared_ptr<IAudioClient> audioClient;
    DWORD hardwareSupport;
    LPWSTR pDeviceId = NULL;
    LPWAVEFORMATEX format;
    float peakValue;
    QString deviceName;
    int deviceIndex;
    for (UINT i = 0; i < count; ++i) {
        result = endpoints->Item(i, &pDevice);
        CONTINUE_ON_FAIL(result);
        device = std::shared_ptr<IMMDevice>(pDevice, &release<IMMDevice>);

        // if the device isn't listed through Qt, skip it
        deviceName = ::getWinDeviceName(pDevice);
        deviceIndex = 0;
        for (;  deviceIndex < _inputDevices.size(); ++deviceIndex) {
            if (deviceName == _inputDevices[deviceIndex].deviceName()) {
                break;
            }
        }
        if (deviceIndex >= _inputDevices.size()) {
            continue;
        }

        //continue;

        result = device->Activate(__uuidof(IAudioMeterInformation), CLSCTX_ALL, NULL, (void**)&pMeterInfo);
        CONTINUE_ON_FAIL(result);
        meterInfo = std::shared_ptr<IAudioMeterInformation>(pMeterInfo, &release<IAudioMeterInformation>);

        //continue;

        hardwareSupport;
        result = meterInfo->QueryHardwareSupport(&hardwareSupport);
        CONTINUE_ON_FAIL(result);

        //continue;

        // if the device has no hardware support (USB)...
        if (!(hardwareSupport & ENDPOINT_HARDWARE_SUPPORT_METER)) {
            result = device->GetId(&pDeviceId);
            CONTINUE_ON_FAIL(result);
            std::wstring deviceId(pDeviceId);
            CoTaskMemFree(pDeviceId);

            //continue;

            // ...and no active client...
            if (activeClients.find(deviceId) == activeClients.end()) {
                result = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**)&pAudioClient);
                CONTINUE_ON_FAIL(result);
                audioClient = std::shared_ptr<IAudioClient>(pAudioClient, &release<IAudioClient>);

                //continue;

                // ...activate a client
                audioClient->GetMixFormat(&format);
                audioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, 0, 0, format, NULL);
                audioClient->Start();

                //continue;

                activeClients[deviceId] = audioClient;
            }
        }

        // get the peak value and put it in the payload
        meterInfo->GetPeakValue(&peakValue);
        peakValueList[deviceIndex] = peakValue;
    }

    emit peakValueListChanged(peakValueList);
}
Пример #29
0
/**********************************************************************
 * DEVENUM_CreateSpecialCategories (INTERNAL)
 *
 * Creates the keys in the registry for the dynamic categories
 */
static HRESULT DEVENUM_CreateSpecialCategories(void)
{
    HRESULT res;
    WCHAR szDSoundNameFormat[MAX_PATH + 1];
    WCHAR szDSoundName[MAX_PATH + 1];
    DWORD iDefaultDevice = -1;
    UINT numDevs;
    IFilterMapper2 * pMapper = NULL;
    REGFILTER2 rf2;
    REGFILTERPINS2 rfp2;
    WCHAR path[MAX_PATH];
    HKEY basekey;

    if (DEVENUM_populate_handle)
        return S_OK;
    DEVENUM_populate_handle = CreateEventW(NULL, TRUE, FALSE, DEVENUM_populate_handle_nameW);
    if (GetLastError() == ERROR_ALREADY_EXISTS)
    {
        /* Webcams can take some time to scan if the driver is badly written and it enables them,
         * so have a 10 s timeout here
         */
        if (WaitForSingleObject(DEVENUM_populate_handle, 10000) == WAIT_TIMEOUT)
            WARN("Waiting for object timed out\n");
        TRACE("No need to rescan\n");
        return S_OK;
    }
    TRACE("Scanning for devices\n");

    /* Since devices can change between session, for example because you just plugged in a webcam
     * or switched from pulseaudio to alsa, delete all old devices first
     */
    if (SUCCEEDED(DEVENUM_GetCategoryKey(&CLSID_AudioRendererCategory, &basekey, path, MAX_PATH)))
        RegDeleteTreeW(basekey, path);
    if (SUCCEEDED(DEVENUM_GetCategoryKey(&CLSID_AudioInputDeviceCategory, &basekey, path, MAX_PATH)))
        RegDeleteTreeW(basekey, path);
    if (SUCCEEDED(DEVENUM_GetCategoryKey(&CLSID_VideoInputDeviceCategory, &basekey, path, MAX_PATH)))
        RegDeleteTreeW(basekey, path);
    if (SUCCEEDED(DEVENUM_GetCategoryKey(&CLSID_MidiRendererCategory, &basekey, path, MAX_PATH)))
        RegDeleteTreeW(basekey, path);
    if (SUCCEEDED(DEVENUM_GetCategoryKey(&CLSID_VideoCompressorCategory, &basekey, path, MAX_PATH)))
        RegDeleteTreeW(basekey, path);

    rf2.dwVersion = 2;
    rf2.dwMerit = MERIT_PREFERRED;
    rf2.u.s2.cPins2 = 1;
    rf2.u.s2.rgPins2 = &rfp2;
    rfp2.cInstances = 1;
    rfp2.nMediums = 0;
    rfp2.lpMedium = NULL;
    rfp2.clsPinCategory = &IID_NULL;

    if (!LoadStringW(DEVENUM_hInstance, IDS_DEVENUM_DS, szDSoundNameFormat, sizeof(szDSoundNameFormat)/sizeof(szDSoundNameFormat[0])-1))
    {
        ERR("Couldn't get string resource (GetLastError() is %d)\n", GetLastError());
        return HRESULT_FROM_WIN32(GetLastError());
    }

    res = CoCreateInstance(&CLSID_FilterMapper2, NULL, CLSCTX_INPROC,
                           &IID_IFilterMapper2, (void **) &pMapper);
    /*
     * Fill in info for devices
     */
    if (SUCCEEDED(res))
    {
        UINT i;
        WAVEOUTCAPSW wocaps;
	WAVEINCAPSW wicaps;
        MIDIOUTCAPSW mocaps;
        REGPINTYPES * pTypes;
        IPropertyBag * pPropBag = NULL;

	numDevs = waveOutGetNumDevs();

        res = DEVENUM_CreateAMCategoryKey(&CLSID_AudioRendererCategory);
        if (FAILED(res)) /* can't register any devices in this category */
            numDevs = 0;

	rfp2.dwFlags = REG_PINFLAG_B_RENDERER;
	for (i = 0; i < numDevs; i++)
	{
	    if (waveOutGetDevCapsW(i, &wocaps, sizeof(WAVEOUTCAPSW))
	        == MMSYSERR_NOERROR)
	    {
                IMoniker * pMoniker = NULL;

                rfp2.nMediaTypes = 1;
                pTypes = CoTaskMemAlloc(rfp2.nMediaTypes * sizeof(REGPINTYPES));
                if (!pTypes)
                {
                    IFilterMapper2_Release(pMapper);
                    return E_OUTOFMEMORY;
                }
                /* FIXME: Native devenum seems to register a lot more types for
                 * DSound than we do. Not sure what purpose they serve */
                pTypes[0].clsMajorType = &MEDIATYPE_Audio;
                pTypes[0].clsMinorType = &MEDIASUBTYPE_PCM;

                rfp2.lpMediaType = pTypes;

                res = IFilterMapper2_RegisterFilter(pMapper,
		                              &CLSID_AudioRender,
					      wocaps.szPname,
					      &pMoniker,
					      &CLSID_AudioRendererCategory,
					      wocaps.szPname,
					      &rf2);

                if (pMoniker)
                {
                    VARIANT var;

                    V_VT(&var) = VT_I4;
                    V_I4(&var) = i;
                    res = IMoniker_BindToStorage(pMoniker, NULL, NULL, &IID_IPropertyBag, (LPVOID)&pPropBag);
                    if (SUCCEEDED(res))
                        res = IPropertyBag_Write(pPropBag, wszWaveOutID, &var);
                    else
                        pPropBag = NULL;

                    V_VT(&var) = VT_LPWSTR;
                    V_BSTR(&var) = wocaps.szPname;
                    if (SUCCEEDED(res))
                        res = IPropertyBag_Write(pPropBag, wszFriendlyName, &var);
                    if (pPropBag)
                        IPropertyBag_Release(pPropBag);
                    IMoniker_Release(pMoniker);
                    pMoniker = NULL;
                }

		wsprintfW(szDSoundName, szDSoundNameFormat, wocaps.szPname);
	        res = IFilterMapper2_RegisterFilter(pMapper,
		                              &CLSID_DSoundRender,
					      szDSoundName,
					      &pMoniker,
					      &CLSID_AudioRendererCategory,
					      szDSoundName,
					      &rf2);

                /* FIXME: do additional stuff with IMoniker here, depending on what RegisterFilter does */

		if (pMoniker)
		    IMoniker_Release(pMoniker);

		if (i == iDefaultDevice)
		{
		    FIXME("Default device\n");
		}

                CoTaskMemFree(pTypes);
	    }
	}

        numDevs = waveInGetNumDevs();

        res = DEVENUM_CreateAMCategoryKey(&CLSID_AudioInputDeviceCategory);
        if (FAILED(res)) /* can't register any devices in this category */
            numDevs = 0;

	rfp2.dwFlags = REG_PINFLAG_B_OUTPUT;
        for (i = 0; i < numDevs; i++)
        {
            if (waveInGetDevCapsW(i, &wicaps, sizeof(WAVEINCAPSW))
                == MMSYSERR_NOERROR)
            {
                IMoniker * pMoniker = NULL;

                rfp2.nMediaTypes = 1;
                pTypes = CoTaskMemAlloc(rfp2.nMediaTypes * sizeof(REGPINTYPES));
                if (!pTypes)
                {
                    IFilterMapper2_Release(pMapper);
                    return E_OUTOFMEMORY;
                }

                /* FIXME: Not sure if these are correct */
                pTypes[0].clsMajorType = &MEDIATYPE_Audio;
                pTypes[0].clsMinorType = &MEDIASUBTYPE_PCM;

                rfp2.lpMediaType = pTypes;

                res = IFilterMapper2_RegisterFilter(pMapper,
		                              &CLSID_AudioRecord,
					      wicaps.szPname,
					      &pMoniker,
					      &CLSID_AudioInputDeviceCategory,
					      wicaps.szPname,
					      &rf2);


                if (pMoniker) {
                    VARIANT var;

                    V_VT(&var) = VT_I4;
                    V_I4(&var) = i;
                    res = IMoniker_BindToStorage(pMoniker, NULL, NULL, &IID_IPropertyBag, (LPVOID)&pPropBag);
                    if (SUCCEEDED(res))
                        res = IPropertyBag_Write(pPropBag, wszWaveInID, &var);
                    else
                        pPropBag = NULL;

                    V_VT(&var) = VT_LPWSTR;
                    V_BSTR(&var) = wicaps.szPname;
                    if (SUCCEEDED(res))
                        res = IPropertyBag_Write(pPropBag, wszFriendlyName, &var);

                    if (pPropBag)
                        IPropertyBag_Release(pPropBag);
                    IMoniker_Release(pMoniker);
                }

                CoTaskMemFree(pTypes);
	    }
	}

	numDevs = midiOutGetNumDevs();

        res = DEVENUM_CreateAMCategoryKey(&CLSID_MidiRendererCategory);
        if (FAILED(res)) /* can't register any devices in this category */
            numDevs = 0;

	rfp2.dwFlags = REG_PINFLAG_B_RENDERER;
	for (i = 0; i < numDevs; i++)
	{
	    if (midiOutGetDevCapsW(i, &mocaps, sizeof(MIDIOUTCAPSW))
	        == MMSYSERR_NOERROR)
	    {
                IMoniker * pMoniker = NULL;

                rfp2.nMediaTypes = 1;
                pTypes = CoTaskMemAlloc(rfp2.nMediaTypes * sizeof(REGPINTYPES));
                if (!pTypes)
                {
                    IFilterMapper2_Release(pMapper);
                    return E_OUTOFMEMORY;
                }

                /* FIXME: Not sure if these are correct */
                pTypes[0].clsMajorType = &MEDIATYPE_Midi;
                pTypes[0].clsMinorType = &MEDIASUBTYPE_None;

                rfp2.lpMediaType = pTypes;

                res = IFilterMapper2_RegisterFilter(pMapper,
		                              &CLSID_AVIMIDIRender,
					      mocaps.szPname,
					      &pMoniker,
					      &CLSID_MidiRendererCategory,
					      mocaps.szPname,
					      &rf2);

                /* FIXME: do additional stuff with IMoniker here, depending on what RegisterFilter does */
		/* Native version sets MidiOutId */

		if (pMoniker)
		    IMoniker_Release(pMoniker);

		if (i == iDefaultDevice)
		{
		    FIXME("Default device\n");
		}

                CoTaskMemFree(pTypes);
	    }
	}
        res = DEVENUM_CreateAMCategoryKey(&CLSID_VideoInputDeviceCategory);
        if (SUCCEEDED(res))
            for (i = 0; i < 10; i++)
            {
                WCHAR szDeviceName[32], szDeviceVersion[32], szDevicePath[10];

                if (capGetDriverDescriptionW ((WORD) i,
                                              szDeviceName, sizeof(szDeviceName)/sizeof(WCHAR),
                                              szDeviceVersion, sizeof(szDeviceVersion)/sizeof(WCHAR)))
                {
                    IMoniker * pMoniker = NULL;
                    WCHAR dprintf[] = { 'v','i','d','e','o','%','d',0 };
                    snprintfW(szDevicePath, sizeof(szDevicePath)/sizeof(WCHAR), dprintf, i);
                    /* The above code prevents 1 device with a different ID overwriting another */

                    rfp2.nMediaTypes = 1;
                    pTypes = CoTaskMemAlloc(rfp2.nMediaTypes * sizeof(REGPINTYPES));
                    if (!pTypes) {
                        IFilterMapper2_Release(pMapper);
                        return E_OUTOFMEMORY;
                    }

                    pTypes[0].clsMajorType = &MEDIATYPE_Video;
                    pTypes[0].clsMinorType = &MEDIASUBTYPE_None;

                    rfp2.lpMediaType = pTypes;

                    res = IFilterMapper2_RegisterFilter(pMapper,
                                                        &CLSID_VfwCapture,
                                                        szDeviceName,
                                                        &pMoniker,
                                                        &CLSID_VideoInputDeviceCategory,
                                                        szDevicePath,
                                                        &rf2);

                    if (pMoniker) {
                       OLECHAR wszVfwIndex[] = { 'V','F','W','I','n','d','e','x',0 };
                       VARIANT var;
                       V_VT(&var) = VT_I4;
                       V_I4(&var) = i;
                       res = IMoniker_BindToStorage(pMoniker, NULL, NULL, &IID_IPropertyBag, (LPVOID)&pPropBag);
                       if (SUCCEEDED(res)) {
                           res = IPropertyBag_Write(pPropBag, wszVfwIndex, &var);
                           IPropertyBag_Release(pPropBag);
                       }
                       IMoniker_Release(pMoniker);
                    }

                    if (i == iDefaultDevice) FIXME("Default device\n");
                    CoTaskMemFree(pTypes);
                }
            }
    }

    if (pMapper)
        IFilterMapper2_Release(pMapper);

    register_vfw_codecs();

    SetEvent(DEVENUM_populate_handle);
    return res;
}
Пример #30
0
HRESULT LogAttributeValueByIndexNew(IMFAttributes *pAttr, DWORD index, MfVideoCapture::MediaType &out)
{
    WCHAR *pGuidName = NULL;
    WCHAR *pGuidValName = NULL;

    GUID guid = { 0 };

    PROPVARIANT var;
    PropVariantInit(&var);

    HRESULT hr = pAttr->GetItemByIndex(index, &guid, &var);

    if (FAILED(hr))
    {
        goto done;
    }

    hr = GetGUIDNameNew(guid, &pGuidName);

    if (FAILED(hr))
    {
        goto done;
    }

    hr = SpecialCaseAttributeValueNew(guid, var, out);

    unsigned int *p;

    if (FAILED(hr))
    {
        goto done;
    }
    if (hr == S_FALSE)
    {
        switch (var.vt)
        {
        case VT_UI4:

            p = GetParameter(guid, out);

            if(p)
            {
                *p = var.ulVal;
            }

            break;

        case VT_UI8:

            break;

        case VT_R8:

            break;

        case VT_CLSID:
            if(guid == MF_MT_AM_FORMAT_TYPE)
            {
                hr = GetGUIDNameNew(*var.puuid, &pGuidValName);

                if (SUCCEEDED(hr))
                {
                    out.MF_MT_AM_FORMAT_TYPE = MF_MT_AM_FORMAT_TYPE;

                    out.MF_MT_AM_FORMAT_TYPEName = std::wstring(pGuidValName);

                    pGuidValName = NULL;
                }
            }

            if(guid == MF_MT_MAJOR_TYPE)
            {
                hr = GetGUIDNameNew(*var.puuid, &pGuidValName);

                if (SUCCEEDED(hr))
                {
                    out.MF_MT_MAJOR_TYPE = MF_MT_MAJOR_TYPE;

                    out.MF_MT_MAJOR_TYPEName = std::wstring(pGuidValName);

                    pGuidValName = NULL;
                }
            }

            if(guid == MF_MT_SUBTYPE)
            {
                hr = GetGUIDNameNew(*var.puuid, &pGuidValName);

                if (SUCCEEDED(hr))
                {
                    out.MF_MT_SUBTYPE = MF_MT_SUBTYPE;

                    out.MF_MT_SUBTYPEName = std::wstring(pGuidValName);

                    pGuidValName = NULL;
                }
            }

            break;

        case VT_LPWSTR:

            break;

        case VT_VECTOR | VT_UI1:

            break;

        case VT_UNKNOWN:

            break;

        default:

            break;
        }
    }

done:
    CoTaskMemFree(pGuidName);
    CoTaskMemFree(pGuidValName);
    PropVariantClear(&var);
    return hr;
}