Exemplo n.º 1
0
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
  TCHAR *cmdline;
  TCHAR seekchar = _T(' ');
  TCHAR *keyname, *file;

  // These are turned into heap memory to avoid _chkstk
  keyname = (TCHAR*) GlobalAlloc(GPTR, STR_SIZE*sizeof(TCHAR));
  file    = (TCHAR*) GlobalAlloc(GPTR, STR_SIZE*sizeof(TCHAR));

  cmdline = GetCommandLine();
  if (*cmdline == _T('\"'))
    seekchar = *cmdline++;

  while (*cmdline && *cmdline != seekchar)
    cmdline = CharNext(cmdline);
  cmdline = CharNext(cmdline);
  while (*cmdline == _T(' '))
    cmdline++;

  if (*cmdline++ != _T('/'))
  {
    ExitProcess(1);
    return 0;
  }

  if (*cmdline == _T('S'))
  {
    HKEY rootkey;

    if (SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\NSIS.Library.RegTool.v3"), 0, KEY_READ, &rootkey)))
    {
      while (RegEnumKey(rootkey, 0, keyname, STR_SIZE) == ERROR_SUCCESS)
      {
        HKEY key;

        if (SUCCEEDED(RegOpenKeyEx(rootkey, keyname, 0, KEY_READ, &key)))
        {
          DWORD t, count, l = sizeof(DWORD);

          if (SUCCEEDED(RegQueryValueEx(key, _T("count"), NULL, &t, (LPBYTE) &count, &l)) && t == REG_DWORD)
          {
            DWORD j;
            TCHAR valname[128], mode[3];

            for (j = 1; j <= count; j++)
            {
              wsprintf(valname, _T("%u.mode"), j);
              l = sizeof(mode);
              if (FAILED(RegQueryValueEx(key, valname, NULL, &t, (LPBYTE) mode, &l)) || t != REG_SZ)
                continue;

              wsprintf(valname, _T("%u.file"), j);
              l = STR_SIZE*sizeof(TCHAR);
              if (FAILED(RegQueryValueEx(key, valname, NULL, &t, (LPBYTE) file, &l)) || t != REG_SZ)
                continue;

              file[STR_SIZE - 1] = 0;

              // JP: Note, if this mode[1] is used as anything but a boolean later on,
              // we'll need to consider the next line carefully.
              RegFile(mode[0], file, mode[1] == 'X');
            }
          }

          RegCloseKey(key);
          RegDeleteKey(rootkey, keyname);
        }
      }

      RegCloseKey(rootkey);
      RegDeleteKey(HKEY_LOCAL_MACHINE, _T("Software\\NSIS.Library.RegTool.v3"));
    }

    {
      if (GetModuleFileName(GetModuleHandle(NULL), file, STR_SIZE))
      {
        DeleteFileOnReboot(file);
      }
    }
  }
  else
  {
    SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
    OleInitialize(NULL);

    if (*cmdline == _T('D'))
    {
      RegDll(cmdline + 1);
    }
    else if (*cmdline == _T('T'))
    {
      RegTypeLib(cmdline + 1);
    }

    OleUninitialize();
    SetErrorMode(0);
  }

  GlobalFree(keyname);
  GlobalFree(file);
  ExitProcess(0);
  return 0;
}
Exemplo n.º 2
0
char* GetAccountTypeHelper(BOOL CheckTokenForGroupDeny) 
{
  char  *group = NULL;
  HANDLE  hToken = NULL;
  struct group
  {
    DWORD auth_id;
    char *name;
  };

  struct group groups[] = 
  {
    {DOMAIN_ALIAS_RID_USERS, "User"},
    // every user belongs to the users group, hence users come before guests
    {DOMAIN_ALIAS_RID_GUESTS, "Guest"},
    {DOMAIN_ALIAS_RID_POWER_USERS, "Power"},
    {DOMAIN_ALIAS_RID_ADMINS, "Admin"}
  };

  if (GetVersion() & 0x80000000) // Not NT
  {
    return "Admin";
  }

  // First we must open a handle to the access token for this thread.
  if (OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken) ||
    OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
  {
    SID_IDENTIFIER_AUTHORITY SystemSidAuthority = {SECURITY_NT_AUTHORITY};
    TOKEN_GROUPS  *ptg          = NULL;
    BOOL       ValidTokenGroups = FALSE;
    DWORD      cbTokenGroups;
    DWORD      i, j;
    
    
    if (CheckTokenForGroupDeny)
      // GetUserName is in advapi32.dll so we can avoid Load/Freelibrary
      _CheckTokenMembership=
        (CHECKTOKENMEMBERSHIP) GetProcAddress(
          GetModuleHandle("ADVAPI32"), "CheckTokenMembership");
    
    // Use "old school" membership check?
    if (!CheckTokenForGroupDeny || _CheckTokenMembership == NULL)
    {
      // We must query the size of the group information associated with
      // the token. Note that we expect a FALSE result from GetTokenInformation
      // because we've given it a NULL buffer. On exit cbTokenGroups will tell
      // the size of the group information.
      if (!GetTokenInformation(hToken, TokenGroups, NULL, 0, &cbTokenGroups) &&
        GetLastError() == ERROR_INSUFFICIENT_BUFFER)
      {
        // Allocate buffer and ask for the group information again.
        // This may fail if an administrator has added this account
        // to an additional group between our first call to
        // GetTokenInformation and this one.
        if ((ptg = GlobalAlloc(GPTR, cbTokenGroups)) &&
          GetTokenInformation(hToken, TokenGroups, ptg, cbTokenGroups, &cbTokenGroups))
        {
          ValidTokenGroups=TRUE;
        }
      }
    }
    
    if (ValidTokenGroups || (CheckTokenForGroupDeny && _CheckTokenMembership))
    {
      PSID psid;
      for (i = 0; i < sizeof(groups)/sizeof(struct group); i++)
      {
        // Create a SID for the local group and then check if it exists in our token
        if (AllocateAndInitializeSid(
          &SystemSidAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
          groups[i].auth_id, 0, 0, 0, 0, 0, 0,&psid))
        {
          BOOL IsMember = FALSE;
          if (CheckTokenForGroupDeny && _CheckTokenMembership)
          {
            _CheckTokenMembership(0, psid, &IsMember);
          }
          else if (ValidTokenGroups)
          {
            for (j = 0; j < ptg->GroupCount; j++)
            {
              if (EqualSid(ptg->Groups[j].Sid, psid))
              {
                IsMember = TRUE;
              }
            }
          }
          
          if (IsMember) group=groups[i].name;
          FreeSid(psid);
        }
      }
    }

    if (ptg)
      GlobalFree(ptg);
    CloseHandle(hToken);

    return group;
  }

  return "";
}
Exemplo n.º 3
0
void __declspec(dllexport) LangDialog(HWND hwndParent, int string_size, 
                                      char *variables, stack_t **stacktop)
{
  g_hwndParent=hwndParent;
  EXDLL_INIT();

  {
    int i;
    int doauto = 0;
    BOOL pop_empty_string = FALSE;

    // get texts
    if (popstring(g_wndtitle)) return;
    if (popstring(g_wndtext)) return;

    // get flags
    if (popstring(temp)) return;

    // parse flags
    {
      char *p=temp;
      while (*p)
      {
        if (*p == 'A') doauto=1; // parse auto count flag
        if (*p == 'F') dofont=1; // parse font flag
        if (*p == 'C') docp=1;   // parse codepage flag
        p++;
      }
    }
 
    if (doauto) {
      // automatic language count
      stack_t *th;
      langs_num=0;
      th=(*g_stacktop);
      while (th && th->text[0]) {
        langs_num++;
        th = th->next;
      }
      if (!th) return;
      if (docp)
        langs_num /= 3;
      else
        langs_num /= 2;
      pop_empty_string = TRUE;
    } else {
      // use counts languages
      langs_num = myatou(temp);
    }

    // zero languages?
    if (!langs_num) return;

    // initialize visible languages count
    visible_langs_num = 0;

    // allocate language struct
    langs = (struct lang *)GlobalAlloc(GPTR, langs_num*sizeof(struct lang));
    if (!langs) return;

    // fill language struct
    for (i = 0; i < langs_num; i++) {
      if (popstring(temp)) { visible_langs_num = 0; break; }
      langs[visible_langs_num].name = GlobalAlloc(GPTR, lstrlen(temp)+1);
      if (!langs[visible_langs_num].name) { visible_langs_num = 0; break; }
      lstrcpy(langs[visible_langs_num].name, temp);

      if (popstring(temp)) { visible_langs_num = 0; break; }
      langs[visible_langs_num].id = GlobalAlloc(GPTR, lstrlen(temp)+1);
      if (!langs[visible_langs_num].id) { visible_langs_num = 0; break; }
      lstrcpy(langs[visible_langs_num].id, temp);

      if (docp)
      {
        if (popstring(temp)) { visible_langs_num = 0; break; }
        langs[visible_langs_num].cp = myatou(temp);
      }

      if (!docp || langs[visible_langs_num].cp == GetACP() || langs[visible_langs_num].cp == 0)
      {
        visible_langs_num++;
      }
      else
      {
        GlobalFree(langs[visible_langs_num].name);
        GlobalFree(langs[visible_langs_num].id);
      }
    }

    // pop the empty string to keep the stack clean
    if (pop_empty_string) {
      if (popstring(temp)) {
        visible_langs_num = 0;
      }
    }

    // start dialog
    if (visible_langs_num > 1)
    {
      DialogBox(g_hInstance, MAKEINTRESOURCE(IDD_DIALOG), 0, DialogProc);
    }
    else if (visible_langs_num == 0)
    {
      pushstring("");
    }
    else
    {
      pushstring(langs[0].id);
    }

    // free structs
    for (i = 0; i < visible_langs_num; i++) {
      if (langs[i].name) GlobalFree(langs[i].name);
      if (langs[i].id) GlobalFree(langs[i].id);
    }
    GlobalFree(langs);
  }
}
  //
  // Entry point for conversion
  //
UT_Error IE_ImpGraphic_Win32Native::_convertGraphic(UT_ByteBuf * pBB, std::string& mimetype)
{	
    IPicture* pPicture = NULL;
    IStream* stream;	
    HGLOBAL hG;		
    HBITMAP hBitmap;
    OLE_HANDLE* hB;
    PBITMAPINFO	bi;
    UT_ByteBuf bBufBMP;
    UT_Error err;	

	/* If the system has GDI+, use it*/
	if (isGDIPlusAvailable())
	{
		m_pBB = new UT_ByteBuf();
		return GDIconvertGraphic(pBB, m_pBB, mimetype);		
	}

	// the code below always writes out PNG's for now; we could update it to support
	// native JPEG images as well, or just delete it and always use GDI+.
	mimetype = "image/png";

    // We need to store the incoming bytebuffer in a Windows global heap	
    size_t nBlockLen = pBB->getLength();   	
    hG = GlobalAlloc(GPTR, nBlockLen);
    if (!hG) 
		return UT_IE_NOMEMORY;	
    
    CopyMemory(hG, pBB->getPointer(0), nBlockLen);   	
    
    // Create a stream from heap
    HRESULT hr = CreateStreamOnHGlobal(hG,false,&stream);
    if (!SUCCEEDED(hr) || !stream)
	{
		GlobalFree(hG);
		return UT_IE_NOMEMORY;
	}
    
    hr = OleLoadPicture(stream,0,false,IID_IPicture,(void**)&pPicture);	

    stream->Release();
    GlobalFree(hG);
    
    if (!SUCCEEDED(hr) || !pPicture)
	{
		return UT_IE_UNKNOWNTYPE;
	}

    pPicture->get_Handle((unsigned int*)&hB);
    
    hBitmap = (HBITMAP)CopyImage(hB,IMAGE_BITMAP,0,0,LR_COPYRETURNORG);
    
    HWND hWnd = GetDesktopWindow();
    
    // Create a BMP file from a BITMAP	
    bi = CreateBitmapInfoStruct(hBitmap);						
    CreateBMPFile(hWnd, bBufBMP, bi, hBitmap, GetDC(hWnd));
    LocalFree ((HLOCAL)bi);
    
    InitializePrivateClassData();
    
    /* Read Header Data */
    err = Read_BMP_Header(&bBufBMP);
	
	/* 
	   It's not a bitmap, then we have to rendered it into a device
	   context and get a bitmap from there. Case wmf graphics
	*/
	if (err) 
	{
		if (err!=UT_IE_BOGUSDOCUMENT) 
		{
			pPicture->Release();
			return err;		
		}
		
        long nWidth  = 0;
        long nHeight = 0;
		long nScaleToWidth= 500;
		long nScaleToHeight= 500;		
		RECT rc, rect;				
		BYTE *imagedata;
		HBITMAP hBit;
		HBITMAP hOld;
		BITMAPINFO bmi; 		
		HDC hWndDC = GetDC(hWnd);
		HDC	hMemDC = CreateCompatibleDC(hWndDC);
		HBRUSH hBrush = (HBRUSH)GetCurrentObject(hMemDC, OBJ_BRUSH);
		
		pPicture->get_Width (&nWidth);
		pPicture->get_Height(&nHeight);

		bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); 	
		bmi.bmiHeader.biWidth = nScaleToWidth;
		bmi.bmiHeader.biHeight = nScaleToHeight;
		bmi.bmiHeader.biPlanes = 1; 
		bmi.bmiHeader.biBitCount = 24; // as we want true-color
		bmi.bmiHeader.biCompression = BI_RGB; // no compression
		bmi.bmiHeader.biSizeImage = (((bmi.bmiHeader.biWidth * bmi.bmiHeader.biBitCount + 31) & ~31) >> 3) * bmi.bmiHeader.biHeight; 
		bmi.bmiHeader.biXPelsPerMeter = 0;
		bmi.bmiHeader.biYPelsPerMeter = 0; 
		bmi.bmiHeader.biClrImportant = 0;
		bmi.bmiHeader.biClrUsed = 0; // we are not using palette
			
		hBit = CreateDIBSection(hMemDC,&bmi,DIB_RGB_COLORS,(void**)&imagedata,0,0);						
		hOld = (HBITMAP) SelectObject(hMemDC, hBit);			

		
		rect.left = 0;
        rect.top = nScaleToHeight;
        rect.right = nScaleToWidth;
        rect.bottom = 0;

		FillRect(hMemDC, &rect,  hBrush);
		pPicture->Render(hMemDC, 0,0,  nScaleToWidth,	nScaleToHeight, 0,  nHeight, 
						 nWidth, -nHeight, &rc);	
		
		hBit =  (HBITMAP)SelectObject(hMemDC, hOld);
		
		bi =  CreateBitmapInfoStruct(hBit);						
		CreateBMPFile(hWnd, bBufBMP, &bmi, hBit, hMemDC);
		LocalFree ((HLOCAL)bi);

		
		DeleteDC(hMemDC);
		DeleteDC(hWndDC);
	    DeleteObject(hBrush); 
		DeleteObject(hBit);	  
    
		err = Read_BMP_Header(&bBufBMP);
		if (err) 
		{
			pPicture->Release();
			return err;				
		}
		
	}

	pPicture->Release();


    if ((err = Initialize_PNG()))
	{   
		return err;
	}	
    
    /* Read Palette, if no palette set Header accordingly */
    if(m_iBitsPerPlane < 24) 
	{
		if ((err = Convert_BMP_Palette(&bBufBMP))) 
			return err;
	}
    else
	{
		UT_uint16 bitsPerChannel;
		UT_uint16 colorType;

		if (m_iBitsPerPlane == 24) {
			bitsPerChannel = 8;
			colorType = PNG_COLOR_TYPE_RGB;
		} else if (m_iBitsPerPlane == 32) {
			bitsPerChannel = 8;
			colorType = PNG_COLOR_TYPE_RGB_ALPHA;
		} else if (m_iBitsPerPlane == 48) {
			bitsPerChannel = 16;
			colorType = PNG_COLOR_TYPE_RGB;
		} else if (m_iBitsPerPlane == 64) {
			bitsPerChannel = 16;
			colorType = PNG_COLOR_TYPE_RGB_ALPHA;
		} else {		   
			return UT_ERROR;
		}
	
		png_set_IHDR ( m_pPNG,
					   m_pPNGInfo,
					   m_iWidth,
					   m_iHeight,
					   bitsPerChannel,
					   colorType,
					   PNG_INTERLACE_NONE,
					   PNG_COMPRESSION_TYPE_DEFAULT,
					   PNG_FILTER_TYPE_DEFAULT );
	
	}
    if ((err = Convert_BMP(&bBufBMP))) 
	{
		return err;
	}
    
    /* Clean Up Memory Used */
		
    //FREEP(m_pPNGInfo->palette);
    png_destroy_write_struct(&m_pPNG, &m_pPNGInfo);
    
    return UT_OK;  	  	
}
Exemplo n.º 5
0
void operator delete( void *p ) { if (p) GlobalFree(p); }
Exemplo n.º 6
0
int MyOpen(HWND hEdit)
{
    int id;
    HWND hMain;
    DWORD dwSize = 0L;
    OPENFILENAME ofn;
    HANDLE hFile;
    DWORD dwAccBytes;
    LPTSTR lpszBuf;

    HGLOBAL hMem;

    id = MyConfirm(hEdit);
    if (id == IDCANCEL)
        return -1;

    // OPENFILENAME構造体を設定
    memset(&ofn, 0, sizeof(OPENFILENAME));
    ofn.lStructSize = sizeof(OPENFILENAME);
    ofn.hwndOwner = hEdit;
    ofn.lpstrFilter =
        TEXT("text(*.txt)\0*.txt\0All files(*.*)\0*.*\0\0");
    ofn.lpstrFile = szFile;
    ofn.lpstrFileTitle = szFileTitle;
    ofn.nMaxFile = MAX_PATH;
    ofn.nMaxFileTitle = MAX_PATH;
    ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
    ofn.lpstrDefExt = TEXT("txt");
    ofn.lpstrTitle = TEXT("猫でもわかるファイルオープン");

    if(GetOpenFileName(&ofn) == 0)  // 「ファイルを開く」ダイアログ
        return -1;

    hFile = CreateFile(szFile,  // ファイル名
        GENERIC_READ,           // 読み取り/書き込みアクセス
        0,                      // 共有設定 0だと共有対象としない
        NULL,                   // セキュリティ属性
        OPEN_ALWAYS,            // ファイルがすでに存在しているかどうか
        FILE_ATTRIBUTE_NORMAL,  // ファイル属性
        NULL);
    dwSize = GetFileSize(hFile, NULL);  // ファイルサイズを取得

    // メモリを動的に確保
    hMem = GlobalAlloc(GHND, dwSize + sizeof(TCHAR));
    if (hMem == NULL) {
        MessageBox(hEdit, TEXT("メモリを確保できません"),
                   TEXT("猫でもわかるメモ帳もどき"),
                   MB_ICONEXCLAMATION | MB_OK);
        return -1;
    }
    lpszBuf = (LPTSTR)GlobalLock(hMem);

    // ファイルを読み込み、エディットコントロールに表示する
    ReadFile(hFile, lpszBuf, dwSize, &dwAccBytes, NULL);
    lpszBuf[dwAccBytes] = TEXT('\0');
    Edit_SetText(hEdit, lpszBuf);

    // タイトルバーの設定
    wsprintf(szTitle, szTitle_org, szFileTitle, dwSize);
    hMain = GetParent(hEdit);
    SetWindowText(hMain, szTitle);

    CloseHandle(hFile);
    GlobalUnlock(hMem);
    GlobalFree(hMem);

    return 0;
}
Exemplo n.º 7
0
void PrintingCleanup(void)
{
    if (hDevNames) GlobalFree(hDevNames);
    if (hDevMode)  GlobalFree(hDevMode);
}
Exemplo n.º 8
0
/** Print out a stacktrace. */
static void Stacktrace(LPEXCEPTION_POINTERS e, HANDLE hThread = INVALID_HANDLE_VALUE) {
	PIMAGEHLP_SYMBOL pSym;
	STACKFRAME sf;
	HANDLE process, thread;
	DWORD dwModBase, Disp;
	BOOL more = FALSE;
	int count = 0;
	char modname[MAX_PATH];

	pSym = (PIMAGEHLP_SYMBOL)GlobalAlloc(GMEM_FIXED, 16384);

	BOOL suspended = FALSE;
	CONTEXT c;
	if (e) {
		c = *e->ContextRecord;
		thread = GetCurrentThread();
	} else {
		SuspendThread(hThread);
		suspended = TRUE;
		memset(&c, 0, sizeof(CONTEXT));
		c.ContextFlags = CONTEXT_FULL;
		// FIXME: This does not work if you want to dump the current thread's stack
		if (!GetThreadContext(hThread, &c)) {
			ResumeThread(hThread);
			return;
		}
		thread = hThread;
	}

	ZeroMemory(&sf, sizeof(sf));
	sf.AddrPC.Offset = c.Eip;
	sf.AddrStack.Offset = c.Esp;
	sf.AddrFrame.Offset = c.Ebp;
	sf.AddrPC.Mode = AddrModeFlat;
	sf.AddrStack.Mode = AddrModeFlat;
	sf.AddrFrame.Mode = AddrModeFlat;

	process = GetCurrentProcess();

	// use globalalloc to reduce risk for allocator related deadlock
	char* printstrings = (char*)GlobalAlloc(GMEM_FIXED, 0);

	bool containsOglDll = false;
	while (true) {
		more = StackWalk(
			IMAGE_FILE_MACHINE_I386, // TODO: fix this for 64 bit windows?
			process,
			thread,
			&sf,
			&c,
			NULL,
			SymFunctionTableAccess,
			SymGetModuleBase,
			NULL
		);
		if (!more || sf.AddrFrame.Offset == 0) {
			break;
		}

		dwModBase = SymGetModuleBase(process, sf.AddrPC.Offset);

		if (dwModBase) {
			GetModuleFileName((HINSTANCE)dwModBase, modname, MAX_PATH);
		} else {
			strcpy(modname, "Unknown");
		}

		pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
		pSym->MaxNameLength = MAX_PATH;

		char *printstringsnew = (char *)GlobalAlloc(GMEM_FIXED, (count + 1) * BUFFER_SIZE);
		memcpy(printstringsnew, printstrings, count * BUFFER_SIZE);
		GlobalFree(printstrings);
		printstrings = printstringsnew;

		if (SymGetSymFromAddr(process, sf.AddrPC.Offset, &Disp, pSym)) {
			// This is the code path taken on VC if debugging syms are found.
			SNPRINTF(printstrings + count * BUFFER_SIZE, BUFFER_SIZE, "(%d) %s(%s+%#0lx) [0x%08lX]", count, modname, pSym->Name, Disp, sf.AddrPC.Offset);
		} else {
			// This is the code path taken on MinGW, and VC if no debugging syms are found.
			SNPRINTF(printstrings + count * BUFFER_SIZE, BUFFER_SIZE, "(%d) %s [0x%08lX]", count, modname, sf.AddrPC.Offset);
		}

		// OpenGL lib names (ATI): "atioglxx.dll" "atioglx2.dll"
		containsOglDll = containsOglDll || strstr(modname, "atiogl");
		// OpenGL lib names (Nvidia): "nvoglnt.dll" "nvoglv32.dll" "nvoglv64.dll" (last one is a guess)
		containsOglDll = containsOglDll || strstr(modname, "nvogl");

		++count;
	}

	if (containsOglDll) {
		PRINT("This stack trace indicates a problem with your graphic card driver. "
		      "Please try upgrading or downgrading it. "
		      "Specifically recommended is the latest driver, and one that is as old as your graphic card. "
		      "Make sure to use a driver removal utility, before installing other drivers.");
	}

	if (suspended) {
		ResumeThread(hThread);
	}

	for (int i = 0; i < count; ++i) {
		PRINT("%s", printstrings + i * BUFFER_SIZE);
	}

	GlobalFree(printstrings);

	GlobalFree(pSym);
}
Exemplo n.º 9
0
static LRESULT CALLBACK vboxClipboardWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    LRESULT rc = 0;

    VBOXCLIPBOARDCONTEXT *pCtx = &g_ctx;

    switch (msg)
    {
        case WM_CLIPBOARDUPDATE:
        {
            Log(("WM_CLIPBOARDUPDATE\n"));

            if (GetClipboardOwner() != hwnd)
            {
                /* Clipboard was updated by another application. */
                vboxClipboardChanged(pCtx);
            }
        } break;

        case WM_CHANGECBCHAIN:
        {
            Log(("WM_CHANGECBCHAIN\n"));

            if (vboxClipboardIsNewAPI(pCtx))
            {
                rc = DefWindowProc(hwnd, msg, wParam, lParam);
                break;
            }

            HWND hwndRemoved = (HWND)wParam;
            HWND hwndNext    = (HWND)lParam;

            if (hwndRemoved == pCtx->hwndNextInChain)
            {
                /* The window that was next to our in the chain is being removed.
                 * Relink to the new next window.
                 */
                pCtx->hwndNextInChain = hwndNext;
            }
            else
            {
                if (pCtx->hwndNextInChain)
                {
                    /* Pass the message further. */
                    DWORD_PTR dwResult;
                    rc = SendMessageTimeout(pCtx->hwndNextInChain, WM_CHANGECBCHAIN, wParam, lParam, 0, CBCHAIN_TIMEOUT, &dwResult);
                    if (!rc)
                        rc = (LRESULT)dwResult;
                }
            }
        } break;

        case WM_DRAWCLIPBOARD:
        {
            Log(("WM_DRAWCLIPBOARD\n"));

            if (GetClipboardOwner () != hwnd)
            {
                /* Clipboard was updated by another application. */
                vboxClipboardChanged (pCtx);
            }

            if (pCtx->hwndNextInChain)
            {
                Log(("WM_DRAWCLIPBOARD next %p\n", pCtx->hwndNextInChain));
                /* Pass the message to next windows in the clipboard chain. */
                DWORD_PTR dwResult;
                rc = SendMessageTimeout(pCtx->hwndNextInChain, msg, wParam, lParam, 0, CBCHAIN_TIMEOUT, &dwResult);
                if (!rc)
                    rc = dwResult;
            }
        } break;

        case WM_TIMER:
        {
            if (vboxClipboardIsNewAPI(pCtx))
                break;

            HWND hViewer = GetClipboardViewer();

            /* Re-register ourselves in the clipboard chain if our last ping
             * timed out or there seems to be no valid chain. */
            if (!hViewer || pCtx->fCBChainPingInProcess)
            {
                removeFromCBChain(pCtx);
                addToCBChain(pCtx);
            }
            /* Start a new ping by passing a dummy WM_CHANGECBCHAIN to be
             * processed by ourselves to the chain. */
            pCtx->fCBChainPingInProcess = TRUE;
            hViewer = GetClipboardViewer();
            if (hViewer)
                SendMessageCallback(hViewer, WM_CHANGECBCHAIN, (WPARAM)pCtx->hwndNextInChain, (LPARAM)pCtx->hwndNextInChain, CBChainPingProc, (ULONG_PTR) pCtx);
        } break;
		        
        case WM_RENDERFORMAT:
        {
            /* Insert the requested clipboard format data into the clipboard. */
            uint32_t u32Format = 0;

            UINT format = (UINT)wParam;

            Log(("WM_RENDERFORMAT %d\n", format));

            switch (format)
            {
                case CF_UNICODETEXT:
                    u32Format |= VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT;
                    break;

                case CF_DIB:
                    u32Format |= VBOX_SHARED_CLIPBOARD_FMT_BITMAP;
                    break;

                default:
                    if (format >= 0xC000)
                    {
                        TCHAR szFormatName[256];

                        int cActual = GetClipboardFormatName(format, szFormatName, sizeof(szFormatName)/sizeof (TCHAR));

                        if (cActual)
                        {
                            if (strcmp (szFormatName, "HTML Format") == 0)
                            {
                                u32Format |= VBOX_SHARED_CLIPBOARD_FMT_HTML;
                            }
                        }
                    }
                    break;
            }

            if (u32Format == 0 || pCtx->pClient == NULL)
            {
                /* Unsupported clipboard format is requested. */
                Log(("WM_RENDERFORMAT unsupported format requested or client is not active.\n"));
                EmptyClipboard ();
            }
            else
            {
                int vboxrc = vboxClipboardReadDataFromClient (pCtx, u32Format);
                
                dprintf(("vboxClipboardReadDataFromClient vboxrc = %d, pv %p, cb %d, u32Format %d\n",
                          vboxrc, pCtx->pClient->data.pv, pCtx->pClient->data.cb, pCtx->pClient->data.u32Format));

                if (   RT_SUCCESS (vboxrc)
                    && pCtx->pClient->data.pv != NULL
                    && pCtx->pClient->data.cb > 0
                    && pCtx->pClient->data.u32Format == u32Format)
                {
                    HANDLE hMem = GlobalAlloc (GMEM_DDESHARE | GMEM_MOVEABLE, pCtx->pClient->data.cb);

                    dprintf(("hMem %p\n", hMem));

                    if (hMem)
                    {
                        void *pMem = GlobalLock (hMem);

                        dprintf(("pMem %p, GlobalSize %d\n", pMem, GlobalSize (hMem)));

                        if (pMem)
                        {
                            Log(("WM_RENDERFORMAT setting data\n"));

                            if (pCtx->pClient->data.pv)
                            {
                                memcpy (pMem, pCtx->pClient->data.pv, pCtx->pClient->data.cb);

                                RTMemFree (pCtx->pClient->data.pv);
                                pCtx->pClient->data.pv        = NULL;
                            }

                            pCtx->pClient->data.cb        = 0;
                            pCtx->pClient->data.u32Format = 0;

                            /* The memory must be unlocked before inserting to the Clipboard. */
                            GlobalUnlock (hMem);

                            /* 'hMem' contains the host clipboard data.
                             * size is 'cb' and format is 'format'.
                             */
                            HANDLE hClip = SetClipboardData (format, hMem);

                            dprintf(("vboxClipboardHostEvent hClip %p\n", hClip));

                            if (hClip)
                            {
                                /* The hMem ownership has gone to the system. Nothing to do. */
                                break;
                            }
                        }

                        GlobalFree (hMem);
                    }
                }

                RTMemFree (pCtx->pClient->data.pv);
                pCtx->pClient->data.pv        = NULL;
                pCtx->pClient->data.cb        = 0;
                pCtx->pClient->data.u32Format = 0;

                /* Something went wrong. */
                EmptyClipboard ();
            }
        } break;

        case WM_RENDERALLFORMATS:
        {
            Log(("WM_RENDERALLFORMATS\n"));

            /* Do nothing. The clipboard formats will be unavailable now, because the
             * windows is to be destroyed and therefore the guest side becomes inactive.
             */
            int vboxrc = vboxOpenClipboard(hwnd);
            if (RT_SUCCESS(vboxrc))
            {
                EmptyClipboard();

                CloseClipboard();
            }
            else
            {
                LogFlow(("vboxClipboardWndProc: WM_RENDERALLFORMATS: error in open clipboard. hwnd: %x, rc: %Rrc\n", hwnd, vboxrc));
            }
        } break;

        case WM_USER:
        {
            if (pCtx->pClient == NULL || pCtx->pClient->fMsgFormats)
            {
                /* Host has pending formats message. Ignore the guest announcement,
                 * because host clipboard has more priority.
                 */
                Log(("WM_USER ignored\n"));
                break;
            }

            /* Announce available formats. Do not insert data, they will be inserted in WM_RENDER*. */
            uint32_t u32Formats = (uint32_t)lParam;

            Log(("WM_USER u32Formats = %02X\n", u32Formats));

            int vboxrc = vboxOpenClipboard(hwnd);
            if (RT_SUCCESS(vboxrc))
            {
                EmptyClipboard();

                Log(("WM_USER emptied clipboard\n"));

                HANDLE hClip = NULL;

                if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT)
                {
                    dprintf(("window proc WM_USER: VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT\n"));

                    hClip = SetClipboardData (CF_UNICODETEXT, NULL);
                }

                if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_BITMAP)
                {
                    dprintf(("window proc WM_USER: VBOX_SHARED_CLIPBOARD_FMT_BITMAP\n"));

                    hClip = SetClipboardData (CF_DIB, NULL);
                }

                if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_HTML)
                {
                    UINT format = RegisterClipboardFormat ("HTML Format");
                    dprintf(("window proc WM_USER: VBOX_SHARED_CLIPBOARD_FMT_HTML 0x%04X\n", format));
                    if (format != 0)
                    {
                        hClip = SetClipboardData (format, NULL);
                    }
                }

                CloseClipboard();

                dprintf(("window proc WM_USER: hClip %p, err %d\n", hClip, GetLastError ()));
            }
            else
            {
                dprintf(("window proc WM_USER: failed to open clipboard. rc: %Rrc\n", vboxrc));
            }
        } break;

        case WM_DESTROY:
        {
            /* MS recommends to remove from Clipboard chain in this callback */
            Assert(pCtx->hwnd);
            removeFromCBChain(pCtx);
            if (pCtx->timerRefresh)
                KillTimer(pCtx->hwnd, 0);
            PostQuitMessage(0);
        } break;

        default:
        {
            Log(("WM_ %p\n", msg));
            rc = DefWindowProc(hwnd, msg, wParam, lParam);
        }
    }

    Log(("WM_ rc %d\n", rc));
    return rc;
}
Exemplo n.º 10
0
BOOL
InitializeOptions
(
    IN      LPSTR   lpCmdLine
)
{
    BOOL Success1 = FALSE;
    BOOL Success2 = FALSE;

    DWORD ArgC = 0;

    LPTSTR * ArgV = CommandLineToArgv(lpCmdLine, &ArgC);

    if (ArgV)
    {
        for (DWORD i=0; i<ArgC; i++)
        {
            if (_stricmp(ArgV[i], "/s")==0)
            {
                OptionSilent = TRUE;
            }
            else if (_stricmp(ArgV[i],"/silent")==0)
            {
                OptionSilent = TRUE;
            }
            else if (_stricmp(ArgV[i],"/path")==0)
            {
                if (((i+1)<ArgC) && (ArgV[i+1]))
                {
                    strcpy(InfPath, ArgV[i+1]);

                    Success1 = TRUE;
                    i++;
                }
            }
            else if (_stricmp(ArgV[i],"/path:relative")==0)
            {
                if (((i+1)<ArgC) && (ArgV[i+1]))
                {
                    GetCurrentDirectory(MAX_PATH, InfPath);
                    strcat(InfPath, "\\");
                    strcat(InfPath, ArgV[i+1]);

                    Success1 = TRUE;
                    i++;
                }
            }
            else if (_stricmp(ArgV[i],"/ddinstall")==0)
            {
                if (((i+1)<ArgC) && (ArgV[i+1]))
                {
                    strcpy(DDInstallSection, ArgV[i+1]);

                    Success2 = TRUE;
                    i++;
                }
            }
            else if (_stricmp(ArgV[i],"/os")==0)
            {
                if (((i+1)<ArgC) && (ArgV[i+1]))
                {
                    strcpy(ExpectedOsVersion, ArgV[i+1]);

                    OptionOsVersionCheck = TRUE;
                    i++;
                }
            }
            else if (_stricmp(ArgV[i],"/buildnumber")==0)
            {
                if (((i+1)<ArgC) && (ArgV[i+1]))
                {
                    ExpectedOsBuildNumber = atoi(ArgV[i+1]);

                    OptionOsBuildNumberCheck = TRUE;
                    i++;
                }
            }
            else if (_stricmp(ArgV[i],"/sp")==0)
            {
                if (((i+1)<ArgC) && (ArgV[i+1]))
                {
                    ExpectedOsServicePack = atoi(ArgV[i+1]);

                    OptionOsServicePackCheck = TRUE;
                    i++;
                }
            }
        }

        GlobalFree(HGLOBAL(ArgV));
    }

    return (Success1 && Success2);
}
Exemplo n.º 11
0
HRESULT WINAPI ObjectFromLresult( LRESULT result, REFIID riid, WPARAM wParam, void **ppObject )
{
    WCHAR atom_str[sizeof(lresult_atom_prefix)/sizeof(WCHAR)+3*8+3];
    HANDLE server_proc, server_mapping, mapping;
    DWORD proc_id, size;
    IStream *stream;
    HGLOBAL data;
    void *view;
    HRESULT hr;
    WCHAR *p;

    TRACE("%ld %s %ld %p\n", result, debugstr_guid(riid), wParam, ppObject );

    if(wParam)
        FIXME("unsupported wParam = %lx\n", wParam);

    if(!ppObject)
        return E_INVALIDARG;
    *ppObject = NULL;

    if(result != (ATOM)result)
        return E_FAIL;

    if(!GlobalGetAtomNameW(result, atom_str, sizeof(atom_str)/sizeof(WCHAR)))
        return E_FAIL;
    if(memcmp(atom_str, lresult_atom_prefix, sizeof(lresult_atom_prefix)))
        return E_FAIL;
    p = atom_str + sizeof(lresult_atom_prefix)/sizeof(WCHAR);
    proc_id = strtoulW(p, &p, 16);
    if(*p != ':')
        return E_FAIL;
    server_mapping = ULongToHandle( strtoulW(p+1, &p, 16) );
    if(*p != ':')
        return E_FAIL;
    size = strtoulW(p+1, &p, 16);
    if(*p != 0)
        return E_FAIL;

    server_proc = OpenProcess(PROCESS_DUP_HANDLE, FALSE, proc_id);
    if(!server_proc)
        return E_FAIL;

    if(!DuplicateHandle(server_proc, server_mapping, GetCurrentProcess(), &mapping,
                0, FALSE, DUPLICATE_CLOSE_SOURCE|DUPLICATE_SAME_ACCESS))
        return E_FAIL;
    CloseHandle(server_proc);
    GlobalDeleteAtom(result);

    view = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0);
    CloseHandle(mapping);
    if(!view)
        return E_FAIL;

    data = GlobalAlloc(GMEM_FIXED, size);
    memcpy(data, view, size);
    UnmapViewOfFile(view);
    if(!data)
        return E_OUTOFMEMORY;

    hr = CreateStreamOnHGlobal(data, TRUE, &stream);
    if(FAILED(hr)) {
        GlobalFree(data);
        return hr;
    }

    hr = CoUnmarshalInterface(stream, riid, ppObject);
    IStream_Release(stream);
    return hr;
}
Exemplo n.º 12
0
ALERROR dibLoadFromBlock (IReadBlock &Data, HBITMAP *rethDIB, EBitmapTypes *retiType)

//	dibLoadFromBlock
//
//	Loads a DIB into memory

	{
	ALERROR error;
	HBITMAP hDIB;
	HANDLE hFileData;
	int iBitsOffset;
	BITMAPINFOHEADER bi;

	if (error = Data.Open())
		return error;

	//	Get information

	if (error = ReadDIBInfo(&Data, &hFileData, &iBitsOffset, &bi))
		return error;

	//	Return the bit-depth of the original bitmap

	if (retiType)
		{
		switch (bi.biBitCount)
			{
			case 1:
				*retiType = bitmapMonochrome;
				break;

			case 8:
				*retiType = bitmapAlpha;
				break;

			default:
				*retiType = bitmapRGB;
				break;
			}
		}

	//	Calculate how much space we need for the bits

	DWORD dwBits = bi.biSizeImage;
	DWORD dwPaletteSize = dibPaletteSize(&bi);
	DWORD dwLen = bi.biSize + dwPaletteSize + dwBits;

	//	Create a DIBSection

	if (error = dibCreate16bitDIB(bi.biWidth, bi.biHeight, &hDIB, NULL))
		{
		GlobalFree(hFileData);
		return error;
		}

	//	Set the bits

	HDC hDC = CreateCompatibleDC(NULL);
	SetDIBits(hDC,
			hDIB,
			0,
			bi.biHeight,
			Data.GetPointer(iBitsOffset, -1),
			(BITMAPINFO *)GlobalLock(hFileData),
			DIB_RGB_COLORS);

	::DeleteDC(hDC);

	GlobalUnlock(hFileData);
	GlobalFree(hFileData);

	//	Done

	*rethDIB = hDIB;

	return NOERROR;
	}
Exemplo n.º 13
0
int CNetWorkFinder::StartFind(LPNETRESOURCE lpnr)
{
	DWORD dwResult, dwResultEnum;
	HANDLE hEnum;
	DWORD cbBuffer = 16384;      // 16K is a good size
	DWORD cEntries = (DWORD)-1;         // enumerate all possible entries
	LPNETRESOURCE lpnrLocal;     // pointer to enumerated structures
	DWORD i;
	int count = 0;
	//
	// Call the WNetOpenEnum function to begin the enumeration.
	//
	dwResult = WNetOpenEnum(RESOURCE_GLOBALNET, // all network resources
						  RESOURCETYPE_ANY,   // all resources
						  0,        // enumerate all resources
						  lpnr,     // NULL first time the function is called
						  &hEnum);  // handle to the resource

    TCHAR szDescription[256];
    TCHAR szProvider[256];
	DWORD dwWNetResult, dwLastError; 

	if (dwResult != NO_ERROR)
	{  
        dwWNetResult = WNetGetLastError(&dwLastError, // error code
            szDescription,  // buffer for error description 
            sizeof(szDescription),  // size of error buffer
            szProvider,     // buffer for provider name 
            sizeof(szProvider));    // size of name buffer
	//
	// Process errors with an application-defined error handler.
	//
	return count;
	}
	//
	// Call the GlobalAlloc function to allocate resources.
	//
	lpnrLocal = (LPNETRESOURCE) GlobalAlloc(GPTR, cbBuffer);
	if (lpnrLocal == NULL) 
		return count;

	do
	{  
	//
	// Initialize the buffer.
	//
	ZeroMemory(lpnrLocal, cbBuffer);
	//
	// Call the WNetEnumResource function to continue
	//  the enumeration.
	//
	dwResultEnum = WNetEnumResource(hEnum,      // resource handle
									&cEntries,  // defined locally as -1
									lpnrLocal,  // LPNETRESOURCE
									&cbBuffer); // buffer size
	//
	// If the call succeeds, loop through the structures.
	//
	bool bRecursive = m_bRecursive;
	if (dwResultEnum == NO_ERROR)
	{
		count += cEntries;
			// Sort as per thier name as 
		qsort(lpnrLocal, cEntries, sizeof(NETRESOURCE),
			(GenericCompareFn)CompareNetResource);
		for(i = 0; i < cEntries && !m_bAborted; i++)
		{
			// Call callback
			if (mNetWorkFindCallBack != NULL) {
				switch (mNetWorkFindCallBack(lpnrLocal+i,m_pUserParam)) {
				case FCB_ABORT:
					m_bAborted = true;
					break;
				case FCB_DORECURSIVE:
					bRecursive = true;
					break;
				case FCB_NORECURSIVE:
					bRecursive = false;
					break;
				}
			}
			if (!m_bAborted && cEntries > 0 && bRecursive) {
				if(RESOURCEUSAGE_CONTAINER == (lpnrLocal[i].dwUsage
											   & RESOURCEUSAGE_CONTAINER))
					count += StartFind(&lpnrLocal[i]);
			}
		}
	}
	// Process errors.
	//
	else if (dwResultEnum != ERROR_NO_MORE_ITEMS)
	{
	  break;
	}
	}
	//
	// End do.
	//
	while(dwResultEnum != ERROR_NO_MORE_ITEMS && !m_bAborted);
	//
	// Call the GlobalFree function to free the memory.
	//
	GlobalFree((HGLOBAL)lpnrLocal);
	//
	// Call WNetCloseEnum to end the enumeration.
	//
	dwResult = WNetCloseEnum(hEnum);


	return count;
}
Exemplo n.º 14
0
/** Modifies the wininit.ini file to rename / delete a file.
 *
 * @param prevName The previous / current name of the file.
 * @param newName The new name to move the file to.  If NULL, the current file
 * will be deleted.
 */
void RenameViaWininit(TCHAR* prevName, TCHAR* newName)
{
  static char szRenameLine[1024];
  static TCHAR wininit[1024];
  static TCHAR tmpbuf[1024];
#ifdef _UNICODE
  static char shortExisting[1024];
  static char shortNew[1024];
#endif

  int cchRenameLine;
  static const char szRenameSec[] = "[Rename]\r\n"; // rename section marker
  HANDLE hfile;
  DWORD dwFileSize;
  DWORD dwBytes;
  DWORD dwRenameLinePos;
  char *pszWinInit;   // Contains the file contents of wininit.ini

  int spn;   // length of the short path name in TCHARs.

  lstrcpy(tmpbuf, _T("NUL"));

  if (newName) {
    // create the file if it's not already there to prevent GetShortPathName from failing
    CloseHandle(myOpenFile(newName,0,CREATE_NEW));
    spn = GetShortPathName(newName,tmpbuf,1024);
    if (!spn || spn > 1024)
      return;
  }
  // wininit is used as a temporary here
  spn = GetShortPathName(prevName,wininit,1024);
  if (!spn || spn > 1024)
    return;

 // Because wininit.ini is an ASCII text file, we need to be careful what we
 // convert here to TCHARs.

#ifdef _UNICODE
  // The short name produced by GetShortPathName is always in the ASCII range
  // of characters.
 
  // Convert short name of new name to ANSI
  if (WideCharToMultiByte(CP_ACP, 0, tmpbuf, -1, shortNew, sizeof(shortNew), NULL, NULL) == 0)
  {
     // We have a failure in conversion to ANSI
     return;
  }

  // Convert short name of old name to ANSI
  if (WideCharToMultiByte(CP_ACP, 0, wininit, -1, shortExisting, sizeof(shortExisting), NULL, NULL) == 0)
  {
     // We have a failure in conversion to ANSI
     return;
  }

  cchRenameLine = wsprintfA(szRenameLine, "%s=%s\r\n", shortNew, shortExisting);
#else
  cchRenameLine = wsprintfA(szRenameLine, "%s=%s\r\n", tmpbuf, wininit);
#endif
  // Get the path to the wininit.ini file.
  GetWindowsDirectory(wininit, 1024-16);
  lstrcat(wininit, _T("\\wininit.ini"));

  hfile = myOpenFile(wininit, GENERIC_READ | GENERIC_WRITE, OPEN_ALWAYS);

  if (hfile != INVALID_HANDLE_VALUE)
  {
    // We are now working on the Windows wininit file
    dwFileSize = GetFileSize(hfile, NULL);
    pszWinInit = (char*) GlobalAlloc(GPTR, dwFileSize + cchRenameLine + 10);

    if (pszWinInit != NULL)
    {
      if (ReadFile(hfile, pszWinInit, dwFileSize, &dwBytes, NULL) && dwFileSize == dwBytes)
      {
        // Look for the rename section in the current file.
        LPSTR pszRenameSecInFile = mystrstriA(pszWinInit, szRenameSec);
        if (pszRenameSecInFile == NULL)
        {
          // No rename section.  So we add it to the end of file.
          lstrcpyA(pszWinInit+dwFileSize, szRenameSec);
          dwFileSize += 10;
          dwRenameLinePos = dwFileSize;
        }
        else
        {
          // There is a rename section, but is there another section after it?
          char *pszFirstRenameLine = pszRenameSecInFile+10;
          char *pszNextSec = mystrstriA(pszFirstRenameLine,"\n[");
          if (pszNextSec)
          {
            char *p = pszWinInit + dwFileSize;
            char *pEnd = pszWinInit + dwFileSize + cchRenameLine;

            while (p > pszNextSec)
            {
              *pEnd-- = *p--;
            }

            dwRenameLinePos = pszNextSec - pszWinInit + 1; // +1 for the \n
          }
          // rename section is last, stick item at end of file
          else dwRenameLinePos = dwFileSize;
        }

        mini_memcpy(&pszWinInit[dwRenameLinePos], szRenameLine, cchRenameLine);
        dwFileSize += cchRenameLine;

        SetFilePointer(hfile, 0, NULL, FILE_BEGIN);
        WriteFile(hfile, pszWinInit, dwFileSize, &dwBytes, NULL);

        GlobalFree(pszWinInit);
      }
    }
    
    CloseHandle(hfile);
  }
}
Exemplo n.º 15
0
int main(int argc, char **argv)
{
int exfc, infc;
char **exfv, **infv;
char *x_opt;
DWORD dwVerInfoSize;
DWORD dwVerHnd;
char szFullPath[_MAX_PATH];
int retcode;
#ifdef WIN32
char *ptr;
#else
HFILE hfile;
OFSTRUCT ofs;
#endif
HANDLE  hMem;         /* handle to mem alloc'ed */

if (argc < 2)   /* We must have an archive to unzip */
   {
   printf("usage: %s <zipfile> [entry1 [entry2 [...]]] [-x xentry1 [...]]",
          "example");
   return 0;
   }

hDCL = GlobalAlloc( GPTR, (DWORD)sizeof(DCL));
if (!hDCL)
   {
   return 0;
   }
lpDCL = (LPDCL)GlobalLock(hDCL);
if (!lpDCL)
   {
   GlobalFree(hDCL);
   return 0;
   }

hUF = GlobalAlloc( GPTR, (DWORD)sizeof(USERFUNCTIONS));
if (!hUF)
   {
   GlobalUnlock(hDCL);
   GlobalFree(hDCL);
   return 0;
   }
lpUserFunctions = (LPUSERFUNCTIONS)GlobalLock(hUF);

if (!lpUserFunctions)
   {
   GlobalUnlock(hDCL);
   GlobalFree(hDCL);
   GlobalFree(hUF);
   return 0;
   }

lpUserFunctions->password = password;
lpUserFunctions->print = DisplayBuf;
lpUserFunctions->sound = NULL;
lpUserFunctions->replace = GetReplaceDlgRetVal;
lpUserFunctions->SendApplicationMessage = ReceiveDllMessage;

/* First we go look for the unzip dll */
#ifdef WIN32
if (SearchPath(
    NULL,               /* address of search path               */
    UNZ_DLL_NAME,       /* address of filename                  */
    NULL,               /* address of extension                 */
    _MAX_PATH,           /* size, in characters, of buffer       */
    szFullPath,         /* address of buffer for found filename */
    &ptr                /* address of pointer to file component */
   ) == 0)
#else
hfile = OpenFile(UNZ_DLL_NAME,  &ofs, OF_SEARCH);
if (hfile == HFILE_ERROR)
#endif
   {
   char str[256];
   wsprintf (str, DLL_WARNING, UNZ_DLL_NAME);
   printf("%s\n", str);
   FreeUpMemory();
   return 0;
   }
#ifndef WIN32
else
   lstrcpy(szFullPath, ofs.szPathName);
_lclose(hfile);
#endif

/* Now we'll check the unzip dll version information. Note that this is
   not the same information as is returned from a call to UzpVersion()
 */
dwVerInfoSize =
    GetFileVersionInfoSize(szFullPath, &dwVerHnd);

if (dwVerInfoSize)
   {
   BOOL  fRet, fRetName;
   char str[256];
   LPSTR   lpstrVffInfo; /* Pointer to block to hold info */
   LPSTR lszVer = NULL;
   LPSTR lszVerName = NULL;
   UINT  cchVer = 0;

   /* Get a block big enough to hold the version information */
   hMem          = GlobalAlloc(GMEM_MOVEABLE, dwVerInfoSize);
   lpstrVffInfo  = GlobalLock(hMem);

   /* Get the version information */
   if (GetFileVersionInfo(szFullPath, 0L, dwVerInfoSize, lpstrVffInfo))
      {
      fRet = VerQueryValue(lpstrVffInfo,
               TEXT("\\StringFileInfo\\040904E4\\FileVersion"),
              (LPVOID)&lszVer,
              &cchVer);
      fRetName = VerQueryValue(lpstrVffInfo,
               TEXT("\\StringFileInfo\\040904E4\\CompanyName"),
               (LPVOID)&lszVerName,
               &cchVer);
      if (!fRet || !fRetName ||
         (lstrcmpi(lszVer, UNZ_DLL_VERSION) != 0) ||
         (lstrcmpi(lszVerName, COMPANY_NAME) != 0))
         {
         wsprintf (str, DLL_VERSION_WARNING, UNZ_DLL_NAME);
         printf("%s\n", str);
         FreeUpMemory();
         GlobalUnlock(hMem);
         GlobalFree(hMem);
         return 0;
         }
      }
      /* free memory */
   GlobalUnlock(hMem);
   GlobalFree(hMem);
   }
else
   {
   char str[256];
   wsprintf (str, DLL_VERSION_WARNING, UNZ_DLL_NAME);
   printf("%s\n", str);
   FreeUpMemory();
   return 0;
   }
/* Okay, now we know that the dll exists, and has the proper version
 * information in it. We can go ahead and load it.
 */
hUnzipDll = LoadLibrary(UNZ_DLL_NAME);
#ifndef WIN32
if (hUnzipDll > HINSTANCE_ERROR)
#else
if (hUnzipDll != NULL)
#endif
   {
   Wiz_SingleEntryUnzip =
     (_DLL_UNZIP)GetProcAddress(hUnzipDll, "Wiz_SingleEntryUnzip");
   }
else
   {
   char str[256];
   wsprintf (str, "Could not load %s", UNZ_DLL_NAME);
   printf("%s\n", str);
   FreeUpMemory();
   return 0;
   }

/*
   Here is where the actual extraction process begins. First we set up the
   flags to be passed into the dll.
 */
lpDCL->ncflag = 0; /* Write to stdout if true */
lpDCL->fQuiet = 0; /* We want all messages.
                      1 = fewer messages,
                      2 = no messages */
lpDCL->ntflag = 0; /* test zip file if true */
lpDCL->nvflag = 0; /* give a verbose listing if true */
lpDCL->nzflag = 0; /* display a zip file comment if true */
lpDCL->ndflag = 1; /* Recreate directories if true */
lpDCL->naflag = 0; /* Do not convert CR to CRLF */
lpDCL->nfflag = 0; /* Do not freshen existing files only */
lpDCL->noflag = 1; /* Over-write all files if true */
lpDCL->ExtractOnlyNewer = 0; /* Do not extract only newer */
lpDCL->PromptToOverwrite = 0; /* "Overwrite all" selected -> no query mode */
lpDCL->lpszZipFN = argv[1]; /* The archive name */
lpDCL->lpszExtractDir = NULL; /* The directory to extract to. This is set
                                 to NULL if you are extracting to the
                                 current directory.
                               */
/*
   As this is a quite short example, intended primarily to show how to
   load and call in to the dll, the command-line parameters are only
   parsed in a very simplistic way:
   We assume that the command-line parameters after the zip archive
   make up a list of file patterns:
   " [file_i1] [file_i2] ... [file_iN] [-x file_x1 [file_x2] ...]".
   We scan for an argument "-x"; all arguments in front are
   "include file patterns", all arguments after are "exclude file patterns".
   If no more arguments are given, we extract ALL files.

   In summary, the example program should be run like:
   example <archive.name> [files to include] [-x files to exclude]
   ("<...> denotes mandatory arguments, "[...]" optional arguments)
 */
x_opt = NULL;
if (argc > 2) {
  infv = &argv[2];
  for (infc = 0; infc < argc-2; infc++)
    if (!strcmp("-x", infv[infc])) {
        x_opt = infv[infc];
        infv[infc] = NULL;
        break;
    }
  exfc = argc - infc - 3;
  if (exfc > 0)
    exfv = &argv[infc+3];
  else {
    exfc = 0;
    exfv = NULL;
  }
} else {
  infc = exfc = 0;
  infv = exfv = NULL;
}
retcode = (*Wiz_SingleEntryUnzip)(infc, infv, exfc, exfv, lpDCL,
                                  lpUserFunctions);
if (x_opt) {
  infv[infc] = x_opt;
  x_opt = NULL;
}

if (retcode != 0)
   printf("Error unzipping...\n");

FreeUpMemory();
FreeLibrary(hUnzipDll);
return 1;
}
Exemplo n.º 16
0
/*-----------------------------------------------------------------------------
    Name        : llSystemsShutdown
    Description : Shut down systems required by the system
    Inputs      :
    Outputs     :
    Return      :
----------------------------------------------------------------------------*/
void llSystemsShutdown(void)
{
    //memory
    GlobalFree(utyMemoryHeap);
}
Exemplo n.º 17
0
HRGN	DibCreateRegion( LPBYTE lpDib, BYTE byColor )
{
	LPBYTE			lpData;
	int				x, y, cx, cy;
	DWORD			dwMaxRect;
	RECT			r;
	RGNDATA			*pRd;
	HGLOBAL			hMem;
	HRGN			hRgn;

	if ( !lpDib || DIB_BPP( lpDib ) != 8 )
		return NULL;

	cx = DIB_CX( lpDib );
	cy = DIB_CY( lpDib );
	dwMaxRect = 3000;

	hMem = GlobalAlloc( GMEM_FIXED, sizeof(RGNDATAHEADER) + sizeof(RECT) * dwMaxRect );
	pRd = (RGNDATA *)GlobalLock( hMem );
	pRd->rdh.dwSize = sizeof(RGNDATAHEADER);
	pRd->rdh.iType = RDH_RECTANGLES;
	pRd->rdh.nCount = 0;
	pRd->rdh.nRgnSize = 0;
	SetRect( &(pRd->rdh.rcBound), cx, cy, 0, 0 );

	for ( y = 0; y < cy; y++ )
	{
		lpData = DIB_DATA8XY_INV( lpDib, 0, y );
		for ( x = 0; x < cx; x++ )
		{
			if ( *lpData == byColor )
			{
				// get run length rect
				r.left = x;
				r.top = r.bottom = y;
				while ( *lpData == byColor && x < cx )
				{
					x++;
					lpData++;
				}
				r.right = x;

				// update bound rect
				if ( r.left < pRd->rdh.rcBound.left )
					pRd->rdh.rcBound.left = r.left;
				if ( r.top < pRd->rdh.rcBound.top )
					pRd->rdh.rcBound.top = r.top;
				if ( r.right > pRd->rdh.rcBound.right )
					pRd->rdh.rcBound.right = r.right;
				if ( r.bottom > pRd->rdh.rcBound.bottom )
					pRd->rdh.rcBound.bottom = r.bottom;

				memcpy( &pRd->Buffer[pRd->rdh.nCount++], &r, sizeof(RECT) );
				if ( pRd->rdh.nCount >= dwMaxRect )
					goto exitLoop;
			}
			lpData++;
		}
	}

exitLoop:

	pRd->rdh.nRgnSize = sizeof(RECT) * pRd->rdh.nCount;
	hRgn = ExtCreateRegion( NULL, sizeof(RGNDATAHEADER) + sizeof(RECT) * pRd->rdh.nCount, pRd );

	GlobalUnlock( hMem );
	GlobalFree( hMem );

	return hRgn;
}
Exemplo n.º 18
0
void *ClientData::run()
{
	USHORT sz,fr;

	if(type==ClientData::t_send)
	{
		// Send on the socket the datas shared

		// Send the format of the clipboard data
		char info[sizeof(USHORT)*2];
		sz=htons(*size);
		fr=htons(*format);
		memcpy(info,&sz,sizeof(USHORT));
		memcpy(info+sizeof(USHORT),&fr,sizeof(USHORT));

		// Send the data
		int result=send(s,info,sizeof(USHORT)*2,NULL);

		if(result==0	|| result==SOCKET_ERROR)
		{
			//printError(L"send");
			//MessageBox(hWnd,_T("Invio dei dati preliminari fallito"),_T("Errore"),MB_OK);
			return NULL;
		}

		result=send(s,data,*size,NULL);

		if(result==0	|| result==SOCKET_ERROR)
		{
			//printError(L"send");
			//MessageBox(hWnd,_T("Invio dei dati fallito"),_T("Errore"),MB_OK);
			return NULL;
		}

	}else{

		// Connect with the owner of the clipboard required

		sockaddr_in c_in;
		int addr_sz=sizeof(c_in);
		
		SOCKET s_tmp=accept(s,reinterpret_cast<sockaddr *>(&c_in),&addr_sz);
		if(s_tmp==INVALID_SOCKET)
		{
			//printError(L"accept");
			MessageBox(hWnd,_T("Nessuna risposta dal proprietario; trasferimento della clipboard fallito."),_T("Errore"),MB_OK);
			return NULL;
		}

		closesocket(s);
		s=s_tmp;

	
		// Receive the size and format of the clipboard data
		char info[sizeof(USHORT)*2];
		if(!recv_timeout(s,info,sizeof(USHORT)*2,0))
		{
			//MessageBox(hWnd,_T("Nessun dato preliminare dal client!"),_T("Errore"),MB_OK);
			MessageBox(hWnd,_T("Nessuna risposta dal proprietario; trasferimento della clipboard fallito."),_T("Errore"),MB_OK);
			return NULL;
		}

		memcpy(&sz,info,sizeof(USHORT));
		memcpy(&fr,info+sizeof(USHORT),sizeof(USHORT));
		sz=htons(sz);
		fr=htons(fr);

		// Receive the data
		if(sz<1)
		{
			MessageBox(hWnd,_T("Ricevuto un valore di size inaccettabile; trasferimento della clipboard fallito."),_T("Errore"),MB_OK);
			return NULL;
		}

		char *cbData=new char[sz];

		if(!recv_timeout(s,cbData,sz,0))
		{
			//printError(L"recv_timeout");
			MessageBox(hWnd,_T("Nessuna risposta dal proprietario; trasferimento della clipboard fallito."),_T("Errore"),MB_OK);	
			return NULL;
		}

		// Copy datas in the clipboard
		if(OpenClipboard(hWnd)==false)
		{
			//printError(L"OpenClipboard");
			MessageBox(hWnd,L"Impossibile accedere alla Clipboard; trasferimento della clipboard fallito.",_T("Errore"),MB_OK);
			delete[] cbData;
			return false;
		}

		if(EmptyClipboard()==false)
		{
			//printError(L"EmptyClipboard");
			MessageBox(hWnd,L"Impossibile svuotare la clipboard; trasferimento della clipboard fallito.",_T("Errore"),MB_OK);
			delete[] cbData;
			CloseClipboard();
			return false;
		}

		HANDLE hData=GlobalAlloc(GMEM_MOVEABLE, sz); 
        if (hData == NULL) 
        { 
            //printError(L"GlobalAlloc");
			MessageBox(hWnd,L"Impossibile allocare l'oggetto globale; trasferimento della clipboard fallito.",_T("Errore"),MB_OK);
			delete[] cbData;
			CloseClipboard();
			return false;
		}
 
        // Lock the handle and copy the text to the buffer. 
        LPVOID lptstrCopy = GlobalLock(hData); 
        memcpy(lptstrCopy, cbData, sz);
        GlobalUnlock(hData); 

        // Place the handle on the clipboard. 
		if(SetClipboardData(fr,hData)==NULL)
		{
			//printError(L"SetClipboardData");
			MessageBox(hWnd,L"Impossibile impostare i dati nella clipboard.",_T("Errore"),MB_OK);
			GlobalFree(hData);
			delete[] cbData;
			return false;
		}

		if(CloseClipboard()==false)
		{
			printError(L"CloseClipboard");
			MessageBox(hWnd,L"Impossibile chiudere la Clipboard.",_T("Errore"),MB_OK);
			return false;
		}
		MessageBox(hWnd,_T("I dati richiesti sono stati trasferiti nella tua clipboard."),_T("Avviso"),MB_OK);
	}

	return NULL;
}
Exemplo n.º 19
0
Proxy* WinHttpIO::getautoproxy()
{
    Proxy* proxy = new Proxy();
    proxy->setProxyType(Proxy::NONE);

    WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ieProxyConfig = { 0 };

    if (WinHttpGetIEProxyConfigForCurrentUser(&ieProxyConfig) == TRUE)
    {
        if (ieProxyConfig.lpszProxy)
        {
            string proxyURL;
            proxy->setProxyType(Proxy::CUSTOM);
            int len = wcslen(ieProxyConfig.lpszProxy);
            proxyURL.assign((const char*)ieProxyConfig.lpszProxy, len * sizeof(wchar_t) + 1);

            // only save one proxy
            for (int i = 0; i < len; i++)
            {
                wchar_t* character = (wchar_t*)(proxyURL.data() + i * sizeof(wchar_t));

                if (*character == ' ' || *character == ';')
                {
                    proxyURL.resize(i*sizeof(wchar_t));
                    len = i;
                    break;
                }
            }

            // remove protocol prefix, if any
            for (int i = len - 1; i >= 0; i--)
            {
                wchar_t* character = (wchar_t*)(proxyURL.data() + i * sizeof(wchar_t));

                if (*character == '/')
                {
                    proxyURL = proxyURL.substr((i + 1) * sizeof(wchar_t));
                    break;
                }
            }

            proxy->setProxyURL(&proxyURL);
        }
        else if (ieProxyConfig.lpszAutoConfigUrl || ieProxyConfig.fAutoDetect == TRUE)
        {
            WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions;

            if (ieProxyConfig.lpszAutoConfigUrl)
            {
                autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
                autoProxyOptions.lpszAutoConfigUrl = ieProxyConfig.lpszAutoConfigUrl;
                autoProxyOptions.dwAutoDetectFlags = 0;
            }
            else
            {
                autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
                autoProxyOptions.lpszAutoConfigUrl = NULL;
                autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
            }

            autoProxyOptions.fAutoLogonIfChallenged = TRUE;
            autoProxyOptions.lpvReserved = NULL;
            autoProxyOptions.dwReserved = 0;

            WINHTTP_PROXY_INFO proxyInfo;

            if (WinHttpGetProxyForUrl(hSession, L"https://g.api.mega.co.nz/", &autoProxyOptions, &proxyInfo))
            {
                if (proxyInfo.lpszProxy)
                {
                    string proxyURL;
                    proxy->setProxyType(Proxy::CUSTOM);
                    proxyURL.assign((const char*)proxyInfo.lpszProxy, wcslen(proxyInfo.lpszProxy) * sizeof(wchar_t));
                    proxy->setProxyURL(&proxyURL);
                }
            }
        }
    }

    if (ieProxyConfig.lpszProxy)
    {
        GlobalFree(ieProxyConfig.lpszProxy);
    }

    if (ieProxyConfig.lpszProxyBypass)
    {
        GlobalFree(ieProxyConfig.lpszProxyBypass);
    }

    if (ieProxyConfig.lpszAutoConfigUrl)
    {
        GlobalFree(ieProxyConfig.lpszAutoConfigUrl);
    }

    return proxy;
}
Exemplo n.º 20
0
/* This function will open a wave input file and prepare it for reading,
 * so the data can be easily
 * read with WaveReadFile. Returns 0 if successful, the error code if not.
 *      pszFileName - Input filename to load.
 *      phmmioIn    - Pointer to handle which will be used
 *          for further mmio routines.
 *      ppwfxInfo   - Ptr to ptr to WaveFormatEx structure
 *          with all info about the file.
 *
*/
int WaveOpenFile(
	char *pszFileName,                              // (IN)
	HMMIO *phmmioIn,                                // (OUT)
	WAVEFORMATEX **ppwfxInfo,                       // (OUT)
	MMCKINFO *pckInRIFF                             // (OUT)
			)
{
	HMMIO           hmmioIn;
	MMCKINFO        ckIn;           // chunk info. for general use.
	PCMWAVEFORMAT   pcmWaveFormat;  // Temp PCM structure to load in.
	WORD            cbExtraAlloc;   // Extra bytes for waveformatex
	int             nError;         // Return value.


	// Initialization...
	*ppwfxInfo = NULL;
	nError = 0;
	hmmioIn = NULL;

	if ((hmmioIn = mmioOpen(pszFileName, NULL, MMIO_ALLOCBUF | MMIO_READ)) == NULL)
		{
		nError = ER_CANNOTOPEN;
		goto ERROR_READING_WAVE;
		}

	if ((nError = (int)mmioDescend(hmmioIn, pckInRIFF, NULL, 0)) != 0)
		{
		goto ERROR_READING_WAVE;
		}


	if ((pckInRIFF->ckid != FOURCC_RIFF) || (pckInRIFF->fccType != mmioFOURCC('W', 'A', 'V', 'E')))
		{
		nError = ER_NOTWAVEFILE;
		goto ERROR_READING_WAVE;
		}

	/* Search the input file for for the 'fmt ' chunk.     */
    ckIn.ckid = mmioFOURCC('f', 'm', 't', ' ');
    if ((nError = (int)mmioDescend(hmmioIn, &ckIn, pckInRIFF, MMIO_FINDCHUNK)) != 0)
		{
		goto ERROR_READING_WAVE;
		}

	/* Expect the 'fmt' chunk to be at least as large as <PCMWAVEFORMAT>;
    * if there are extra parameters at the end, we'll ignore them */

    if (ckIn.cksize < (long) sizeof(PCMWAVEFORMAT))
		{
		nError = ER_NOTWAVEFILE;
		goto ERROR_READING_WAVE;
		}

	/* Read the 'fmt ' chunk into <pcmWaveFormat>.*/
    if (mmioRead(hmmioIn, (HPSTR) &pcmWaveFormat, (long) sizeof(pcmWaveFormat)) != (long) sizeof(pcmWaveFormat))
		{
		nError = ER_CANNOTREAD;
		goto ERROR_READING_WAVE;
		}


	// Ok, allocate the waveformatex, but if its not pcm
	// format, read the next word, and thats how many extra
	// bytes to allocate.
	if (pcmWaveFormat.wf.wFormatTag == WAVE_FORMAT_PCM)
		cbExtraAlloc = 0;

	else
		{
		// Read in length of extra bytes.
		if (mmioRead(hmmioIn, (LPSTR) &cbExtraAlloc,
			(long) sizeof(cbExtraAlloc)) != (long) sizeof(cbExtraAlloc))
			{
			nError = ER_CANNOTREAD;
			goto ERROR_READING_WAVE;
			}

		}

	// Ok, now allocate that waveformatex structure.
//	if ((*ppwfxInfo = GlobalAlloc(GMEM_FIXED, sizeof(WAVEFORMATEX)+cbExtraAlloc)) == NULL)
//		{
//		nError = ER_MEM;
//		goto ERROR_READING_WAVE;
//		}

	// Copy the bytes from the pcm structure to the waveformatex structure
	memcpy(*ppwfxInfo, &pcmWaveFormat, sizeof(pcmWaveFormat));
	(*ppwfxInfo)->cbSize = cbExtraAlloc;

	// Now, read those extra bytes into the structure, if cbExtraAlloc != 0.
	if (cbExtraAlloc != 0)
		{
		if (mmioRead(hmmioIn, (LPSTR) (((BYTE*)&((*ppwfxInfo)->cbSize))+sizeof(cbExtraAlloc)),
			(long) (cbExtraAlloc)) != (long) (cbExtraAlloc))
			{
			nError = ER_NOTWAVEFILE;
			goto ERROR_READING_WAVE;
			}
		}

	/* Ascend the input file out of the 'fmt ' chunk. */
	if ((nError = mmioAscend(hmmioIn, &ckIn, 0)) != 0)
		{
		goto ERROR_READING_WAVE;

		}


	goto TEMPCLEANUP;

ERROR_READING_WAVE:
	if (*ppwfxInfo != NULL)
		{
		GlobalFree(*ppwfxInfo);
		*ppwfxInfo = NULL;
		}

	if (hmmioIn != NULL)
	{
	mmioClose(hmmioIn, 0);
		hmmioIn = NULL;
		}

TEMPCLEANUP:
	*phmmioIn = hmmioIn;

	return(nError);

}
Exemplo n.º 21
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1,
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA,
		32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 };
	static GLuint PixelFormat;
	static HWND hEdit;
	static HFONT hFont;
	static HINSTANCE hRtLib;
	static BOOL bEditVisible = TRUE;
	static HGLRC hRC;
	switch (msg)
	{
	case WM_CREATE:
		hRtLib = LoadLibrary(TEXT("RICHED32"));
		hFont = CreateFont(24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TEXT("Consolas"));
		hEdit = CreateWindowEx(WS_EX_LAYERED, RICHEDIT_CLASS, 0, WS_VISIBLE | WS_POPUP | WS_HSCROLL |
			WS_VSCROLL | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_NOHIDESEL,
			0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
		SendMessage(hEdit, EM_SETTEXTMODE, TM_PLAINTEXT, 0);
		SendMessage(hEdit, EM_LIMITTEXT, -1, 0);
		EditWndProc = (WNDPROC)SetWindowLong(hEdit, GWL_WNDPROC, (LONG)EditProc);
		SendMessage(hEdit, WM_SETFONT, (WPARAM)hFont, 0);
		if (!(hDC = GetDC(hWnd)) ||
			!(PixelFormat = ChoosePixelFormat(hDC, &pfd)) ||
			!SetPixelFormat(hDC, PixelFormat, &pfd) ||
			!(hRC = wglCreateContext(hDC)) ||
			!wglMakeCurrent(hDC, hRC) ||
			glewInit() != GLEW_OK ||
			!InitGL()) return -1;
		SetWindowText(hEdit, 
			TEXT("#define pi 3.14159265358979\r\n")
			TEXT("uniform float time;\r\n")
			TEXT("void main()\r\n")
			TEXT("{\r\n")
			TEXT("	vec2 p = gl_FragCoord;\r\n")
			TEXT("	float c = 0.0;\r\n")
			TEXT("	for (float i = 0.0; i < 5.0; i++)\r\n")
			TEXT("	{\r\n")
			TEXT("		vec2 b = vec2(\r\n")
			TEXT("		sin(time + i * pi / 7) * 256 + 512,\r\n")
			TEXT("		cos(time + i * pi / 2) * 256 + 384\r\n")
			TEXT("		);\r\n")
			TEXT("		c += 32 / distance(p, b);\r\n")
			TEXT("	}\r\n")
			TEXT("	gl_FragColor = vec4(c*c / sin(time), c*c / 2, c*c, 1.0);\r\n")
			TEXT("}\r\n")
			);
		PostMessage(hWnd, WM_CREATED, 0, 0);
		break;
	case WM_CREATED:
		SendMessage(hWnd, WM_COMMAND, MAKEWPARAM(0, EN_CHANGE), (long)hEdit);
		SendMessage(hEdit, EM_SETEVENTMASK, 0, (LPARAM)(SendMessage(hEdit, EM_GETEVENTMASK, 0, 0) | ENM_CHANGE));
		SetFocus(hEdit);
		PostMessage(hEdit, WM_SETALPHA, SHOWEDITALPHA, 0);
		break;
	case WM_MOVE:
		{
			RECT rect;
			GetClientRect(hWnd, &rect);
			ClientToScreen(hWnd, (LPPOINT)&rect.left);
			ClientToScreen(hWnd, (LPPOINT)&rect.right);
			MoveWindow(hEdit, rect.left + 16, rect.top + 16, rect.right - rect.left - 32, rect.bottom - rect.top - 32, 1);
		}
		break;
	case WM_COMMAND:
		switch (LOWORD(wParam))
		{
		case 0:
			if (HIWORD(wParam) == EN_CHANGE)
			{
				const DWORD dwSize = GetWindowTextLengthA(hEdit);
				if (!dwSize) return 0;
				LPSTR lpszText = (LPSTR)GlobalAlloc(0, (dwSize + 1)*sizeof(CHAR));
				if (!lpszText) return 0;
				GetWindowTextA(hEdit, lpszText, dwSize + 1);
				const GLuint newProgram = CreateProgram(vsrc, lpszText);
				if (newProgram)
				{
					if (program) glDeleteProgram(program);
					program = newProgram;
					SetWindowText(hWnd, TEXT("フラグメントシェーダ [コンパイル成功]"));
				}
				else
				{
					SetWindowText(hWnd, TEXT("フラグメントシェーダ [コンパイル失敗]"));
				}
				GlobalFree(lpszText);
			}
			break;
		case ID_EDITSHOW:
			ShowWindow(hEdit, IsWindowVisible(hEdit) ? SW_HIDE : SW_NORMAL);
			break;
		case ID_SELECTALL:
			if (IsWindowVisible(hEdit))
			{
				SendMessage(hEdit, EM_SETSEL, 0, -1);
				SetFocus(hEdit);
			}
			break;
		}
		break;
	case WM_RBUTTONDOWN:
	case WM_LBUTTONDOWN:
		SendMessage(hWnd, WM_COMMAND, ID_EDITSHOW, 0);
		break;
	case WM_ACTIVATE:
		active = !HIWORD(wParam);
		break;
	case WM_DESTROY:
		DeleteObject(hFont);
		if (program) glDeleteProgram(program);
		if (vbo) glDeleteBuffers(1, &vbo);
		if (vao) glDeleteVertexArrays(1, &vao);
		if (hRC)
		{
			wglMakeCurrent(0, 0);
			wglDeleteContext(hRC);
		}
		if (hDC) ReleaseDC(hWnd, hDC);
		DestroyWindow(hEdit);
		FreeLibrary(hRtLib);
		PostQuitMessage(0);
		break;
	case WM_SYSCOMMAND:
		switch (wParam)
		{
		case SC_SCREENSAVE:
		case SC_MONITORPOWER:
			return 0;
		}
	default:
		return DefWindowProc(hWnd, msg, wParam, lParam);
	}
	return 0;
}
Exemplo n.º 22
0
int WaveLoadFile(
			char *pszFileName,                      // (IN)
			UINT *cbSize,                           // (OUT)
			DWORD *pcSamples,                       // (OUT)
			WAVEFORMATEX **ppwfxInfo,       // (OUT)
			BYTE **ppbData                          // (OUT)
			)
{

	HMMIO                           hmmioIn;
	MMCKINFO                        ckInRiff;
	MMCKINFO                        ckIn;
	int                                     nError;
	UINT                            cbActualRead;

	*ppbData = NULL;
	*ppwfxInfo = NULL;
	*cbSize = 0;

	if ((nError = WaveOpenFile(pszFileName, &hmmioIn, ppwfxInfo, &ckInRiff)) != 0)
		{
		goto ERROR_LOADING;
		}

	if ((nError = WaveStartDataRead(&hmmioIn, &ckIn, &ckInRiff)) != 0)
		{
		goto ERROR_LOADING;
		}

	// Ok, size of wave data is in ckIn, allocate that buffer.
	if ((*ppbData = (BYTE *)GlobalAlloc(GMEM_FIXED, ckIn.cksize)) == NULL)
		{
		nError = ER_MEM;
		goto ERROR_LOADING;
		}

	if ((nError = WaveReadFile(hmmioIn, ckIn.cksize, *ppbData, &ckIn, &cbActualRead)) != 0)
		{
		goto ERROR_LOADING;
		}

	*cbSize = cbActualRead;
	goto DONE_LOADING;

ERROR_LOADING:
	if (*ppbData != NULL)
		{
		GlobalFree(*ppbData);
		*ppbData = NULL;
		}
	if (*ppwfxInfo != NULL)
		{
		GlobalFree(*ppwfxInfo);
		*ppwfxInfo = NULL;
		}

DONE_LOADING:
	// Close the wave file.
	if (hmmioIn != NULL)
		{
		mmioClose(hmmioIn, 0);
		hmmioIn = NULL;
		}

	return(nError);

}
Exemplo n.º 23
0
LRESULT HandleConvertCommand(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
    HIMC hIMC = ImmGetContext(hWndCompStr);
    DWORD dwSel;
    DWORD dwSize;
    LPCANDIDATELIST lpCL = NULL;

    switch(wParam)
    {
        case IDM_CONVERT:
            ImmNotifyIME(hIMC,NI_COMPOSITIONSTR,CPS_CONVERT,0);
            break;

        case IDM_CANCEL:
            ImmNotifyIME(hIMC,NI_COMPOSITIONSTR,CPS_CANCEL,0);
            break;

        case IDM_REVERT:
            ImmNotifyIME(hIMC,NI_COMPOSITIONSTR,CPS_REVERT,0);
            break;

        case IDM_COMPLETE:
            ImmNotifyIME(hIMC,NI_COMPOSITIONSTR,CPS_COMPLETE,0);
            break;

        case IDM_OPENCAND:
            ImmNotifyIME(hIMC,NI_OPENCANDIDATE,0,0);
            break;

        case IDM_CLOSECAND:
            ImmNotifyIME(hIMC,NI_CLOSECANDIDATE,0,0);
            break;

        case IDM_NEXTCAND: /* fall-through */
        case IDM_PREVCAND:
            if (dwSize = ImmGetCandidateList(hIMC,0x0,NULL,0))
            {
                lpCL = (LPCANDIDATELIST)GlobalAlloc(GPTR,dwSize);
        
                ImmGetCandidateList(hIMC,0x0,lpCL,dwSize);
 
                dwSel = lpCL->dwSelection;

                if (wParam == IDM_NEXTCAND)
                {
                   if (++dwSel >= lpCL->dwCount)
                   {
                      dwSel = 0;
                   }
                }
                else
                {
                   if (dwSel)
                   {
                      dwSel--;
                   }
                   else
                   {
                      dwSel = lpCL->dwCount - 1;
                   }
                }
                GlobalFree((HANDLE)lpCL);

                ImmNotifyIME(hIMC,NI_SELECTCANDIDATESTR,0,dwSel);
            }
            break;

    }

    ImmReleaseContext(hWndCompStr,hIMC);

    return 1;
}
Exemplo n.º 24
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static HWND hEdit1, hEdit2, hEdit3, hButton;
	static HWND hStatic1, hStatic2;
	static HWND hCheck;
	switch (msg)
	{
	case WM_CREATE:
		hStatic1 = CreateWindow(TEXT("Static"), TEXT("対象リスト"), WS_VISIBLE | WS_CHILD, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
		hEdit1 = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT(""), WS_VISIBLE | WS_CHILD | WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL | ES_MULTILINE | ES_WANTRETURN, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
		SendMessage(hEdit1, EM_LIMITTEXT, 0, 0);
		hCheck = CreateWindow(TEXT("Button"), TEXT("HTMLエスケープ"), WS_VISIBLE | WS_CHILD | WS_TABSTOP | BS_AUTOCHECKBOX, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
		hEdit3 = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT(""), WS_VISIBLE | WS_CHILD | WS_TABSTOP | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
		hButton = CreateWindow(TEXT("Button"), TEXT(">変換>"), WS_VISIBLE | WS_CHILD | WS_TABSTOP | BS_DEFPUSHBUTTON, 0, 0, 0, 0, hWnd, (HMENU)IDOK, ((LPCREATESTRUCT)lParam)->hInstance, 0);
		hStatic2 = CreateWindow(TEXT("Static"), TEXT("結果リスト"), WS_VISIBLE | WS_CHILD, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
		hEdit2 = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT(""), WS_VISIBLE | WS_CHILD | WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL | ES_MULTILINE | ES_READONLY, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
		SendMessage(hEdit2, EM_LIMITTEXT, 0, 0);
		DragAcceptFiles(hWnd, TRUE);
		break;
	case WM_DROPFILES:
		{
			const HDROP hDrop = (HDROP)wParam;
			const UINT nFiles = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0);
			if (nFiles == 1)
			{
				TCHAR szFileName[MAX_PATH];
				DragQueryFile(hDrop, 0, szFileName, sizeof(szFileName));
				const HANDLE hFile = CreateFile(szFileName, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
				if (hFile != INVALID_HANDLE_VALUE)
				{
					const DWORD dwFileSize = GetFileSize(hFile, 0);
					DWORD dwReadSize;
					LPSTR lpszText = (LPSTR)GlobalAlloc(0, dwFileSize + 1);
					ReadFile(hFile, lpszText, dwFileSize, &dwReadSize, 0);
					lpszText[dwReadSize] = 0;
					SetWindowTextA(hEdit1, lpszText);
					GlobalFree(lpszText);
					CloseHandle(hFile);
				}
			}
			DragFinish(hDrop);
		}
		break;
	case WM_SIZE:
		{
			const int button_width = 128;
			const int width = (LOWORD(lParam) - button_width - 20) / 2;
			MoveWindow(hStatic1, 0, 0, width, 32, TRUE);
			MoveWindow(hEdit1, 0, 32, width, HIWORD(lParam) - 32, TRUE);
			MoveWindow(hCheck, width + 10, HIWORD(lParam) / 2 - 16 - 10 - 32, button_width, 32, TRUE);
			MoveWindow(hEdit3, width + 10, HIWORD(lParam) / 2 - 16, button_width, 32, TRUE);
			MoveWindow(hButton, width + 10, HIWORD(lParam) / 2 + 16 + 10, button_width, 32, TRUE);
			MoveWindow(hStatic2, width + button_width + 20, 0, width, 32, TRUE);
			MoveWindow(hEdit2, width + button_width + 20, 32, width, HIWORD(lParam) - 32, TRUE);
		}
		break;
	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK)
		{
			EnableWindow(hButton, FALSE);
			SetWindowTextA(hEdit2, 0);
			const INT_PTR nEditLineCount1 = SendMessageA(hEdit1, EM_GETLINECOUNT, 0, 0);
			const INT_PTR bHtmlEscape = SendMessageA(hCheck, BM_GETCHECK, 0, 0);
			LPSTR lpszEdit3 = 0;
			const int nEditLenght3 = GetWindowTextLengthA(hEdit3);
			if (nEditLenght3)
			{
				lpszEdit3 = (LPSTR)GlobalAlloc(0, sizeof(CHAR) * (nEditLenght3 + 1));
				GetWindowTextA(hEdit3, lpszEdit3, nEditLenght3 + 1);
			}
			BOOL bIsFound;
			for (INT_PTR i = 0; i < nEditLineCount1; ++i)
			{
				bIsFound = FALSE;
				const INT_PTR nEditLineIndex1 = SendMessageA(hEdit1, EM_LINEINDEX, i, 0);
				const INT_PTR nEditLineLength1 = SendMessageA(hEdit1, EM_LINELENGTH, nEditLineIndex1, 0);
				if (!nEditLineLength1) continue;
				LPSTR lpszEditLine1 = (LPSTR)GlobalAlloc(0, sizeof(CHAR)* (nEditLineLength1 + 1 + 2)); // 改行文字2文字分追加
				*(WORD *)lpszEditLine1 = (WORD)nEditLineLength1;
				SendMessageA(hEdit1, EM_GETLINE, i, (LPARAM)lpszEditLine1);
				lpszEditLine1[nEditLineLength1] = 0;
				{
					const std::string target(lpszEditLine1);
					std::regex re(R"(https?://[-_.!~*\'()a-zA-Z0-9;/?:@&=+$,%#]+)");
					std::smatch match;
					for (auto it = target.begin(); regex_search(it, target.end(), match, re); it += match.position(0) + match.length(0))
					{
						std::string str(match.str(0));
						if (bHtmlEscape)
						{
							str = Replace(str, "&amp;", "&");
							str = Replace(str, "%3D", "=");
							str = Replace(str, "%22", "\"");
							str = Replace(str, "%20", " ");
						}
						if (!lpszEdit3 || StrStrIA(str.c_str(), lpszEdit3))
						{
							INT_PTR dwEditTextLength = SendMessageA(hEdit2, WM_GETTEXTLENGTH, 0, 0);
							SendMessageA(hEdit2, EM_SETSEL, dwEditTextLength, dwEditTextLength);
							SendMessageA(hEdit2, EM_REPLACESEL, 0, (LPARAM)str.c_str());
							SendMessageA(hEdit2, EM_REPLACESEL, 0, (LPARAM)"\r\n");
						}
					}
				}
				GlobalFree(lpszEditLine1);
			}
			if (lpszEdit3)
			{
				GlobalFree(lpszEdit3);
			}
			SendMessageA(hEdit2, EM_SETSEL, 0, -1);
			SetFocus(hEdit2);
			EnableWindow(hButton, TRUE);
		}
		break;
	case WM_CLOSE:
		DestroyWindow(hWnd);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefDlgProc(hWnd, msg, wParam, lParam);
	}
	return 0;
}
Exemplo n.º 25
0
void STDMETHODCALLTYPE IECrossfireBHO::OnDocumentComplete(IDispatch *pDisp, VARIANT *pvarURL) {
	BSTR bstr = pvarURL->bstrVal;
	if (bstr && m_htmlToDisplay && wcscmp(bstr, ABOUT_BLANK) == 0) {
		CComPtr<IUnknown> webBrowserIUnknown = NULL;
		HRESULT hr = m_webBrowser->QueryInterface(IID_IUnknown, (void**)&webBrowserIUnknown);
		if (SUCCEEDED(hr)) {
			CComPtr<IUnknown> pDispIUnknown = NULL;
			hr = pDisp->QueryInterface(IID_IUnknown, (void**)&pDispIUnknown);
			if (SUCCEEDED(hr)) {
				if (webBrowserIUnknown == pDispIUnknown) {
					/* this is the top-level page frame */
					size_t length = (wcslen(m_htmlToDisplay) + 1) * 2;
					HGLOBAL buffer = GlobalAlloc(GPTR, length);
					if (buffer) {
						wcscpy_s((wchar_t*)buffer, length, m_htmlToDisplay);
						CComPtr<IStream> stream = NULL;
						HRESULT hr = CreateStreamOnHGlobal(buffer, false, &stream);
						if (SUCCEEDED(hr)) {
							CComPtr<IDispatch> document = NULL;
							HRESULT hr = m_webBrowser->get_Document(&document);
							if (SUCCEEDED(hr)) {
								CComPtr<IPersistStreamInit> persistStreamInit = NULL;
								hr = document->QueryInterface(IID_IPersistStreamInit, (void**)&persistStreamInit);
								if (SUCCEEDED(hr)) {
									hr = persistStreamInit->InitNew();
									if (SUCCEEDED(hr)) {
										hr = persistStreamInit->Load(stream);
									}
								}
							}
							if (FAILED(hr)) {
								Logger::error("IECrossfireBHO.OnDocumentComplete(): failed setting page content", hr);
							}
						} else {
							Logger::error("IECrossfireBHO.OnDocumentComplete(): CreateStreamOnHGlobal() failed", hr);
						}
						GlobalFree(buffer);
					}
					free(m_htmlToDisplay);
					m_htmlToDisplay = NULL;
				}
			}
		}
		if (FAILED(hr)) {
			Logger::error("IECrossfireBHO.OnDocumentComplete() failed", hr);
		}
		return;
	}

	if (m_serverState != STATE_CONNECTED) {
		return;
	}

	CComPtr<IUnknown> webBrowserIUnknown = NULL;
	HRESULT hr = m_webBrowser->QueryInterface(IID_IUnknown, (void**)&webBrowserIUnknown);
	if (FAILED(hr)) {
		Logger::error("IECrossfireBHO.OnDocumentComplete(): QI(IUnknown)[1] failed", hr);
	} else {
		CComPtr<IUnknown> pDispIUnknown = NULL;
		hr = pDisp->QueryInterface(IID_IUnknown, (void**)&pDispIUnknown);
		if (FAILED(hr)) {
			Logger::error("IECrossfireBHO.OnDocumentComplete(): QI(IUnknown)[2] failed", hr);
		} else {
			if (webBrowserIUnknown == pDispIUnknown) {
				/* this is the top-level page frame */
				HRESULT hr = m_server->contextLoaded(GetCurrentProcessId());
				if (FAILED(hr)) {
					Logger::error("IECrossfireBHO.OnDocumentComplete(): contextLoaded() failed", hr);
				}
			}
		}
	}
}
Exemplo n.º 26
0
//
//  FUNCTION: About(HWND, unsigned, WORD, LONG)
//
//  PURPOSE:  Processes messages for "About" dialog box
//       This version allows greater flexibility over the contents of the 'About' box,
//       by pulling out values from the 'Version' resource.
//
//  MESSAGES:
//
// WM_INITDIALOG - initialize dialog box
// WM_COMMAND    - Input received
//
//
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
   static  HFONT hfontDlg;    // Font for dialog text
   static   HFONT hFinePrint; // Font for 'fine print' in dialog
   DWORD   dwVerInfoSize;     // Size of version information block
   LPSTR   lpVersion;         // String pointer to 'version' text
   DWORD   dwVerHnd=0;        // An 'ignored' parameter, always '0'
   UINT    uVersionLen;
   BOOL    bRetCode;
   int     i;
   char    szFullPath[256];
   char    szResult[256];
   char    szGetName[256];
   DWORD dwVersion;
   char  szVersion[40];
   DWORD dwResult;

   switch (message)
   {
   case WM_INITDIALOG:
      ShowWindow (hDlg, SW_HIDE);

      if (PRIMARYLANGID(GetUserDefaultLangID()) == LANG_JAPANESE)
      {
         hfontDlg = CreateFont(14, 0, 0, 0, 0, 0, 0, 0, SHIFTJIS_CHARSET, 0, 0, 0,
                               VARIABLE_PITCH | FF_DONTCARE, "");
         hFinePrint = CreateFont(11, 0, 0, 0, 0, 0, 0, 0, SHIFTJIS_CHARSET, 0, 0, 0,
                                 VARIABLE_PITCH | FF_DONTCARE, "");
      }
      else
      {
         hfontDlg = CreateFont(14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                               VARIABLE_PITCH | FF_SWISS, "");
         hFinePrint = CreateFont(11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                 VARIABLE_PITCH | FF_SWISS, "");
      }

      CenterWindow (hDlg, GetWindow (hDlg, GW_OWNER));
      GetModuleFileName (hInst, szFullPath, sizeof(szFullPath));

      // Now lets dive in and pull out the version information:
      dwVerInfoSize = GetFileVersionInfoSize(szFullPath, &dwVerHnd);
      if (dwVerInfoSize)
      {
         LPSTR   lpstrVffInfo;
         HANDLE  hMem;
         hMem = GlobalAlloc(GMEM_MOVEABLE, dwVerInfoSize);
         lpstrVffInfo  = GlobalLock(hMem);
         GetFileVersionInfo(szFullPath, dwVerHnd, dwVerInfoSize, lpstrVffInfo);
         // The below 'hex' value looks a little confusing, but
         // essentially what it is, is the hexidecimal representation
         // of a couple different values that represent the language
         // and character set that we are wanting string values for.
         // 040904E4 is a very common one, because it means:
         //   US English, Windows MultiLingual characterset
         // Or to pull it all apart:
         // 04------        = SUBLANG_ENGLISH_USA
         // --09----        = LANG_ENGLISH
         // --11----        = LANG_JAPANESE
         // ----04E4 = 1252 = Codepage for Windows:Multilingual

         _snprintf_s(szGetName, 256, _TRUNCATE, "%sProductName", GetStringRes(IDS_VER_INFO_LANG));

         // Set the title of the dialog:
         bRetCode = VerQueryValue((LPVOID)lpstrVffInfo,
                                  (LPSTR)szGetName,
                                  (LPVOID)&lpVersion,
                                  (UINT *)&uVersionLen);

         // Notice order of version and string...
         if (PRIMARYLANGID(GetUserDefaultLangID()) == LANG_JAPANESE)
         {
            _snprintf_s(szResult, 256, _TRUNCATE, "%s のバージョン情報", lpVersion);
         }
         else
         {
            _snprintf_s(szResult, 256, _TRUNCATE, "About %s", lpVersion);
         }

         // -----------------------------------------------------

         SetWindowText (hDlg, szResult);

         // Walk through the dialog items that we want to replace:
         for (i = DLG_VERFIRST; i <= DLG_VERLAST; i++)
         {
            GetDlgItemText(hDlg, i, szResult, sizeof(szResult));
            _snprintf_s(szGetName, 256, _TRUNCATE, "%s%s", GetStringRes(IDS_VER_INFO_LANG), szResult);
            uVersionLen   = 0;
            lpVersion     = NULL;
            bRetCode      =  VerQueryValue((LPVOID)lpstrVffInfo,
                                           (LPSTR)szGetName,
                                           (LPVOID)&lpVersion,
                                           (UINT *)&uVersionLen);

            if ( bRetCode && uVersionLen && lpVersion)
            {
               // Replace dialog item text with version info
               strncpy_s(szResult, 256, lpVersion, _TRUNCATE);
               SetDlgItemText(hDlg, i, szResult);
            }
            else
            {
               dwResult = GetLastError();

               _snprintf_s(szResult, 256, _TRUNCATE, GetStringRes(IDS_VERSION_ERROR), dwResult);
               SetDlgItemText (hDlg, i, szResult);
            }
            SendMessage (GetDlgItem (hDlg, i), WM_SETFONT,
                         (UINT_PTR)((i==DLG_VERLAST)?hFinePrint:hfontDlg),
                         TRUE);
         } // for (i = DLG_VERFIRST; i <= DLG_VERLAST; i++)


         GlobalUnlock(hMem);
         GlobalFree(hMem);

      }
      else
      {
         // No version information available.

      } // if (dwVerInfoSize)

      SendMessage (GetDlgItem (hDlg, IDC_LABEL), WM_SETFONT,
                   (WPARAM)hfontDlg,(LPARAM)TRUE);

      // We are  using GetVersion rather then GetVersionEx
      // because earlier versions of Windows NT and Win32s
      // didn't include GetVersionEx:
      dwVersion = GetVersion();

      if (dwVersion < 0x80000000)
      {
         // Windows NT
         _snprintf_s(szVersion, 40, _TRUNCATE, "Microsoft Windows NT %u.%u (Build: %u)",
                   (DWORD)(LOBYTE(LOWORD(dwVersion))),
                   (DWORD)(HIBYTE(LOWORD(dwVersion))),
                   (DWORD)(HIWORD(dwVersion)) );
      }
      else if (LOBYTE(LOWORD(dwVersion))<4)
      {
         // Win32s
         _snprintf_s(szVersion, 40, _TRUNCATE, "Microsoft Win32s %u.%u (Build: %u)",
                   (DWORD)(LOBYTE(LOWORD(dwVersion))),
                   (DWORD)(HIBYTE(LOWORD(dwVersion))),
                   (DWORD)(HIWORD(dwVersion) & ~0x8000) );
      }
      else
      {
         // Windows 95
         _snprintf_s(szVersion, 40, _TRUNCATE, "Microsoft Windows 95 %u.%u",
                   (DWORD)(LOBYTE(LOWORD(dwVersion))),
                   (DWORD)(HIBYTE(LOWORD(dwVersion))) );
      }

      SetWindowText (GetDlgItem(hDlg, IDC_OSVERSION), szVersion);
      ShowWindow (hDlg, SW_SHOW);
      return (TRUE);

   case WM_COMMAND:
      if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
      {
         EndDialog(hDlg, TRUE);
         DeleteObject (hfontDlg);
         DeleteObject (hFinePrint);
         return (TRUE);
      }
      break;
   }

   return FALSE;
}
Exemplo n.º 27
0
int audio_play_samples(struct audio_info_struct *ai,unsigned char *buf,int len)
{
   HGLOBAL hg, hg2;
   LPWAVEHDR wh;
   MMRESULT res;
   void *b;

   ///////////////////////////////////////////////////////
   //  Wait for a few FREE blocks...
   ///////////////////////////////////////////////////////
   while(nBlocks > MAX_BLOCKS)
       Sleep(77);

   ////////////////////////////////////////////////////////
   // FIRST allocate some memory for a copy of the buffer!
   ////////////////////////////////////////////////////////
   hg2 = GlobalAlloc(GMEM_MOVEABLE, len);
   if(!hg2)
   {
       MessageBox(NULL, "GlobalAlloc failed!", "Error...",  MB_OK);
       return(-1);
   }
   b = GlobalLock(hg2);


   //////////////////////////////////////////////////////////
   // Here we can call any modification output functions we want....
   ///////////////////////////////////////////////////////////
   CopyMemory(b, buf, len);

   ///////////////////////////////////////////////////////////
   // now make a header and WRITE IT!
   ///////////////////////////////////////////////////////////
   hg = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof (WAVEHDR));
   if(!hg)
   {
       return -1;
   }
   wh = GlobalLock(hg);
   wh->dwBufferLength = len;
   wh->lpData = b;


   EnterCriticalSection( &cs );

   res = waveOutPrepareHeader(dev, wh, sizeof (WAVEHDR));
   if(res)
   {
       GlobalUnlock(hg);
       GlobalFree(hg);
       LeaveCriticalSection( &cs );
       return -1;
   }

   res = waveOutWrite(dev, wh, sizeof (WAVEHDR));
   if(res)
   {
       GlobalUnlock(hg);
       GlobalFree(hg);
       LeaveCriticalSection( &cs );
       return (-1);
   }

   nBlocks++;

   LeaveCriticalSection( &cs );

   return(len);
}
Exemplo n.º 28
0
void CAddEdit_Attachment::ShowPreview()
{
  CItemAtt &att = M_attachment();
  HRESULT hr(S_OK);

  int rc(0);

  // Assume not an image
  m_attType = ATTACHMENT_NOT_IMAGE;

  if (!att.HasContent()) {
    // No content so filename must not be empty
    if (m_AttFileName.IsEmpty())
      return;

    int status = att.Import(LPCWSTR(m_AttFileName));
    if (status != PWScore::SUCCESS) {
      // most likely file error - TBD better error reporting
      rc = 1;
      goto load_error;
    }

    // Get media type before we find we can't load it
    m_csMediaType = att.GetMediaType().c_str();

    // Get other properties
    wchar_t szFileSize[256];
    StrFormatByteSize(att.GetContentSize(), szFileSize, 256);
    m_csSize = szFileSize;
    m_csFileCTime = att.GetFileCTime().c_str();
    if (m_csFileCTime.IsEmpty())
      m_csFileCTime.LoadString(IDS_NA);
    m_csFileMTime = att.GetFileMTime().c_str();
    if (m_csFileMTime.IsEmpty())
      m_csFileMTime.LoadString(IDS_NA);

    if (m_csMediaType.Left(5) == L"image") {
      // Should be an image file - but may not be supported by CImage - try..
      hr = m_AttImage.Load(m_AttFileName);
      if (SUCCEEDED(hr)) {
        hr = m_stImgAttachment.Load(m_AttFileName);
      } 

      if (SUCCEEDED(hr)) {
        // Success - was an image
        m_attType = ATTACHMENT_IS_IMAGE;
      }
    }

    // Create UUID if not already present
    if (!att.HasUUID())
      att.CreateUUID();
  } else {// att.HasContent()
    // This should only be the case during the InitDialog - maybe m_bInitDone
    // in the logic for this processing rather than att.HasContent
    ASSERT(!m_bInitdone);

    if (m_csMediaType.Left(5) == L"image") {
      // Should be an image file - but may not be supported by CImage - try..
      // Allocate attachment buffer
      UINT imagesize = (UINT)att.GetContentSize();
      HGLOBAL gMemory = GlobalAlloc(GMEM_MOVEABLE, imagesize);
      ASSERT(gMemory);

      if (gMemory == NULL) {
        rc = 2;
        goto load_error;
      }

      BYTE *pBuffer = (BYTE *)GlobalLock(gMemory);
      ASSERT(pBuffer);

      if (pBuffer == NULL) {
        rc = 3;
        GlobalFree(gMemory);
        goto load_error;
      }

      // Load image into buffer
      att.GetContent(pBuffer, imagesize);

      // Put it into a IStream
      IStream *pStream = NULL;
      hr = CreateStreamOnHGlobal(gMemory, FALSE, &pStream);
      if (SUCCEEDED(hr)) {
        // Load it
        hr = m_AttImage.Load(pStream);
        if (SUCCEEDED(hr)) {
          hr = m_stImgAttachment.Load(pStream);
        }
      }

      // Clean up - no real need to trash the buffer
      if (pStream != NULL)
        pStream->Release();

      GlobalUnlock(gMemory);
      GlobalFree(gMemory);

      // Check image load (or previous error of putting content into an IStream)
      if (FAILED(hr)) {
        goto load_error;
      }

      // Success - was an image
      m_attType = ATTACHMENT_IS_IMAGE;
    }
  }

  return;

load_error:
  // Ooops???
  m_stImgAttachment.IssueError(rc, hr);
}
Exemplo n.º 29
0
 ~AutoGrobalFree() {
    GlobalFree(m_hGlobal);
 }
Exemplo n.º 30
0
bool SaveFile(LPCSTR pszFile, int iCodePage, bool bSaveCopy)
{
  HANDLE hFile;
  bool   bWriteSuccess;
  
  LPSTR lpData;
  DWORD cbData;
  DWORD dwBytesWritten;
  
  hFile = CreateFile(pszFile,
                     GENERIC_WRITE,
                     FILE_SHARE_READ|FILE_SHARE_WRITE,
                     NULL,
                     CREATE_ALWAYS,
                     FILE_ATTRIBUTE_NORMAL,
                     NULL);

  // failure could be due to missing attributes (2k/XP)
  if (hFile == INVALID_HANDLE_VALUE)
  {
    DWORD dwAttributes = GetFileAttributes(pszFile);
    if (dwAttributes != 0) // INVALID_FILE_ATTRIBUTES FILE_ATTRIBUTE_READONLY
    {
      dwAttributes = dwAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM);
      hFile = CreateFile(pszFile,
                        GENERIC_WRITE,
                        FILE_SHARE_READ|FILE_SHARE_WRITE,
                        NULL,
                        CREATE_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL | dwAttributes,
                        NULL);
    }
  }

  if (hFile == INVALID_HANDLE_VALUE)
    return FALSE;

  // get text
  cbData = SendMessage(hwnd,SCI_GETLENGTH,0,0);
  lpData = GlobalAlloc(GPTR,cbData + 1);
  SendMessage(hwnd,SCI_GETTEXT,GlobalSize(lpData),(LPARAM)lpData);
  
  if (cbData == 0)
    bWriteSuccess = SetEndOfFile(hFile);

  else
  {
    if (iCodePage & NCP_UNICODE)
    {
      LPWSTR lpDataWide;
      int    cbDataWide;
      CPINFO cpi;
      UINT   uCP_UTF8;

      // UTF-8 text is interpreted as ANSI when saving as Unicode on Windows 95
      uCP_UTF8 = (GetCPInfo(CP_UTF8, &cpi) || IsValidCodePage(CP_UTF8)) ? CP_UTF8 : CP_ACP;

      lpDataWide = GlobalAlloc(GPTR,cbData * 2 + 16);
      cbDataWide = MultiByteToWideChar(uCP_UTF8,0,lpData,cbData,lpDataWide,GlobalSize(lpDataWide));

      if (iCodePage & NCP_UNICODE_BOM) 
      {
        if (iCodePage & NCP_UNICODE_REVERSE)
          WriteFile(hFile,(LPCVOID)"\xFE\xFF",2,&dwBytesWritten,NULL);
        else
          WriteFile(hFile,(LPCVOID)"\xFF\xFE",2,&dwBytesWritten,NULL); 
      }
      
      if (iCodePage & NCP_UNICODE_REVERSE)
      {
        _swab((char*)lpDataWide,(char*)lpDataWide,cbDataWide * sizeof(WCHAR));
      }

      bWriteSuccess = WriteFile(hFile,lpDataWide,cbDataWide * sizeof(WCHAR),&dwBytesWritten,NULL);

      GlobalFree(lpData);
    }

    else if (iCodePage & NCP_UTF8)
    {
      if (iCodePage & NCP_UTF8_SIGN)
        WriteFile(hFile,(LPCVOID)"\xEF\xBB\xBF",3,&dwBytesWritten,NULL);

      bWriteSuccess = WriteFile(hFile,lpData,cbData,&dwBytesWritten,NULL);
    }

    else // convert text to 8bit
    {
      //LPWSTR lpDataWide = GlobalAlloc(GPTR,cbData * 2 + 16);
      //int    cbDataWide = MultiByteToWideChar(CP_UTF8,0,lpData,cbData,lpDataWide,GlobalSize(lpDataWide));

      //ZeroMemory(lpData,GlobalSize(lpData));
      //cbData = WideCharToMultiByte(CP_ACP,0,lpDataWide,cbDataWide,lpData,GlobalSize(lpData),NULL,NULL);
      //GlobalFree(lpDataWide);

      bWriteSuccess = WriteFile(hFile,lpData,cbData,&dwBytesWritten,NULL);

      GlobalFree(lpData);
    }
  }

  CloseHandle(hFile);

  if (bWriteSuccess)
  {
    if (!bSaveCopy)
      SendMessage(hwnd,SCI_SETSAVEPOINT,0,0);

    return TRUE;
  }

  else
    return FALSE;

}