Example #1
0
void CMainDialog::OnCmdClipboard(UINT, int, HWND)
{
	HANDLE hData = NULL;
	LPTSTR lptstr = NULL;
	CString strIdKey;
	CString strSNDigit;
	CString strIdKeys;

	if (!IsClipboardFormatAvailable(CF_TTEXT))
		return;

	if (!OpenClipboard())
		return;

	hData = GetClipboardData(CF_TTEXT);
	if (hData == NULL)
		goto end;
	
	lptstr = (LPTSTR)GlobalLock(hData);
	if (!lptstr)
		goto end;

	ATLTRACE(_T("lptstr(%s) "), lptstr);

	// scan & check Mac Address
	int len = _tcslen(lptstr);
	int nMacNibbles = 0;
	TCHAR nibbles[12];

	for (int i = 0; i < len; i++)
	{
		TCHAR x = _totupper(lptstr[i]);
		switch(_totupper(lptstr[i]))
		{
		case _T('0'): case _T('1'): case _T('2'): case _T('3'): case _T('4'): 
		case _T('5'): case _T('6'): case _T('7'): case _T('8'): case _T('9'): 
		case _T('A'): case _T('B'): case _T('C'): case _T('D'): case _T('E'): case _T('F'):
			if (nMacNibbles < 12)
			{
				nibbles[nMacNibbles] = _totupper(lptstr[i]);
				nMacNibbles++;
			}

			if (nMacNibbles == 12)
			{
				TCHAR hex[3] = {0,};
				for (int i = 0; i < 6; i++)
				{
					hex[0] = nibbles[i * 2];
					hex[1] = nibbles[i * 2 +1];
					m_wndAddresses[i].SetWindowText(hex);

				}

				SendMessage(WM_COMMAND, IDOK);

				strIdKey.Empty();
				_GetNdasIdString(strIdKey);

				strSNDigit = pGetSNDigitString(nibbles);

				strIdKeys += strSNDigit + " " + strIdKey + _T("\r\n");

				nMacNibbles = 0;
			}

			break;
		}
	}

	GlobalUnlock(hData);
	lptstr = NULL;

	len = strIdKeys.GetLength();
	HANDLE hAlloc = GlobalAlloc(GMEM_MOVEABLE, (len + 1) * sizeof(TCHAR));
	if (NULL == hAlloc)
		goto end;

	LPVOID lpData = GlobalLock(hAlloc);
	CopyMemory(lpData, static_cast<LPCTSTR>(strIdKeys), (len + 1) * sizeof(TCHAR));
	GlobalUnlock(hAlloc);

	EmptyClipboard();

	SetClipboardData(CF_TTEXT, hAlloc);

	ATLTRACE(strIdKeys);

end:
	if (lptstr && hData)
	{
		GlobalUnlock(hData);
		lptstr = NULL;
	}

	if (hData)
	{
		CloseClipboard();
		hData = NULL;
	}
}
Example #2
0
BOOL RtfNotify(HWND hDlg, NMHDR* nmhdr)
{
    static BOOL FindFirst = TRUE;
#define BUFF_LEN 2048
    static TCHAR FindWhat[BUFF_LEN];

    if (nmhdr->code == EN_PROTECTED && !PuttingChar) {
        //block
        ENPROTECTED* enp = (ENPROTECTED*) nmhdr;
        CHARRANGE cr;
        INT TextLen = RtfWindowTextLength();
        BOOL Reset = FALSE, Disallow = FALSE;


        // just let it go ahead anyway
        if (enp->msg == WM_COPY)
            return FALSE;

        // they hit backspace
        if (enp->wParam == VK_BACK) {
            if ((DWORD) enp->chrg.cpMin < StartOfInput ||
                    ((DWORD) enp->chrg.cpMin == StartOfInput &&
                     enp->chrg.cpMin == enp->chrg.cpMax)) {
                Reset = TRUE;
                Disallow = TRUE;
            }
        } else if ((DWORD) enp->chrg.cpMin < StartOfInput) {
            Reset = TRUE;
            Disallow = (enp->wParam == VK_DELETE);
        }

        if (Reset) {
            cr.cpMin = TextLen;
            cr.cpMax = cr.cpMin;
            SendMessage(hWndRtf, EM_EXSETSEL, 0, (LPARAM) &cr);
        }

        // we don't want to paste rich text, as that makes it look weird
        // so send only plain text paste commands
        if ((enp->msg == WM_PASTE) && !Disallow) {
            LPTSTR Buffer = NULL;
            Disallow = TRUE;
#if defined _UNICODE
#define CLIP_FORMAT  CF_UNICODETEXT
#else
#define CLIP_FORMAT  CF_TEXT
#endif
            if (IsClipboardFormatAvailable(CLIP_FORMAT) &&
                    OpenClipboard(hWndMain)) {
                HGLOBAL hGlb;
                LPTSTR str;

                if ((hGlb = GetClipboardData(CLIP_FORMAT)) != NULL &&
                        (str = GlobalLock(hGlb)) != NULL) {
                    Buffer = StringDup(str);
                    GlobalUnlock(hGlb);
                }
                CloseClipboard();
            }

            if (Buffer != NULL) {
                // strip trailing new line characters
                INT i;
                for (i = StringLen(Buffer)-1;
                        i >= 0 && (Buffer[i] == TEXT('\r') || Buffer[i] == TEXT('\n'));
                        i--)
                    Buffer[i] = 0;

#if defined _UNICODE
                {
                    SETTEXTEX stt;

                    stt.codepage = CP_UNICODE;
                    stt.flags = ST_SELECTION;
                    SendMessage(hWndRtf,EM_SETTEXTEX,(WPARAM)&stt,(LPARAM)Buffer);
                }
#else
                SendMessage(hWndRtf, EM_REPLACESEL, FALSE, (LPARAM)Buffer);
#endif


                free(Buffer);
            }
        }

        return (Disallow ? TRUE : FALSE);
    } else if (nmhdr->code == EN_LINK) {
        // should really fire on up
        // but that screws up the cursor position

        ENLINK* enl = (ENLINK*) nmhdr;
        if (enl->msg == WM_LBUTTONDOWN) {
            TEXTRANGE tr;
            TCHAR Buffer[1000];
            tr.lpstrText = Buffer;
            tr.chrg.cpMin = enl->chrg.cpMin;
            tr.chrg.cpMax = enl->chrg.cpMax;

            SendMessage(hWndRtf, EM_GETTEXTRANGE, 0, (LPARAM) &tr);
            ExecuteFile(Buffer);

            return TRUE;
        }
    } else if (nmhdr->code == EN_MSGFILTER) {
        MSGFILTER* mf = (MSGFILTER*) nmhdr;
#if 0
        //if (mf->msg == WM_CHAR && Running) {
        if (mf->msg == WM_CHAR && 0) {
            WinGHCiReceiveC((TCHAR)mf->wParam == TEXT('\r') ? TEXT('\n') : mf->wParam);
            SetWindowLong(hDlg, DWL_MSGRESULT, 1);
            return FALSE;
        } //else if (Running && mf->msg == WM_KEYDOWN) {
        else if (0) {
            SHORT n = GetKeyState(VK_CONTROL);
            BOOL Control = (n & (1 << 16));
            if(((CHAR)(mf->wParam) ==(CHAR)TEXT('C')) && Control)
                AbortExecution();
            else
                SetWindowLong(hDlg, DWL_MSGRESULT, 1);
            return FALSE;
        } //else if (mf->msg == WM_KEYDOWN && !Running) {
        else
#endif


            if (mf->msg == WM_CHAR) {

                if (mf->wParam == VK_TAB) {

                    INT pos;

                    if(FindFirst) {
                        RtfWindowGetCommand(FindWhat,BUFF_LEN);
                        pos = FindFirstHistory(FindWhat);
                        FindFirst = FALSE;
                    } else
                        pos = FindNextHistory();

                    if(pos>=0)
                        RtfWindowSetCommand(GoToHistory(pos));
                    else
                        MessageBeep((UINT)-1);

                    return TRUE;

                } else {
                    // any other key resets search
                    FindFirst = TRUE;

                    if (mf->wParam == VK_ESCAPE) {

                        //Clear current command
                        RtfWindowSetCommand(TEXT(""));
                        // Go to last item in history
                        AddHistory(TEXT(""));
                        return TRUE;
                    } else {
                        return FALSE;
                    }
                }


            } else if (mf->msg == WM_KEYDOWN) {
                BOOL History = (mf->wParam == VK_UP || mf->wParam == VK_DOWN);
                SHORT n = GetKeyState(VK_CONTROL);
                BOOL Control = (n & (1 << 16));

                if(((CHAR)(mf->wParam) ==(CHAR)TEXT('C')) && Control) {
                    if(RtfWindowCanCutCopy() && DROPEFFECT_COPY)
                        RtfWindowClipboard(WM_COPY);
                    else
                        AbortExecution();
                } else if (History && (mf->lParam & (1 << 24))) {
                    CHARRANGE cr;
                    SendMessage(hWndRtf, EM_EXGETSEL, 0, (LPARAM) &cr);
                    if ((DWORD) cr.cpMin >= StartOfInput) {
                        RtfWindowRelativeHistory(mf->wParam == VK_UP ? -1 : +1);
                        return TRUE;
                    }
                } else if (mf->wParam == VK_RETURN) {
#define BUFF_LEN 2048
                    TCHAR Buffer[BUFF_LEN];


                    RtfWindowGetCommand(Buffer,BUFF_LEN);

                    if(Running) {
                        if(!(mf->lParam & (1<<30))) //avoid repetition
                            FireCommandExt(Buffer,FALSE,TRUE,FALSE,FALSE);
                    }
                    else
                        //if(!(mf->lParam & (1<<30)))
                        FireAsyncCommand(Buffer);
                    return TRUE;
                } else if (mf->wParam == VK_HOME) {
                    CHARRANGE cr;
                    SendMessage(hWndRtf, EM_EXGETSEL, 0, (LPARAM) &cr);
                    if ((DWORD) cr.cpMin >= StartOfInput) {
                        SHORT n = GetKeyState(VK_SHIFT);
                        BOOL Shift = (n & (1 << 16));

                        cr.cpMin = StartOfInput;
                        cr.cpMax = (Shift ? cr.cpMax : StartOfInput);
                        SendMessage(hWndRtf, EM_EXSETSEL, 0, (LPARAM) &cr);
                        return TRUE;
                    }
                }
            }
    } else if (nmhdr->code == EN_SELCHANGE) {
        EnableButtons();
        return FALSE;
    }

    return FALSE;
}
Example #3
0
bool ClipboardIsFormatAvailableHDROP()
{
  return BOOLToBool(IsClipboardFormatAvailable(CF_HDROP));
}
Example #4
0
void
win_update_menus(void)
{
  bool shorts = !term.shortcut_override;
  bool clip = shorts && cfg.clip_shortcuts;
  bool alt_fn = shorts && cfg.alt_fn_shortcuts;
  bool ct_sh = shorts && cfg.ctrl_shift_shortcuts;

  ModifyMenu(
    sysmenu, IDM_NEW, 0, IDM_NEW,
    alt_fn ? "Ne&w\tAlt+F2" : ct_sh ? "Ne&w\tCtrl+Shift+N" : "Ne&w"
  );
  ModifyMenu(
    sysmenu, SC_CLOSE, 0, SC_CLOSE,
    alt_fn ? "&Close\tAlt+F4" : ct_sh ? "&Close\tCtrl+Shift+W" : "&Close"
  );

  uint sel_enabled = term.selected ? MF_ENABLED : MF_GRAYED;
  EnableMenuItem(menu, IDM_OPEN, sel_enabled);
  ModifyMenu(
    menu, IDM_COPY, sel_enabled, IDM_COPY,
    clip ? "&Copy\tCtrl+Ins" : ct_sh ? "&Copy\tCtrl+Shift+C" : "&Copy"
  );

  uint paste_enabled =
    IsClipboardFormatAvailable(CF_TEXT) ||
    IsClipboardFormatAvailable(CF_UNICODETEXT) ||
    IsClipboardFormatAvailable(CF_HDROP)
    ? MF_ENABLED : MF_GRAYED;
  ModifyMenu(
    menu, IDM_PASTE, paste_enabled, IDM_PASTE,
    clip ? "&Paste\tShift+Ins" : ct_sh ? "&Paste\tCtrl+Shift+V" : "&Paste"
  );

  ModifyMenu(
    menu, IDM_SEARCH, 0, IDM_SEARCH,
    alt_fn ? "S&earch\tAlt+F3" : ct_sh ? "S&earch\tCtrl+Shift+H" : "S&earch"
  );

  ModifyMenu(
    menu, IDM_RESET, 0, IDM_RESET,
    alt_fn ? "&Reset\tAlt+F8" : ct_sh ? "&Reset\tCtrl+Shift+R" : "&Reset"
  );

  uint defsize_enabled =
    IsZoomed(wnd) || term.cols != cfg.cols || term.rows != cfg.rows
    ? MF_ENABLED : MF_GRAYED;
  ModifyMenu(
    menu, IDM_DEFSIZE_ZOOM, defsize_enabled, IDM_DEFSIZE_ZOOM,
    alt_fn ? "&Default size\tAlt+F10" :
    ct_sh ? "&Default size\tCtrl+Shift+D" : "&Default size"
  );

  uint fullscreen_checked = win_is_fullscreen ? MF_CHECKED : MF_UNCHECKED;
  ModifyMenu(
    menu, IDM_FULLSCREEN_ZOOM, fullscreen_checked, IDM_FULLSCREEN_ZOOM,
    alt_fn ? "&Full Screen\tAlt+F11" :
    ct_sh ? "&Full Screen\tCtrl+Shift+F" : "&Full Screen"
  );

  uint otherscreen_checked = term.show_other_screen ? MF_CHECKED : MF_UNCHECKED;
  ModifyMenu(
    menu, IDM_FLIPSCREEN, otherscreen_checked, IDM_FLIPSCREEN,
    alt_fn ? "Flip &Screen\tAlt+F12" :
    ct_sh ? "Flip &Screen\tCtrl+Shift+S" : "Flip &Screen"
  );

  uint options_enabled = config_wnd ? MF_GRAYED : MF_ENABLED;
  EnableMenuItem(menu, IDM_OPTIONS, options_enabled);
  EnableMenuItem(sysmenu, IDM_OPTIONS, options_enabled);
}
//------------------------------------------------------------------------------
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms649016%28v=vs.85%29.aspx
DWORD WINAPI Scan_clipboard(LPVOID lParam)
{
  //check if local or not :)
  if (!LOCAL_SCAN)
  {
    h_thread_test[(unsigned int)lParam] = 0;
    check_treeview(htrv_test, H_tests[(unsigned int)lParam], TRV_STATE_UNCHECK);//db_scan
    return 0;
  }

  //db
  sqlite3 *db = (sqlite3 *)db_scan;
  if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"BEGIN TRANSACTION;", NULL, NULL, NULL);

  //lecture du contenu du presse papier et extraction
  if (OpenClipboard(0))
  {
    char description[MAX_LINE_SIZE], format[DEFAULT_TMP_SIZE],
    data[MAX_LINE_SIZE],user[NB_USERNAME_SIZE+1]="";
    unsigned int session_id = current_session_id;
    HGLOBAL hMem;

    //user
    DWORD s=NB_USERNAME_SIZE;
    GetUserName(user,&s);

    int nb_items = CountClipboardFormats();
    if (nb_items > 0)
    {
      unsigned int uFormat = EnumClipboardFormats(0);
      #ifdef CMD_LINE_ONLY_NO_DB
      printf("\"Clipboard\";\"format\";\"code\";\"description\";\"user\";\"session_id\";\"data\";\r\n");
      #endif // CMD_LINE_ONLY_NO_DB
      while (uFormat && start_scan && GetLastError() == ERROR_SUCCESS && --nb_items>0)
      {
        //check if ok
        if (IsClipboardFormatAvailable(uFormat) == FALSE)
        {
          uFormat = EnumClipboardFormats(uFormat);
          continue;
        }

        description[0] = 0;
        data[0]= 0;
        if (GetClipboardFormatName(uFormat, description, MAX_LINE_SIZE) != 0)
        {
          hMem = GetClipboardData(uFormat);
          if (hMem != NULL)
          {
            switch(uFormat)
            {
              case CF_TEXT:
                //format
                strncpy(format,"CF_TEXT",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Text",DEFAULT_TMP_SIZE);
                //datas
                strncpy(data,GlobalLock(hMem),MAX_LINE_SIZE);
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_BITMAP:
                //format
                strncpy(format,"CF_BITMAP",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Bitmap Picture",DEFAULT_TMP_SIZE);
                //do in bitmap to hexa
                SaveBitmapToHexaStr((HBITMAP)hMem , data, MAX_LINE_SIZE);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_METAFILEPICT:
                //format
                strncpy(format,"CF_METAFILEPICT",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Meta-File Picture",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
                GlobalUnlock(hMem);
              break;
              case CF_SYLK:
                //format
                strncpy(format,"CF_SYLK",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Microsoft Symbolic Link (SYLK) data",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"%s",(char*)GlobalLock(hMem));
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_OEMTEXT:
                //format
                strncpy(format,"CF_OEMTEXT",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Text (OEM)",DEFAULT_TMP_SIZE);
                //datas
                strncpy(data,GlobalLock(hMem),MAX_LINE_SIZE);
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_DIB:
                //format
                strncpy(format,"CF_DIB",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"DIB Bitmap Picture",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_DIF:
                //format
                strncpy(format,"CF_DIF",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Software Arts' Data Interchange information",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_TIFF:
                //format
                strncpy(format,"CF_TIFF",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Tagged Image File Format (TIFF) Picture",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_PALETTE:
                //format
                strncpy(format,"CF_PALETTE",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Colour Palette",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_PENDATA:
                //format
                strncpy(format,"CF_PENDATA",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Pen Data",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_UNICODETEXT:
                //format
                strncpy(format,"CF_UNICODETEXT",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Text Unicode",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"%S",GlobalLock(hMem));
                convertStringToSQL(data, MAX_LINE_SIZE);h_thread_test[(unsigned int)lParam] = 0;
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_RIFF:
                //format
                strncpy(format,"CF_RIFF",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"RIFF Audio data",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_WAVE:
                //format
                strncpy(format,"CF_WAVE",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Wave File",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_ENHMETAFILE:
                //format
                strncpy(format,"CF_ENHMETAFILE",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Enhanced Meta-File Picture",DEFAULT_TMP_SIZE);
                //datas
                DWORD dwSize = GetEnhMetaFileBits((HENHMETAFILE)hMem, 0, NULL);
                if (dwSize > 0)
                {
                  LPBYTE buffer = (LPBYTE)malloc(dwSize);
                  if (buffer != NULL)
                  {
                    if (GetEnhMetaFileBits((HENHMETAFILE)hMem, dwSize, buffer)!=0)
                    {
                      DatatoHexa(buffer, dwSize, data, MAX_LINE_SIZE);
                    }
                    free(buffer);
                  }
                }
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case CF_HDROP:
              {
                //format
                strncpy(format,"CF_HDROP",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"File List",DEFAULT_TMP_SIZE);

                HDROP H_DropInfo = (HDROP)hMem;
                char tmp[MAX_PATH];
                DWORD i,nb_path = DragQueryFile(H_DropInfo, 0xFFFFFFFF, tmp, MAX_PATH);
                long int s2 =MAX_LINE_SIZE;
                for (i=0;i<nb_path;i++)
                {
                  //traitement des données ^^
                  DragQueryFile(H_DropInfo, i, tmp, MAX_PATH);

                  //add
                  if (s2>0)
                  {
                    snprintf(data+strlen(data),s,"%s\r\n",tmp);
                    //strncpy(data+strlen(data),tmp,s);
                    s2-=strlen(data);
                  }
                }
                convertStringToSQL(data, MAX_LINE_SIZE);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              }
              break;
              case CF_LOCALE:
                //format
                strncpy(format,"CF_LOCALE",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Text Locale Identifier",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"0x%X",(unsigned int)GlobalLock(hMem));
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 17: //CF_DIBV5
                //format
                strncpy(format,"CF_DIBV5",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), sizeof(BITMAPV5HEADER), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49155:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"OwnerLink",DEFAULT_TMP_SIZE);
                //datas
                strncpy(data,GlobalLock(hMem),MAX_LINE_SIZE);
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49156:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Native Bitmap Picture",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49158:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"FileName",DEFAULT_TMP_SIZE);
                //datas
                strncpy(data,GlobalLock(hMem),MAX_LINE_SIZE);
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49159:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"FileNameW",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"%S",GlobalLock(hMem));
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              case 49298:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                if (description[0]==0)strncpy(description,"Rich Text Format",DEFAULT_TMP_SIZE);
                //datas
                snprintf(data,MAX_LINE_SIZE,"%s",(char*)GlobalLock(hMem));
                convertStringToSQL(data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
              default:
                //format
                strncpy(format,"UNKNOW",DEFAULT_TMP_SIZE);
                //datas
                DatatoHexa(GlobalLock(hMem), GlobalSize(hMem), data, MAX_LINE_SIZE);
                GlobalUnlock(hMem);
                addClipboardtoDB(format, uFormat, description, data, user, session_id, db);
              break;
            }
          }
        }
        uFormat = EnumClipboardFormats(uFormat);
      }
    }
    CloseClipboard();
  }
  if(!SQLITE_FULL_SPEED)sqlite3_exec(db_scan,"END TRANSACTION;", NULL, NULL, NULL);

  check_treeview(htrv_test, H_tests[(unsigned int)lParam], TRV_STATE_UNCHECK);//db_scan
  h_thread_test[(unsigned int)lParam] = 0;
  return 0;
}
Example #6
0
void AuthKeyWindow::PasteFromClipboard()
{
	bool gotClipboardText = false;
	
	// Read key into clipboard
#ifdef TARGET_MSVC	
    bool opened = OpenClipboard(NULL);
    if( opened )
    {
        bool textAvailable = IsClipboardFormatAvailable(CF_TEXT);
        if( textAvailable )
        {
            HANDLE clipTextHandle = GetClipboardData(CF_TEXT);
            if( clipTextHandle )
            {
                char *text = (char *) GlobalLock(clipTextHandle); 
                if(clipTextHandle) 
                { 
                    strncpy( m_key, text, AUTHENTICATION_KEYLEN-1 );
					m_key[AUTHENTICATION_KEYLEN] = '\0';
					gotClipboardText = true;
					
                    GlobalUnlock(text); 
                }
            }
        }
        CloseClipboard();
    }
#elif TARGET_OS_MACOSX
	PasteboardRef clipboard = NULL;
	ItemCount numItems = 0;
	CFDataRef clipboardData = NULL;
	CFStringRef clipboardString;
	
	PasteboardCreate(kPasteboardClipboard, &clipboard);
	if ( clipboard )
	{
		PasteboardGetItemCount(clipboard, &numItems);
		
		// Use the first item, if it exists. Multiple items are only for drag-and-drop, AFAIK
		if ( numItems > 0 )
		{
			PasteboardItemID firstItem;
			PasteboardGetItemIdentifier( clipboard, 1, &firstItem );
			PasteboardCopyItemFlavorData( clipboard, firstItem,
										  CFSTR("public.utf16-plain-text"), &clipboardData);
			if ( clipboardData )
			{
				clipboardString = CFStringCreateWithBytes(NULL, CFDataGetBytePtr(clipboardData),
														  CFDataGetLength(clipboardData),
														  kCFStringEncodingUnicode, false);
				
				// Convert to Latin 1 encoding, and copy as much as will fit
				memset(m_key, 0, sizeof(m_key));
				CFStringGetBytes(clipboardString, CFRangeMake(0, CFStringGetLength(clipboardString)),
								 kCFStringEncodingWindowsLatin1, 0, false,
								 (UInt8 *)m_key, AUTHENTICATION_KEYLEN-1, NULL);
				gotClipboardText = true;
				
				CFRelease(clipboardString);
				CFRelease(clipboardData);
			}
		}
	}
	
	CFRelease( clipboard );
#endif // platform specific

	// Cross-platform code, once we've gotten the clipboard contents into m_key
	//
	if ( gotClipboardText )
	{
		strupr( m_key );
		Authentication_SetKey( m_key );
		Authentication_SaveKey( m_key, App::GetAuthKeyPath() );
	}
}
Example #7
0
size_t Clipboard::Get(LPTSTR aBuf)
// If aBuf is NULL, it returns the length of the text on the clipboard and leaves the
// clipboard open.  Otherwise, it copies the clipboard text into aBuf and closes
// the clipboard (UPDATE: But only if the clipboard is still open from a prior call
// to determine the length -- see later comments for details).  In both cases, the
// length of the clipboard text is returned (or the value CLIPBOARD_FAILURE if error).
// If the clipboard is still open when the next MsgSleep() is called -- presumably
// because the caller never followed up with a second call to this function, perhaps
// due to having insufficient memory -- MsgSleep() will close it so that our
// app doesn't keep the clipboard tied up.  Note: In all current cases, the caller
// will use MsgBox to display an error, which in turn calls MsgSleep(), which will
// immediately close the clipboard.
{
	// Seems best to always have done this even if we return early due to failure:
	if (aBuf)
		// It should be safe to do this even at its peak capacity, because caller
		// would have then given us the last char in the buffer, which is already
		// a zero terminator, so this would have no effect:
		*aBuf = '\0';

	UINT i, file_count = 0;
	BOOL clipboard_contains_text = IsClipboardFormatAvailable(CF_NATIVETEXT);
	BOOL clipboard_contains_files = IsClipboardFormatAvailable(CF_HDROP);
	if (!(clipboard_contains_text || clipboard_contains_files))
		return 0;

	if (!mIsOpen)
	{
		// As a precaution, don't give the caller anything from the clipboard
		// if the clipboard isn't already open from the caller's previous
		// call to determine the size of what's on the clipboard (no other app
		// can alter its size while we have it open).  The is to prevent a
		// buffer overflow from happening in a scenario such as the following:
		// Caller calls us and we return zero size, either because there's no
		// CF_TEXT on the clipboard or there was a problem opening the clipboard.
		// In these two cases, the clipboard isn't open, so by the time the
		// caller calls us again, there's a chance (vanishingly small perhaps)
		// that another app (if our thread were preempted long enough, or the
		// platform is multiprocessor) will have changed the contents of the
		// clipboard to something larger than zero.  Thus, if we copy that
		// into the caller's buffer, the buffer might overflow:
		if (aBuf)
			return 0;
		if (!Open())
		{
			// Since this should be very rare, a shorter message is now used.  Formerly, it was
			// "Could not open clipboard for reading after many timed attempts. Another program is probably holding it open."
			Close(CANT_OPEN_CLIPBOARD_READ);
			return CLIPBOARD_FAILURE;
		}
		if (   !(mClipMemNow = g_clip.GetClipboardDataTimeout(clipboard_contains_text ? CF_NATIVETEXT : CF_HDROP))   )
		{
			// v1.0.47.04: Commented out the following that had been in effect when clipboard_contains_files==false:
			//    Close("GetClipboardData"); // Short error message since so rare.
			//    return CLIPBOARD_FAILURE;
			// This was done because there are situations when GetClipboardData can fail indefinitely.
			// For example, in Firefox, pulling down the Bookmarks menu then right-clicking "Bookmarks Toolbar
			// Folder" then selecting "Copy" puts one or more formats on the clipboard that cause this problem.
			// For details, search the forum for TYMED_NULL.
			//
			// v1.0.42.03: For the fix below, GetClipboardDataTimeout() knows not to try more than once
			// for CF_HDROP.
			// Fix for v1.0.31.02: When clipboard_contains_files==true, tolerate failure, which happens
			// as a normal/expected outcome when there are files on the clipboard but either:
			// 1) zero of them;
			// 2) the CF_HDROP on the clipboard is somehow misformatted.
			// If you select the parent ".." folder in WinRar then use the following hotkey, the script
			// would previously yield a runtime error:
			//#q::
			//Send, ^c
			//ClipWait, 0.5, 1
			//msgbox %Clipboard%
			//Return
			Close();
			if (aBuf)
				*aBuf = '\0';
			return CLIPBOARD_FAILURE; // Return this because otherwise, Contents() returns mClipMemNowLocked, which is NULL.
		}
		// Although GlobalSize(mClipMemNow) can yield zero in some cases -- in which case GlobalLock() should
		// not be attempted -- it probably can't yield zero for CF_HDROP and CF_TEXT because such a thing has
		// never been reported by anyone.  Therefore, GlobalSize() is currently not called.
		if (   !(mClipMemNowLocked = (LPTSTR)GlobalLock(mClipMemNow))   )
		{
			Close(_T("GlobalLock"));  // Short error message since so rare.
			return CLIPBOARD_FAILURE;
		}
		// Otherwise: Update length after every successful new open&lock:
		// Determine the length (size - 1) of the buffer than would be
		// needed to hold what's on the clipboard:
		if (clipboard_contains_text)
		{
			// See below for comments.
			mLength = _tcslen(mClipMemNowLocked);
		}
		else // clipboard_contains_files
		{
			if (file_count = DragQueryFile((HDROP)mClipMemNowLocked, 0xFFFFFFFF, NULL, 0))
			{
				mLength = (file_count - 1) * 2;  // Init; -1 if don't want a newline after last file.
				for (i = 0; i < file_count; ++i)
					mLength += DragQueryFile((HDROP)mClipMemNowLocked, i, NULL, 0);
			}
			else
				mLength = 0;
		}
		if (mLength >= CLIPBOARD_FAILURE) // Can't realistically happen, so just indicate silent failure.
			return CLIPBOARD_FAILURE;
	}
	if (!aBuf)
		return mLength;
		// Above: Just return the length; don't close the clipboard because we expect
		// to be called again soon.  If for some reason we aren't called, MsgSleep()
		// will automatically close the clipboard and clean up things.  It's done this
		// way to avoid the chance that the clipboard contents (and thus its length)
		// will change while we don't have it open, possibly resulting in a buffer
		// overflow.  In addition, this approach performs better because it avoids
		// the overhead of having to close and reopen the clipboard.

	// Otherwise:
	if (clipboard_contains_text) // Fixed for v1.1.16.02: Prefer text over files if both are present.
	{
		// Because the clipboard is being retrieved as text, return this text even if
		// the clipboard also contains files.  Contents() relies on this since it only
		// calls Get() once and does not provide a buffer.  Contents() would be used
		// in "c := Clipboard" or "MsgBox %Clipboard%" because ArgMustBeDereferenced()
		// returns true only if the clipboard contains files but not text.
		_tcscpy(aBuf, mClipMemNowLocked);  // Caller has already ensured that aBuf is large enough.
	}
	else // clipboard_contains_files
	{
		if (file_count = DragQueryFile((HDROP)mClipMemNowLocked, 0xFFFFFFFF, NULL, 0))
			for (i = 0; i < file_count; ++i)
			{
				// Caller has already ensured aBuf is large enough to hold them all:
				aBuf += DragQueryFile((HDROP)mClipMemNowLocked, i, aBuf, 999);
				if (i < file_count - 1) // i.e. don't add newline after the last filename.
				{
					*aBuf++ = '\r';  // These two are the proper newline sequence that the OS prefers.
					*aBuf++ = '\n';
				}
				//else DragQueryFile() has ensured that aBuf is terminated.
			}
		// else aBuf has already been terminated upon entrance to this function.
	}
	// Fix for v1.0.37: Close() is no longer called here because it prevents the clipboard variable
	// from being referred to more than once in a line.  For example:
	// Msgbox %Clipboard%%Clipboard%
	// ToolTip % StrLen(Clipboard) . Clipboard
	// Instead, the clipboard is later closed in other places (search on CLOSE_CLIPBOARD_IF_OPEN
	// to find them).  The alternative to fixing it this way would be to let it reopen the clipboard
	// by means getting rid of the following lines above:
	//if (aBuf)
	//	return 0;
	// However, that has the risks described in the comments above those two lines.
	return mLength;
}
void TextEdit::onKeyDown(const Event &event)
{
   int stringLen = strlen(text);
   setUpdate();
   
    if (event.modifier & SI_SHIFT)
    {
        switch(event.diKeyCode)
        {
             case DIK_HOME:
                blockStart = 0;
                blockEnd = cursorPos;
                cursorPos = 0;
                return;
                
             case DIK_END:
                blockStart = cursorPos;
                blockEnd = stringLen;
                cursorPos = stringLen;
                return;
            
            case DIK_LEFT:
                if ((cursorPos > 0) & (stringLen > 0))
                {
                    //if we already have a selected block
                    if (cursorPos == blockEnd)
                    {
                        cursorPos--;
                        blockEnd--;
                        if (blockEnd == blockStart)
                        {
                            blockStart = 0;
                            blockEnd = 0;
                        }
                    }
                    else {
                        cursorPos--;
                        blockStart = cursorPos;
                        
                        if (blockEnd == 0)
                        {
                            blockEnd = cursorPos + 1;
                        }
                    }
                }
                return;
                
            case DIK_RIGHT:
                if (cursorPos < stringLen)
                {
                    if ((cursorPos == blockStart) && (blockEnd > 0))
                    {
                        cursorPos++;
                        blockStart++;
                        if (blockStart == blockEnd)
                        {
                            blockStart = 0;
                            blockEnd = 0;
                        }
                    }
                    else
                    {
                        if (blockEnd == 0)
                        {
                            blockStart = cursorPos;
                            blockEnd = cursorPos;
                        }
                        cursorPos++;
                        blockEnd++;
                    }
                }
                return;
        }
    }
   else if (event.modifier & SI_CTRL)
   {
      switch(event.diKeyCode)
      {
         case DIK_C:
         case DIK_X:
            if (blockEnd > 0)
            {
                //save the current state
                saveUndoState();
                
                char buf[SimpleText::MAX_STRING_LENGTH + 1], temp;
                
                //copy to the clipboard    
                if (!OpenClipboard(getCanvas()->getHandle()))
                    return;
                LPTSTR  lptstrCopy; 
                HGLOBAL hglbCopy;
                hglbCopy = GlobalAlloc(GMEM_DDESHARE, (blockEnd - blockStart + 1)); 
                if (hglbCopy == NULL) 
                { 
                    CloseClipboard(); 
                    return; 
                } 

                // Lock the handle and copy the text to the buffer. 
                temp = text[blockEnd];
                text[blockEnd] = '\0';
                lptstrCopy = (char*)(GlobalLock(hglbCopy)); 
                strcpy(lptstrCopy, &text[blockStart]); 
                text[blockEnd] = temp;

                GlobalUnlock(hglbCopy);

                // Place the handle on the clipboard. 
                SetClipboardData(CF_TEXT, hglbCopy); 
                
                CloseClipboard();
                
                if (event.diKeyCode == DIK_X)
                {
                    strcpy(buf, &text[blockEnd]);
                    cursorPos = blockStart;
                    strcpy(&text[blockStart], buf);
                }
                
                blockStart = 0;
                blockEnd = 0;
            }
            return;
            
         case DIK_V:
            char buf[SimpleText::MAX_STRING_LENGTH + 1];
            
            //delete anything hilited
            if (blockEnd > 0)
            {
                //save the current state
                saveUndoState();
                
                strcpy(buf, &text[blockEnd]);
                cursorPos = blockStart;
                strcpy(&text[blockStart], buf);
                blockStart = 0;
                blockEnd = 0;
            }
      
            HGLOBAL   hglb; 
            LPTSTR    lptstr; 
            if (!IsClipboardFormatAvailable(CF_TEXT)) 
                return; 
            if (! OpenClipboard(getCanvas()->getHandle()))
                return; 
     
            hglb = GetClipboardData(CF_TEXT); 
            if (hglb != NULL) 
            { 
                lptstr = (char*)GlobalLock(hglb); 
                if (lptstr != NULL) 
                { 
                    int pasteLen = strlen(lptstr);
                    if ((stringLen + pasteLen) > maxStrLen)
                    {
                        pasteLen = maxStrLen - stringLen;
                    }
                                             
                    if (cursorPos == stringLen)
                    {
                        strncpy(&text[cursorPos], lptstr, pasteLen);
                        text[cursorPos + pasteLen] = '\0';
                    }
                    else
                    {
                        strcpy(buf, &text[cursorPos]);
                        strncpy(&text[cursorPos],lptstr, pasteLen);
                        strcpy(&text[cursorPos + pasteLen], buf);
                    }
                    cursorPos += pasteLen;
                    GlobalUnlock(hglb); 
                } 

            } 
            CloseClipboard();
            return; 
        
         case DIK_U:
            if (! dragHit)
            {
                char buf[SimpleText::MAX_STRING_LENGTH + 1];
                int tempBlockStart;
                int tempBlockEnd;
                int tempCursorPos;
                
                //save the current
                strcpy(buf, text);
                tempBlockStart = blockStart;
                tempBlockEnd = blockEnd;
                tempCursorPos = cursorPos;
                
                //restore the prev
                strcpy(text, undoText);
                blockStart = undoBlockStart;
                blockEnd = undoBlockEnd;
                cursorPos = undoCursorPos;
                
                //update the undo
                strcpy(undoText, buf);
                undoBlockStart = tempBlockStart;
                undoBlockEnd = tempBlockEnd;
                undoCursorPos = tempCursorPos;
                
                return;
             }
                
         case DIK_DELETE:
         case DIK_BACK:
            //save the current state
            saveUndoState();
            
            //delete everything in the field
            text[0] = '\0';
            cursorPos = 0;
            blockStart = 0;
            blockEnd = 0;
            return;
      } //switch
   }
   else
   {
      switch(event.diKeyCode)
      {
		 case DIK_LEFT:
            blockStart = 0;
            blockEnd = 0;
            if (cursorPos > 0)
            {
                cursorPos--;
            }
            return;
            
		 case DIK_RIGHT:
            blockStart = 0;
            blockEnd = 0;
            if (cursorPos < stringLen)
            {
                cursorPos++;
            }
            return;
                     
         case DIK_BACK:
            if (blockEnd > 0)
            {
                char buf[SimpleText::MAX_STRING_LENGTH + 1];
                strcpy(buf, &text[blockEnd]);
                cursorPos = blockStart;
                strcpy(&text[blockStart], buf);
                blockStart = 0;
                blockEnd = 0;
            }
            else if (cursorPos > 0)
            {
                char buf[SimpleText::MAX_STRING_LENGTH + 1];
                strcpy(buf, &text[cursorPos]);
                cursorPos--;
                strcpy(&text[cursorPos], buf);
            }
            return;
            
         case DIK_DELETE:
            //save the current state
            saveUndoState();
                
            if (blockEnd > 0)
            {
                char buf[SimpleText::MAX_STRING_LENGTH + 1];
                strcpy(buf, &text[blockEnd]);
                cursorPos = blockStart;
                strcpy(&text[blockStart], buf);
                blockStart = 0;
                blockEnd = 0;
            }
            else if (cursorPos < stringLen)
            {
                char buf[SimpleText::MAX_STRING_LENGTH + 1];
                strcpy(buf, &text[cursorPos + 1]);
                strcpy(&text[cursorPos], buf);
            }
            return;
         
         case DIK_INSERT:
            insertOn = !insertOn;
            return;
         
         case DIK_HOME:
            blockStart = 0;
            blockEnd = 0;
            cursorPos = 0;
            return;
            
         case DIK_END:
            blockStart = 0;
            blockEnd = 0;
            cursorPos = stringLen;
            return;
            
         }
   }
   
   switch (event.diKeyCode)
   {
      case DIK_UP:
      case DIK_DOWN:
      case DIK_TAB:
      case DIK_ESCAPE:
         Parent::onKeyDown(event);
         return;
   }
   
   //if ((! mbNumbersOnly && isprint(event.ascii)) || (mbNumbersOnly && event.ascii >= '0' && mbNumbersOnly && event.ascii <= '9'))
   if (isprint(event.ascii))
   {
      //see if it's a number field
      if (mbNumbersOnly)
      {
         if (event.ascii == '-')
         {
            //a minus sign only exists at the beginning, and only a single minus sign
            if (cursorPos != 0) return;
            if (insertOn && (text[0] == '-')) return;
         }
         else if (event.ascii < '0' || event.ascii > '9')
         {
            return;
         }
      }
      
      //save the current state
      saveUndoState();
                
      //delete anything hilited
      if (blockEnd > 0)
      {
          char buf[SimpleText::MAX_STRING_LENGTH + 1];
          strcpy(buf, &text[blockEnd]);
          cursorPos = blockStart;
          strcpy(&text[blockStart], buf);
          blockStart = 0;
          blockEnd = 0;
      }
      
      if ((insertOn && (stringLen < maxStrLen)) ||
          ((! insertOn) && (cursorPos < maxStrLen)))
      {
         if (cursorPos == stringLen)
         {
            text[cursorPos++] = event.ascii;
            text[cursorPos] = '\0';
         }
         else
         {
            if (insertOn)
            {
                char buf[SimpleText::MAX_STRING_LENGTH + 1];
                strcpy(buf, &text[cursorPos]);
                text[cursorPos] = event.ascii;
                cursorPos++;
                strcpy(&text[cursorPos], buf);
            }
            else
            {
                text[cursorPos++] = event.ascii;
                if (cursorPos > stringLen)
                {
                   text[cursorPos] = '\0';
                }
            }
         }
      }
      return;
   }
}
Example #9
0
void CRichEditExtn::OnContextMenu(CWnd* pWnd, CPoint point)
{
  if (m_vmenu_items.empty()) {
    CRichEditExtn::OnContextMenu(pWnd, point);
    return;
  }

  SetFocus();
  CMenu menu;
  menu.CreatePopupMenu();

  BOOL bReadOnly = GetStyle() & ES_READONLY;
  DWORD flags = CanUndo() && !bReadOnly ? 0 : MF_GRAYED;

  int iPos(0);
  menu.InsertMenu(iPos++, MF_BYPOSITION | flags, EM_UNDO,
                  CString(MAKEINTRESOURCE(IDS_MENUSTRING_UNDO)));

  menu.InsertMenu(iPos++, MF_BYPOSITION | MF_SEPARATOR);

  long lStart, lEnd;
  GetSel(lStart, lEnd);
  flags = lStart == lEnd ? MF_GRAYED : 0;
  menu.InsertMenu(iPos++, MF_BYPOSITION | flags, WM_COPY,
                  CString(MAKEINTRESOURCE(IDS_MENUSTRING_COPY)));

  flags = (flags == MF_GRAYED || bReadOnly) ? MF_GRAYED : 0;
  menu.InsertMenu(iPos++, MF_BYPOSITION | flags, WM_CUT,
                  CString(MAKEINTRESOURCE(IDS_MENUSTRING_CUT)));

  flags = (flags == MF_GRAYED || bReadOnly) ? MF_GRAYED : 0;
  menu.InsertMenu(iPos++, MF_BYPOSITION | flags, WM_CLEAR,
                  CString(MAKEINTRESOURCE(IDS_MENUSTRING_DELETE)));

  flags = IsClipboardFormatAvailable(EDIT_CLIPBOARD_TEXT_FORMAT) &&
                                     !bReadOnly ? 0 : MF_GRAYED;
  menu.InsertMenu(iPos++, MF_BYPOSITION | flags, WM_PASTE,
                  CString(MAKEINTRESOURCE(IDS_MENUSTRING_PASTE)));

  menu.InsertMenu(iPos++, MF_BYPOSITION | MF_SEPARATOR);

  int len = GetWindowTextLength();
  flags = (!len || (lStart == 0 && lEnd == len)) ? MF_GRAYED : 0;

  menu.InsertMenu(iPos++, MF_BYPOSITION | flags, EM_SELECTALL,
                  CString(MAKEINTRESOURCE(IDS_MENUSTRING_SELECTALL)));

  menu.InsertMenu(iPos++, MF_BYPOSITION | MF_SEPARATOR);

  for (size_t i = 0; i < m_vmenu_items.size(); i++) {
      menu.InsertMenu((int)i + iPos, MF_BYPOSITION | m_vmenu_items[i].flags,
                      m_vmenu_items[i].message_number,
                      m_vmenu_items[i].menu_string.c_str());
      if (!m_vmenu_items[i].bEnable)
        menu.EnableMenuItem((int)i + iPos, MF_BYPOSITION | MF_GRAYED);
  }

  if (point.x == -1 || point.y == -1) {
    CRect rc;
    GetClientRect(&rc);
    point = rc.CenterPoint();
    ClientToScreen(&point);
  }

  // For some reason - weird cursor
  m_bContextMenu = true;
  
  // Now show menu
  UINT_PTR nCmd = menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON |
                                      TPM_RETURNCMD | TPM_RIGHTBUTTON, 
                                      point.x, point.y, this);
  // Restore cursor
  m_bContextMenu = false;

  if (nCmd == 0)
    return;

  std::vector<st_context_menu>::iterator iter;
  iter = std::find_if(m_vmenu_items.begin(), m_vmenu_items.end(),
                      equal_cmd(nCmd));
  if (iter != m_vmenu_items.end()) {
    this->GetParent()->SendMessage((UINT)nCmd, iter->wParam, iter->lParam);
    return;
  }

  switch (nCmd) {
    case EM_UNDO:
    case WM_CUT:
    case WM_COPY:
    case WM_CLEAR:
      SendMessage((UINT)nCmd);
      break;
    case WM_PASTE:
      SendMessage(EM_PASTESPECIAL, CF_UNICODETEXT, NULL);
      break;
    case EM_SELECTALL:
      SendMessage(EM_SETSEL, 0, -1);
      break;
    default:
      break;
  }
}
Example #10
0
void Paste( LPCLASSDATA lpcd )
{
	HANDLE		hData;
	LPCTSTR		lpszText;
	BOOL		bDeleted = FALSE;

	/*
	 *	Are we read-only?
	 */
	if ( ISREADONLY )
		return;

	/*
	 *	Valid format on the clipboard?
	 */
	if ( IsClipboardFormatAvailable( CF_TEXT ) == FALSE )
		return;

	/*
	 *	Any marks set?
	 */
	if ( HasMark( lpcd ))
		bDeleted = Delete( lpcd );

	/*
	 *	Hide the caret.
	 */
	DisplayCaret( lpcd, FALSE );

	/*
	 *	Open the clipboard.
	 */
	if ( OpenClipboard( lpcd->hWnd ))
	{
		/*
		 *	Get data handle.
		 */
		if (( hData = GetClipboardData( CF_TEXT )) != NULL )
		{
			/*
			 *	Lock the data.
			 */
			if (( lpszText = GlobalLock( hData )) != NULL )
			{
				/*
				 *	Insert the clipboard contents
				 *	into the text.
				 */
				InsertText( lpcd, lpcd->ptCaretPos.y, lpcd->ptCaretPos.x, lpszText, &lpcd->ptCaretPos, ! bDeleted );

				/*
				 *	Unlock the data handle.
				 */
				GlobalUnlock( hData );
			}
		}
		/*
		 *	Close the clipboard.
		 */
		CloseClipboard();
	}

	/*
	 *	Update column position.
	 */
	lpcd->nLastColumnPos = GetCaretOffset( lpcd, lpcd->ptCaretPos.x );

	/*
	 *	Is the caret inside
	 *	the view?
	 */
	if ( CaretInView( lpcd ) == FALSE )
		/*
		 *	No. Move the view to
		 *	make it visible.
		 */
		MakeCaretVisibleNoRedraw( lpcd );

	/*
	 *	Re-render.
	 */
	InvalidateRect( lpcd->hWnd, NULL, FALSE );

	/*
	 *	Setup scrollers.
	 */
	SetupHScroller( lpcd );
	SetupVScroller( lpcd );

	/*
	 *	We are modified.
	 */
	SetModified( lpcd, TRUE );

	/*
	 *	Show the caret.
	 */
	DisplayCaret( lpcd, TRUE );
}
Example #11
0
LRESULT OnCanPaste( HWND hWnd, WPARAM wParam, LPARAM lParam, LPCLASSDATA lpcd )
{
	return ( BOOL )(( ! ISREADONLY ) && IsClipboardFormatAvailable( CF_TEXT ));
}
void InitializeMenuItems(HMENU popupMenu)
{
    int count = GetMenuItemCount(popupMenu);
    for (int i = 0; i < count; ++i)
    {
        MENUITEMINFO info;
        info.cbSize = sizeof(info);
        info.fMask = MIIM_ID | MIIM_STATE;

        if (!GetMenuItemInfo(popupMenu, i, TRUE, &info))
            break;

        bool check = false;
        bool disable = false;

        switch (info.wID)
        {
        case ID_EDIT_COPY:
            disable = g_text.empty();
            break;

        case ID_EDIT_PASTE:
            disable = !IsClipboardFormatAvailable(CF_TEXT);
            break;

        case ID_EDIT_DECREASETEXTSIZE:
            disable = (g_fontSize == g_minFontSize);
            break;

        case ID_VIEW_SHOWMAGNIFIER:
            check = g_magnifier.visible;
            break;

        case ID_MAGNIFIERTYPE_VECTOR:
            check = (g_magnifier.type == MagnifierInfo::Vector);
            disable = (g_measuringMode != DWRITE_MEASURING_MODE_NATURAL);
            break;

        case ID_MAGNIFIERTYPE_PIXELS:
            check = (g_magnifier.type == MagnifierInfo::Pixel);
            break;

        case ID_MAGNIFIERTYPE_SUBPIXELS:
            check = (g_magnifier.type == MagnifierInfo::Subpixel);
            disable = (g_rendererID == RendererD2D);
            break;

        case ID_MAGNIFIERSCALE_3X:
            check = (g_magnifier.scale == 3);
            break;

        case ID_MAGNIFIERSCALE_6X:
            check = (g_magnifier.scale == 6);
            break;

        case ID_OPTIONS_NATURALMODE:
            check = (g_measuringMode == DWRITE_MEASURING_MODE_NATURAL);
            break;

        case ID_OPTIONS_GDICLASSICMODE:
            check = (g_measuringMode == DWRITE_MEASURING_MODE_GDI_CLASSIC);
            break;

        case ID_OPTIONS_GDINATURALMODE:
            check = (g_measuringMode == DWRITE_MEASURING_MODE_GDI_NATURAL);
            break;

        case ID_OPTIONS_USEDIRECT2D:
            check = (g_rendererID == RendererD2D);
            break;

        case ID_OPTIONS_USEDIRECTWRITE:
            check = (g_rendererID == RendererDWrite);
            break;
        }

        UINT newState = 
            (check ? MFS_CHECKED : 0) | 
            (disable ? MFS_DISABLED : 0);

        if (newState != info.fState)
        {
            info.fMask = MIIM_STATE;
            info.fState = newState;
            SetMenuItemInfo(popupMenu, i, TRUE, &info);
        }
    }
}
Example #13
0
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
     static PTSTR pText ;
     BOOL         bEnable ;
     HGLOBAL      hGlobal ;
     HDC          hdc ;
     PTSTR        pGlobal ;
     PAINTSTRUCT  ps ;
     RECT         rect ;
     
     switch (message)
     {
     case WM_CREATE:
          SendMessage (hwnd, WM_COMMAND, IDM_EDIT_RESET, 0) ;
          return 0 ;

    case WM_INITMENUPOPUP:
          EnableMenuItem ((HMENU) wParam, IDM_EDIT_PASTE,
               IsClipboardFormatAvailable (CF_TCHAR) ? MF_ENABLED : MF_GRAYED) ;

          bEnable = pText ? MF_ENABLED : MF_GRAYED ;

          EnableMenuItem ((HMENU) wParam, IDM_EDIT_CUT,   bEnable) ;
          EnableMenuItem ((HMENU) wParam, IDM_EDIT_COPY,  bEnable) ;
          EnableMenuItem ((HMENU) wParam, IDM_EDIT_CLEAR, bEnable) ;
          break ;
          
     case WM_COMMAND:
          switch (LOWORD (wParam))
          {
          case IDM_EDIT_PASTE:
               OpenClipboard (hwnd) ;

               if (hGlobal = GetClipboardData (CF_TCHAR))
               {
                    pGlobal = GlobalLock (hGlobal) ;

                    if (pText)
                    {
                         free (pText) ;
                         pText = NULL ;
                    }
                    pText = malloc (GlobalSize (hGlobal)) ;
                    lstrcpy (pText, pGlobal) ;
                    InvalidateRect (hwnd, NULL, TRUE) ;
               }
               CloseClipboard () ;
               return 0 ;

          case IDM_EDIT_CUT:
          case IDM_EDIT_COPY:
               if (!pText)
                    return 0 ;

               hGlobal = GlobalAlloc (GHND | GMEM_SHARE, 
                                      (lstrlen (pText) + 1) * sizeof (TCHAR)) ;
               pGlobal = GlobalLock (hGlobal) ;
               lstrcpy (pGlobal, pText) ;
               GlobalUnlock (hGlobal) ;

               OpenClipboard (hwnd) ;
               EmptyClipboard () ;
               SetClipboardData (CF_TCHAR, hGlobal) ;
               CloseClipboard () ;

               if (LOWORD (wParam) == IDM_EDIT_COPY)
                    return 0 ;        
                                             // fall through for IDM_EDIT_CUT
          case IDM_EDIT_CLEAR:
               if (pText)
               {
                    free (pText) ;
                    pText = NULL ;
               }
               InvalidateRect (hwnd, NULL, TRUE) ;
               return 0 ;

          case IDM_EDIT_RESET:
               if (pText)
               {
                    free (pText) ;
                    pText = NULL ;
               }

               pText = malloc ((lstrlen (szDefaultText) + 1) * sizeof (TCHAR)) ;
               lstrcpy (pText, szDefaultText) ;
               InvalidateRect (hwnd, NULL, TRUE) ;
               return 0 ;
          }
          break ;

     case WM_PAINT:
          hdc = BeginPaint (hwnd, &ps) ;

          GetClientRect (hwnd, &rect) ;
          
          if (pText != NULL)
               DrawText (hdc, pText, -1, &rect, DT_EXPANDTABS | DT_WORDBREAK) ;

          EndPaint (hwnd, &ps) ;
          return 0 ;
          
     case WM_DESTROY:
          if (pText)
               free (pText) ;

          PostQuitMessage (0) ;
          return 0 ;
     }
     return DefWindowProc (hwnd, message, wParam, lParam) ;
}
Example #14
0
int
winClipboardFlushXEvents(HWND hwnd,
                         Window iWindow, Display * pDisplay, ClipboardConversionData *data, ClipboardAtoms *atoms)
{
    Atom atomClipboard = atoms->atomClipboard;
    Atom atomLocalProperty = atoms->atomLocalProperty;
    Atom atomUTF8String = atoms->atomUTF8String;
    Atom atomCompoundText = atoms->atomCompoundText;
    Atom atomTargets = atoms->atomTargets;

    /* Process all pending events */
    while (XPending(pDisplay)) {
        XTextProperty xtpText = { 0 };
        XEvent event;
        XSelectionEvent eventSelection;
        unsigned long ulReturnBytesLeft;
        char *pszReturnData = NULL;
        char *pszGlobalData = NULL;
        int iReturn;
        HGLOBAL hGlobal = NULL;
        XICCEncodingStyle xiccesStyle;
        char *pszConvertData = NULL;
        char *pszTextList[2] = { NULL };
        int iCount;
        char **ppszTextList = NULL;
        wchar_t *pwszUnicodeStr = NULL;
        Bool fAbort = FALSE;
        Bool fCloseClipboard = FALSE;
        Bool fSetClipboardData = TRUE;

        /* Get the next event - will not block because one is ready */
        XNextEvent(pDisplay, &event);

        /* Branch on the event type */
        switch (event.type) {
            /*
             * SelectionRequest
             */

        case SelectionRequest:
        {
            char *pszAtomName = NULL;

            winDebug("SelectionRequest - target %ld\n",
                     event.xselectionrequest.target);

            pszAtomName = XGetAtomName(pDisplay,
                                       event.xselectionrequest.target);
            winDebug("SelectionRequest - Target atom name %s\n", pszAtomName);
            XFree(pszAtomName);
            pszAtomName = NULL;
        }

            /* Abort if invalid target type */
            if (event.xselectionrequest.target != XA_STRING
                && event.xselectionrequest.target != atomUTF8String
                && event.xselectionrequest.target != atomCompoundText
                && event.xselectionrequest.target != atomTargets) {
                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }

            /* Handle targets type of request */
            if (event.xselectionrequest.target == atomTargets) {
                Atom atomTargetArr[] = { atomTargets,
                    atomCompoundText,
                    atomUTF8String,
                    XA_STRING
                };

                /* Try to change the property */
                iReturn = XChangeProperty(pDisplay,
                                          event.xselectionrequest.requestor,
                                          event.xselectionrequest.property,
                                          XA_ATOM,
                                          32,
                                          PropModeReplace,
                                          (unsigned char *) atomTargetArr,
                                          ARRAY_SIZE(atomTargetArr));
                if (iReturn == BadAlloc
                    || iReturn == BadAtom
                    || iReturn == BadMatch
                    || iReturn == BadValue || iReturn == BadWindow) {
                    ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                           "XChangeProperty failed: %d\n", iReturn);
                }

                /* Setup selection notify xevent */
                eventSelection.type = SelectionNotify;
                eventSelection.send_event = True;
                eventSelection.display = pDisplay;
                eventSelection.requestor = event.xselectionrequest.requestor;
                eventSelection.selection = event.xselectionrequest.selection;
                eventSelection.target = event.xselectionrequest.target;
                eventSelection.property = event.xselectionrequest.property;
                eventSelection.time = event.xselectionrequest.time;

                /*
                 * Notify the requesting window that
                 * the operation has completed
                 */
                iReturn = XSendEvent(pDisplay,
                                     eventSelection.requestor,
                                     False, 0L, (XEvent *) &eventSelection);
                if (iReturn == BadValue || iReturn == BadWindow) {
                    ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                           "XSendEvent () failed\n");
                }
                break;
            }

            /* Close clipboard if we have it open already */
            if (GetOpenClipboardWindow() == hwnd) {
                CloseClipboard();
            }

            /* Access the clipboard */
            if (!OpenClipboard(hwnd)) {
                ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                       "OpenClipboard () failed: %08x\n", (unsigned int)GetLastError());

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }

            /* Indicate that clipboard was opened */
            fCloseClipboard = TRUE;

            /* Check that clipboard format is available */
            if (data->fUseUnicode && !IsClipboardFormatAvailable(CF_UNICODETEXT)) {
                static int count;       /* Hack to stop acroread spamming the log */
                static HWND lasthwnd;   /* I've not seen any other client get here repeatedly? */

                if (hwnd != lasthwnd)
                    count = 0;
                count++;
                if (count < 6)
                    ErrorF("winClipboardFlushXEvents - CF_UNICODETEXT is not "
                           "available from Win32 clipboard.  Aborting %d.\n",
                           count);
                lasthwnd = hwnd;

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }
            else if (!data->fUseUnicode && !IsClipboardFormatAvailable(CF_TEXT)) {
                ErrorF("winClipboardFlushXEvents - CF_TEXT is not "
                       "available from Win32 clipboard.  Aborting.\n");

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }

            /* Setup the string style */
            if (event.xselectionrequest.target == XA_STRING)
                xiccesStyle = XStringStyle;
#ifdef X_HAVE_UTF8_STRING
            else if (event.xselectionrequest.target == atomUTF8String)
                xiccesStyle = XUTF8StringStyle;
#endif
            else if (event.xselectionrequest.target == atomCompoundText)
                xiccesStyle = XCompoundTextStyle;
            else
                xiccesStyle = XStringStyle;

            /* Get a pointer to the clipboard text, in desired format */
            if (data->fUseUnicode) {
                /* Retrieve clipboard data */
                hGlobal = GetClipboardData(CF_UNICODETEXT);
            }
            else {
                /* Retrieve clipboard data */
                hGlobal = GetClipboardData(CF_TEXT);
            }
            if (!hGlobal) {
                ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                       "GetClipboardData () failed: %08x\n", (unsigned int)GetLastError());

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }
            pszGlobalData = (char *) GlobalLock(hGlobal);

            /* Convert the Unicode string to UTF8 (MBCS) */
            if (data->fUseUnicode) {
                int iConvertDataLen = WideCharToMultiByte(CP_UTF8,
                                                      0,
                                                      (LPCWSTR) pszGlobalData,
                                                      -1, NULL, 0, NULL, NULL);
                /* NOTE: iConvertDataLen includes space for null terminator */
                pszConvertData = malloc(iConvertDataLen);
                WideCharToMultiByte(CP_UTF8,
                                    0,
                                    (LPCWSTR) pszGlobalData,
                                    -1,
                                    pszConvertData,
                                    iConvertDataLen, NULL, NULL);
            }
            else {
                pszConvertData = strdup(pszGlobalData);
            }

            /* Convert DOS string to UNIX string */
            winClipboardDOStoUNIX(pszConvertData, strlen(pszConvertData));

            /* Setup our text list */
            pszTextList[0] = pszConvertData;
            pszTextList[1] = NULL;

            /* Initialize the text property */
            xtpText.value = NULL;
            xtpText.nitems = 0;

            /* Create the text property from the text list */
            if (data->fUseUnicode) {
#ifdef X_HAVE_UTF8_STRING
                iReturn = Xutf8TextListToTextProperty(pDisplay,
                                                      pszTextList,
                                                      1, xiccesStyle, &xtpText);
#endif
            }
            else {
                iReturn = XmbTextListToTextProperty(pDisplay,
                                                    pszTextList,
                                                    1, xiccesStyle, &xtpText);
            }
            if (iReturn == XNoMemory || iReturn == XLocaleNotSupported) {
                ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                       "X*TextListToTextProperty failed: %d\n", iReturn);

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }

            /* Free the converted string */
            free(pszConvertData);
            pszConvertData = NULL;

            /* Copy the clipboard text to the requesting window */
            iReturn = XChangeProperty(pDisplay,
                                      event.xselectionrequest.requestor,
                                      event.xselectionrequest.property,
                                      event.xselectionrequest.target,
                                      8,
                                      PropModeReplace,
                                      xtpText.value, xtpText.nitems);
            if (iReturn == BadAlloc || iReturn == BadAtom
                || iReturn == BadMatch || iReturn == BadValue
                || iReturn == BadWindow) {
                ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                       "XChangeProperty failed: %d\n", iReturn);

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }

            /* Release the clipboard data */
            GlobalUnlock(hGlobal);
            pszGlobalData = NULL;
            fCloseClipboard = FALSE;
            CloseClipboard();

            /* Clean up */
            XFree(xtpText.value);
            xtpText.value = NULL;
            xtpText.nitems = 0;

            /* Setup selection notify event */
            eventSelection.type = SelectionNotify;
            eventSelection.send_event = True;
            eventSelection.display = pDisplay;
            eventSelection.requestor = event.xselectionrequest.requestor;
            eventSelection.selection = event.xselectionrequest.selection;
            eventSelection.target = event.xselectionrequest.target;
            eventSelection.property = event.xselectionrequest.property;
            eventSelection.time = event.xselectionrequest.time;

            /* Notify the requesting window that the operation has completed */
            iReturn = XSendEvent(pDisplay,
                                 eventSelection.requestor,
                                 False, 0L, (XEvent *) &eventSelection);
            if (iReturn == BadValue || iReturn == BadWindow) {
                ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                       "XSendEvent () failed\n");

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }

 winClipboardFlushXEvents_SelectionRequest_Done:
            /* Free allocated resources */
            if (xtpText.value) {
                XFree(xtpText.value);
                xtpText.value = NULL;
                xtpText.nitems = 0;
            }
            free(pszConvertData);
            if (hGlobal && pszGlobalData)
                GlobalUnlock(hGlobal);

            /*
             * Send a SelectionNotify event to the requesting
             * client when we abort.
             */
            if (fAbort) {
                /* Setup selection notify event */
                eventSelection.type = SelectionNotify;
                eventSelection.send_event = True;
                eventSelection.display = pDisplay;
                eventSelection.requestor = event.xselectionrequest.requestor;
                eventSelection.selection = event.xselectionrequest.selection;
                eventSelection.target = event.xselectionrequest.target;
                eventSelection.property = None;
                eventSelection.time = event.xselectionrequest.time;

                /* Notify the requesting window that the operation is complete */
                iReturn = XSendEvent(pDisplay,
                                     eventSelection.requestor,
                                     False, 0L, (XEvent *) &eventSelection);
                if (iReturn == BadValue || iReturn == BadWindow) {
                    /*
                     * Should not be a problem if XSendEvent fails because
                     * the client may simply have exited.
                     */
                    ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                           "XSendEvent () failed for abort event.\n");
                }
            }

            /* Close clipboard if it was opened */
            if (fCloseClipboard) {
                fCloseClipboard = FALSE;
                CloseClipboard();
            }
            break;

            /*
             * SelectionNotify
             */

        case SelectionNotify:
            winDebug("winClipboardFlushXEvents - SelectionNotify\n");
            {
                char *pszAtomName;

                pszAtomName = XGetAtomName(pDisplay,
                                           event.xselection.selection);

                winDebug
                    ("winClipboardFlushXEvents - SelectionNotify - ATOM: %s\n",
                     pszAtomName);
                XFree(pszAtomName);
            }

            /*
              SelectionNotify with property of None indicates either:

              (i) Generated by the X server if no owner for the specified selection exists
                  (perhaps it's disappeared on us mid-transaction), or
              (ii) Sent by the selection owner when the requested selection conversion could
                   not be performed or server errors prevented the conversion data being returned
            */
            if (event.xselection.property == None) {
                    ErrorF("winClipboardFlushXEvents - SelectionNotify - "
                           "Conversion to format %ld refused.\n",
                           event.xselection.target);
                    return WIN_XEVENTS_FAILED;
                }

            if (event.xselection.target == atomTargets) {
              return winClipboardSelectionNotifyTargets(hwnd, iWindow, pDisplay, data, atoms);
            }

            /* Retrieve the selection data and delete the property */
            iReturn = XGetWindowProperty(pDisplay,
                                         iWindow,
                                         atomLocalProperty,
                                         0,
                                         INT_MAX,
                                         True,
                                         AnyPropertyType,
                                         &xtpText.encoding,
                                         &xtpText.format,
                                         &xtpText.nitems,
                                         &ulReturnBytesLeft, &xtpText.value);
            if (iReturn != Success) {
                ErrorF("winClipboardFlushXEvents - SelectionNotify - "
                       "XGetWindowProperty () failed, aborting: %d\n", iReturn);
                goto winClipboardFlushXEvents_SelectionNotify_Done;
            }

            {
                char *pszAtomName = NULL;

                winDebug("SelectionNotify - returned data %lu left %lu\n",
                         xtpText.nitems, ulReturnBytesLeft);
                pszAtomName = XGetAtomName(pDisplay, xtpText.encoding);
                winDebug("Notify atom name %s\n", pszAtomName);
                XFree(pszAtomName);
                pszAtomName = NULL;
            }

            if (data->fUseUnicode) {
#ifdef X_HAVE_UTF8_STRING
                /* Convert the text property to a text list */
                iReturn = Xutf8TextPropertyToTextList(pDisplay,
                                                      &xtpText,
                                                      &ppszTextList, &iCount);
#endif
            }
            else {
                iReturn = XmbTextPropertyToTextList(pDisplay,
                                                    &xtpText,
                                                    &ppszTextList, &iCount);
            }
            if (iReturn == Success || iReturn > 0) {
                /* Conversion succeeded or some unconvertible characters */
                if (ppszTextList != NULL) {
                    int i;
                    int iReturnDataLen = 0;
                    for (i = 0; i < iCount; i++) {
                        iReturnDataLen += strlen(ppszTextList[i]);
                    }
                    pszReturnData = malloc(iReturnDataLen + 1);
                    pszReturnData[0] = '\0';
                    for (i = 0; i < iCount; i++) {
                        strcat(pszReturnData, ppszTextList[i]);
                    }
                }
                else {
                    ErrorF("winClipboardFlushXEvents - SelectionNotify - "
                           "X*TextPropertyToTextList list_return is NULL.\n");
                    pszReturnData = malloc(1);
                    pszReturnData[0] = '\0';
                }
            }
            else {
                ErrorF("winClipboardFlushXEvents - SelectionNotify - "
                       "X*TextPropertyToTextList returned: ");
                switch (iReturn) {
                case XNoMemory:
                    ErrorF("XNoMemory\n");
                    break;
                case XLocaleNotSupported:
                    ErrorF("XLocaleNotSupported\n");
                    break;
                case XConverterNotFound:
                    ErrorF("XConverterNotFound\n");
                    break;
                default:
                    ErrorF("%d\n", iReturn);
                    break;
                }
                pszReturnData = malloc(1);
                pszReturnData[0] = '\0';
            }

            /* Free the data returned from XGetWindowProperty */
            if (ppszTextList)
                XFreeStringList(ppszTextList);
            ppszTextList = NULL;
            XFree(xtpText.value);
            xtpText.value = NULL;
            xtpText.nitems = 0;

            /* Convert the X clipboard string to DOS format */
            winClipboardUNIXtoDOS(&pszReturnData, strlen(pszReturnData));

            if (data->fUseUnicode) {
                /* Find out how much space needed to convert MBCS to Unicode */
                int iUnicodeLen = MultiByteToWideChar(CP_UTF8,
                                                  0,
                                                  pszReturnData, -1, NULL, 0);

                /* NOTE: iUnicodeLen includes space for null terminator */
                pwszUnicodeStr = malloc(sizeof(wchar_t) * iUnicodeLen);
                if (!pwszUnicodeStr) {
                    ErrorF("winClipboardFlushXEvents - SelectionNotify "
                           "malloc failed for pwszUnicodeStr, aborting.\n");

                    /* Abort */
                    fAbort = TRUE;
                    goto winClipboardFlushXEvents_SelectionNotify_Done;
                }

                /* Do the actual conversion */
                MultiByteToWideChar(CP_UTF8,
                                    0,
                                    pszReturnData,
                                    -1, pwszUnicodeStr, iUnicodeLen);

                /* Allocate global memory for the X clipboard data */
                hGlobal = GlobalAlloc(GMEM_MOVEABLE,
                                      sizeof(wchar_t) * iUnicodeLen);
            }
            else {
                int iConvertDataLen = 0;
                pszConvertData = strdup(pszReturnData);
                iConvertDataLen = strlen(pszConvertData) + 1;

                /* Allocate global memory for the X clipboard data */
                hGlobal = GlobalAlloc(GMEM_MOVEABLE, iConvertDataLen);
            }

            free(pszReturnData);

            /* Check that global memory was allocated */
            if (!hGlobal) {
                ErrorF("winClipboardFlushXEvents - SelectionNotify "
                       "GlobalAlloc failed, aborting: %08x\n", (unsigned int)GetLastError());

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionNotify_Done;
            }

            /* Obtain a pointer to the global memory */
            pszGlobalData = GlobalLock(hGlobal);
            if (pszGlobalData == NULL) {
                ErrorF("winClipboardFlushXEvents - Could not lock global "
                       "memory for clipboard transfer\n");

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionNotify_Done;
            }

            /* Copy the returned string into the global memory */
            if (data->fUseUnicode) {
                wcscpy((wchar_t *)pszGlobalData, pwszUnicodeStr);
                free(pwszUnicodeStr);
                pwszUnicodeStr = NULL;
            }
            else {
                strcpy(pszGlobalData, pszConvertData);
                free(pszConvertData);
                pszConvertData = NULL;
            }

            /* Release the pointer to the global memory */
            GlobalUnlock(hGlobal);
            pszGlobalData = NULL;

            /* Push the selection data to the Windows clipboard */
            if (data->fUseUnicode)
                SetClipboardData(CF_UNICODETEXT, hGlobal);
            else
                SetClipboardData(CF_TEXT, hGlobal);

            /* Flag that SetClipboardData has been called */
            fSetClipboardData = FALSE;

            /*
             * NOTE: Do not try to free pszGlobalData, it is owned by
             * Windows after the call to SetClipboardData ().
             */

 winClipboardFlushXEvents_SelectionNotify_Done:
            /* Free allocated resources */
            if (ppszTextList)
                XFreeStringList(ppszTextList);
            if (xtpText.value) {
                XFree(xtpText.value);
                xtpText.value = NULL;
                xtpText.nitems = 0;
            }
            free(pszConvertData);
            free(pwszUnicodeStr);
            if (hGlobal && pszGlobalData)
                GlobalUnlock(hGlobal);
            if (fSetClipboardData) {
                SetClipboardData(CF_UNICODETEXT, NULL);
                SetClipboardData(CF_TEXT, NULL);
            }
            return WIN_XEVENTS_NOTIFY_DATA;

        case SelectionClear:
            winDebug("SelectionClear - doing nothing\n");
            break;

        case PropertyNotify:
            break;

        case MappingNotify:
            break;

        default:
            if (event.type == XFixesSetSelectionOwnerNotify + xfixes_event_base) {
                XFixesSelectionNotifyEvent *e =
                    (XFixesSelectionNotifyEvent *) & event;

                winDebug("winClipboardFlushXEvents - XFixesSetSelectionOwnerNotify\n");

                /* Save selection owners for monitored selections, ignore other selections */
                if ((e->selection == XA_PRIMARY) && fPrimarySelection) {
                    MonitorSelection(e, CLIP_OWN_PRIMARY);
                }
                else if (e->selection == atomClipboard) {
                    MonitorSelection(e, CLIP_OWN_CLIPBOARD);
                }
                else
                    break;

                /* Selection is being disowned */
                if (e->owner == None) {
                    winDebug
                        ("winClipboardFlushXEvents - No window, returning.\n");
                    break;
                }

                /*
                   XXX: there are all kinds of wacky edge cases we might need here:
                   - we own windows clipboard, but neither PRIMARY nor CLIPBOARD have an owner, so we should disown it?
                   - root window is taking ownership?
                 */

                /* If we are the owner of the most recently owned selection, don't go all recursive :) */
                if ((lastOwnedSelectionIndex != CLIP_OWN_NONE) &&
                    (s_iOwners[lastOwnedSelectionIndex] == iWindow)) {
                    winDebug("winClipboardFlushXEvents - Ownership changed to us, aborting.\n");
                    break;
                }

                /* Close clipboard if we have it open already (possible? correct??) */
                if (GetOpenClipboardWindow() == hwnd) {
                    CloseClipboard();
                }

                /* Access the Windows clipboard */
                if (!OpenClipboard(hwnd)) {
                    ErrorF("winClipboardFlushXEvents - OpenClipboard () failed: %08x\n",
                           (int) GetLastError());
                    break;
                }

                /* Take ownership of the Windows clipboard */
                if (!EmptyClipboard()) {
                    ErrorF("winClipboardFlushXEvents - EmptyClipboard () failed: %08x\n",
                           (int) GetLastError());
                    break;
                }

                /* Advertise regular text and unicode */
                SetClipboardData(CF_UNICODETEXT, NULL);
                SetClipboardData(CF_TEXT, NULL);

                /* Release the clipboard */
                if (!CloseClipboard()) {
                    ErrorF("winClipboardFlushXEvents - CloseClipboard () failed: %08x\n",
                           (int) GetLastError());
                    break;
                }
            }
            /* XFixesSelectionWindowDestroyNotifyMask */
            /* XFixesSelectionClientCloseNotifyMask */
            else {
                ErrorF("winClipboardFlushXEvents - unexpected event type %d\n",
                       event.type);
            }
            break;
        }
    }

    return WIN_XEVENTS_SUCCESS;
}
Example #15
0
int
clip_ISCLIPBOARDFORMATAVAILABLE(ClipMachine * mp)
{
	_clip_retl(mp, IsClipboardFormatAvailable(_clip_parni(mp,1)));
	return 0;
}
Example #16
0
void
get_scrap(int type, int *dstlen, char **dst)
{
    scrap_type format;

    *dstlen = 0;
    format = convert_format(type);

#if defined(WZ_WS_X11)
    /* * */
    {
        Window owner;
        Atom selection;
        Atom seln_type;
        int seln_format;
        unsigned long nbytes;
        unsigned long overflow;
        unsigned char * src;

        Lock_Display();
        owner = XGetSelectionOwner(SDL_Display, XA_PRIMARY);
        Unlock_Display();
        if ( (owner == None) || (owner == SDL_Window) )
        {
            owner = DefaultRootWindow(SDL_Display);
            selection = XA_CUT_BUFFER0;
        }
        else
        {
            int selection_response = 0;
            SDL_Event event;

            owner = SDL_Window;
            Lock_Display();
            selection = XInternAtom(SDL_Display, "SDL_SELECTION", False);
            XConvertSelection(SDL_Display, XA_PRIMARY, format,
                              selection, owner, CurrentTime);
            Unlock_Display();
            while ( ! selection_response )
            {
                SDL_WaitEvent(&event);
                if ( event.type == SDL_SYSWMEVENT )
                {
                    XEvent xevent = event.syswm.msg->event.xevent;

                    if ( (xevent.type == SelectionNotify) &&
                            (xevent.xselection.requestor == owner) )
                        selection_response = 1;
                }
            }
        }
        Lock_Display();
        if ( XGetWindowProperty(SDL_Display, owner, selection, 0, INT_MAX/4,
                                False, format, &seln_type, &seln_format,
                                &nbytes, &overflow, &src) == Success )
        {
            if ( seln_type == format )
            {
                *dstlen = convert_scrap(type, NULL, (char*)src, nbytes);
                *dst = (char *)realloc(*dst, *dstlen);
                if ( *dst == NULL )
                    *dstlen = 0;
                else
                    convert_scrap(type, *dst, (char*)src, nbytes);
            }
            XFree(src);
        }
        Unlock_Display();
    }

#elif defined(WZ_WS_WIN)
    /* * */
    if ( IsClipboardFormatAvailable(format) && OpenClipboard(SDL_Window) )
    {
        HANDLE hMem;
        char *src;

        hMem = GetClipboardData(format);
        if ( hMem != NULL )
        {
            src = (char *)GlobalLock(hMem);
            *dstlen = convert_scrap(type, NULL, src, 0);
            *dst = (char *)realloc(*dst, *dstlen);
            if ( *dst == NULL )
                *dstlen = 0;
            else
                convert_scrap(type, *dst, src, 0);
            GlobalUnlock(hMem);
        }
        CloseClipboard();
    }
#elif defined(WZ_WS_QNX)
    /* * */
#if (_NTO_VERSION < 620) /* before 6.2.0 releases */
    {
        void* clhandle;
        PhClipHeader* clheader;
        int* cldata;

        clhandle=PhClipboardPasteStart(InputGroup);
        if (clhandle!=NULL)
        {
            clheader=PhClipboardPasteType(clhandle, Ph_CLIPBOARD_TYPE_TEXT);
            if (clheader!=NULL)
            {
                cldata=clheader->data;
                if ((clheader->length>4) && (*cldata==type))
                {
                    *dstlen = convert_scrap(type, NULL, (char*)clheader->data+4, clheader->length-4);
                    *dst = (char *)realloc(*dst, *dstlen);
                    if (*dst == NULL)
                    {
                        *dstlen = 0;
                    }
                    else
                    {
                        convert_scrap(type, *dst, (char*)clheader->data+4, clheader->length-4);
                    }
                }
            }
            PhClipboardPasteFinish(clhandle);
        }
    }
#else /* 6.2.0 and 6.2.1 and future releases */
    {
        void* clhandle;
        PhClipboardHdr* clheader;
        int* cldata;

        clheader=PhClipboardRead(InputGroup, Ph_CLIPBOARD_TYPE_TEXT);
        if (clheader!=NULL)
        {
            cldata=clheader->data;
            if ((clheader->length>4) && (*cldata==type))
            {
                *dstlen = convert_scrap(type, NULL, (char*)clheader->data+4, clheader->length-4);
                *dst = (char *)realloc(*dst, *dstlen);
                if (*dst == NULL)
                {
                    *dstlen = 0;
                }
                else
                {
                    convert_scrap(type, *dst, (char*)clheader->data+4, clheader->length-4);
                }
            }
        }
    }
#endif
#endif /* scrap type */
}
int
winClipboardFlushXEvents (HWND hwnd,
			  int iWindow,
			  Display *pDisplay,
			  Bool fUseUnicode)
{
  static Atom atomLocalProperty;
  static Atom atomCompoundText;
  static Atom atomUTF8String;
  static Atom atomTargets;
  static int generation;

  if (generation != serverGeneration)
    {
      generation = serverGeneration;
      atomLocalProperty = XInternAtom (pDisplay, WIN_LOCAL_PROPERTY, False);
      atomUTF8String = XInternAtom (pDisplay, "UTF8_STRING", False);
      atomCompoundText = XInternAtom (pDisplay, "COMPOUND_TEXT", False);
      atomTargets = XInternAtom (pDisplay, "TARGETS", False);
    }

  /* Process all pending events */
  while (XPending (pDisplay))
    {
      XTextProperty		xtpText = {0};
      XEvent			event;
      XSelectionEvent		eventSelection;
      unsigned long		ulReturnBytesLeft;
      char			*pszReturnData = NULL;
      char			*pszGlobalData = NULL;
      int			iReturn;
      HGLOBAL			hGlobal = NULL;
      XICCEncodingStyle		xiccesStyle;
      int			iConvertDataLen = 0;
      char			*pszConvertData = NULL;
      char			*pszTextList[2] = {NULL};
      int			iCount;
      char			**ppszTextList = NULL;
      wchar_t			*pwszUnicodeStr = NULL;
      int			iUnicodeLen = 0;
      int			iReturnDataLen = 0;
      int			i;
      Bool			fAbort = FALSE;
      Bool			fCloseClipboard = FALSE;
      Bool			fSetClipboardData = TRUE;

      /* Get the next event - will not block because one is ready */
      XNextEvent (pDisplay, &event);

      /* Branch on the event type */
      switch (event.type)
	{
	  /*
	   * SelectionRequest
	   */

	case SelectionRequest:
	  {
	    char			*pszAtomName = NULL;
	    winDebug("SelectionRequest - target %d\n",
                     event.xselectionrequest.target);

	    pszAtomName = XGetAtomName (pDisplay,
					event.xselectionrequest.target);
	    winDebug("SelectionRequest - Target atom name %s\n", pszAtomName);
	    XFree (pszAtomName);
	    pszAtomName = NULL;
	  }

	  /* Abort if invalid target type */
	  if (event.xselectionrequest.target != XA_STRING
	      && event.xselectionrequest.target != atomUTF8String
	      && event.xselectionrequest.target != atomCompoundText
	      && event.xselectionrequest.target != atomTargets)
	    {
	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }

	  /* Handle targets type of request */
	  if (event.xselectionrequest.target == atomTargets)
	    {
	      Atom atomTargetArr[] = {atomTargets,
				      atomCompoundText,
				      atomUTF8String,
				      XA_STRING};

	      /* Try to change the property */
	      iReturn = XChangeProperty (pDisplay,
					 event.xselectionrequest.requestor,
					 event.xselectionrequest.property,
					 XA_ATOM,
					 32,
					 PropModeReplace,
					 (unsigned char *) atomTargetArr,
					 (sizeof (atomTargetArr)
					  / sizeof (atomTargetArr[0])));
	      if (iReturn == BadAlloc
		  || iReturn == BadAtom
		  || iReturn == BadMatch
		  || iReturn == BadValue
		  || iReturn == BadWindow)
		{
		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
			  "XChangeProperty failed: %d\n",
			  iReturn);
		}

	      /* Setup selection notify xevent */
	      eventSelection.type	= SelectionNotify;
	      eventSelection.send_event	= True;
	      eventSelection.display	= pDisplay;
	      eventSelection.requestor	= event.xselectionrequest.requestor;
	      eventSelection.selection	= event.xselectionrequest.selection;
	      eventSelection.target	= event.xselectionrequest.target;
	      eventSelection.property	= event.xselectionrequest.property;
	      eventSelection.time	= event.xselectionrequest.time;

	      /*
	       * Notify the requesting window that
	       * the operation has completed
	       */
	      iReturn = XSendEvent (pDisplay,
				    eventSelection.requestor,
				    False,
				    0L,
				    (XEvent *) &eventSelection);
	      if (iReturn == BadValue || iReturn == BadWindow)
		{
		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
			  "XSendEvent () failed\n");
		}
	      break;
	    }

	  /* Check that clipboard format is available */
	  if (fUseUnicode
	      && !IsClipboardFormatAvailable (CF_UNICODETEXT))
	    {
	      static int count; /* Hack to stop acroread spamming the log */
	      static HWND lasthwnd; /* I've not seen any other client get here repeatedly? */
	      if (hwnd != lasthwnd) count = 0;
	      count++;
	      if (count < 6) ErrorF ("winClipboardFlushXEvents - CF_UNICODETEXT is not "
		      "available from Win32 clipboard.  Aborting %d.\n", count);
	      lasthwnd = hwnd;

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }
	  else if (!fUseUnicode
		   && !IsClipboardFormatAvailable (CF_TEXT))
	    {
	      ErrorF ("winClipboardFlushXEvents - CF_TEXT is not "
		      "available from Win32 clipboard.  Aborting.\n");

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }

	  /* Close clipboard if we have it open already */
	  if (GetOpenClipboardWindow () == hwnd)
	    {
	      CloseClipboard ();
	    }

	  /* Access the clipboard */
	  if (!OpenClipboard (hwnd))
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
		      "OpenClipboard () failed: %08lx\n",
		      GetLastError ());

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }
	  
	  /* Indicate that clipboard was opened */
	  fCloseClipboard = TRUE;

	  /* Setup the string style */
	  if (event.xselectionrequest.target == XA_STRING)
	    xiccesStyle = XStringStyle;
#ifdef X_HAVE_UTF8_STRING
	  else if (event.xselectionrequest.target == atomUTF8String)
	    xiccesStyle = XUTF8StringStyle;
#endif
	  else if (event.xselectionrequest.target == atomCompoundText)
	    xiccesStyle = XCompoundTextStyle;
	  else
	    xiccesStyle = XStringStyle;

	  /*
	   * FIXME: Can't pass CF_UNICODETEXT on Windows 95/98/Me
	   */
	  
	  /* Get a pointer to the clipboard text, in desired format */
	  if (fUseUnicode)
	    {
	      /* Retrieve clipboard data */
	      hGlobal = GetClipboardData (CF_UNICODETEXT);
	    }
	  else
	    {
	      /* Retrieve clipboard data */
	      hGlobal = GetClipboardData (CF_TEXT);
	    }
	  if (!hGlobal)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
		      "GetClipboardData () failed: %08lx\n",
		      GetLastError ());

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }
	  pszGlobalData = (char *) GlobalLock (hGlobal);

	  /* Convert the Unicode string to UTF8 (MBCS) */
	  if (fUseUnicode)
	    {
	      iConvertDataLen = WideCharToMultiByte (CP_UTF8,
						     0,
						     (LPCWSTR)pszGlobalData,
						     -1,
						     NULL,
						     0,
						     NULL,
						     NULL);
	      /* NOTE: iConvertDataLen includes space for null terminator */
	      pszConvertData = (char *) malloc (iConvertDataLen);
	      WideCharToMultiByte (CP_UTF8,
				   0,
				   (LPCWSTR)pszGlobalData,
				   -1,
				   pszConvertData,
				   iConvertDataLen,
				   NULL,
				   NULL);
	    }
	  else
	    {
	      pszConvertData = strdup (pszGlobalData);
	      iConvertDataLen = strlen (pszConvertData) + 1;
	    }

	  /* Convert DOS string to UNIX string */
	  winClipboardDOStoUNIX (pszConvertData, strlen (pszConvertData));

	  /* Setup our text list */
	  pszTextList[0] = pszConvertData;
	  pszTextList[1] = NULL;

	  /* Initialize the text property */
	  xtpText.value = NULL;
	  xtpText.nitems = 0;

	  /* Create the text property from the text list */
	  if (fUseUnicode)
	    {
#ifdef X_HAVE_UTF8_STRING
	      iReturn = Xutf8TextListToTextProperty (pDisplay,
						     pszTextList,
						     1,
						     xiccesStyle,
						     &xtpText);
#endif
	    }
	  else
	    {
	      iReturn = XmbTextListToTextProperty (pDisplay,
						   pszTextList,
						   1,
						   xiccesStyle,
						   &xtpText);
	    }
	  if (iReturn == XNoMemory || iReturn == XLocaleNotSupported)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
		      "X*TextListToTextProperty failed: %d\n",
		      iReturn);

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }
	  
	  /* Free the converted string */
	  free (pszConvertData);
	  pszConvertData = NULL;

	  /* Copy the clipboard text to the requesting window */
	  iReturn = XChangeProperty (pDisplay,
				     event.xselectionrequest.requestor,
				     event.xselectionrequest.property,
				     event.xselectionrequest.target,
				     8,
				     PropModeReplace,
				     xtpText.value,
				     xtpText.nitems);
	  if (iReturn == BadAlloc || iReturn == BadAtom
	      || iReturn == BadMatch || iReturn == BadValue
	      || iReturn == BadWindow)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
		      "XChangeProperty failed: %d\n",
		      iReturn);

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }

	  /* Release the clipboard data */
	  GlobalUnlock (hGlobal);
	  pszGlobalData = NULL;
	  fCloseClipboard = FALSE;
	  CloseClipboard ();

	  /* Clean up */
	  XFree (xtpText.value);
	  xtpText.value = NULL;
	  xtpText.nitems = 0;

	  /* Setup selection notify event */
	  eventSelection.type = SelectionNotify;
	  eventSelection.send_event = True;
	  eventSelection.display = pDisplay;
	  eventSelection.requestor = event.xselectionrequest.requestor;
	  eventSelection.selection = event.xselectionrequest.selection;
	  eventSelection.target = event.xselectionrequest.target;
	  eventSelection.property = event.xselectionrequest.property;
	  eventSelection.time = event.xselectionrequest.time;

	  /* Notify the requesting window that the operation has completed */
	  iReturn = XSendEvent (pDisplay,
				eventSelection.requestor,
				False,
				0L,
				(XEvent *) &eventSelection);
	  if (iReturn == BadValue || iReturn == BadWindow)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
		      "XSendEvent () failed\n");

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionRequest_Done;
	    }

	winClipboardFlushXEvents_SelectionRequest_Done:
	  /* Free allocated resources */
	  if (xtpText.value)
	  {
	    XFree (xtpText.value);
	    xtpText.value = NULL;
	    xtpText.nitems = 0;
	  }
	  free(pszConvertData);
	  if (hGlobal && pszGlobalData)
	    GlobalUnlock (hGlobal);
	  
	  /*
	   * Send a SelectionNotify event to the requesting
	   * client when we abort.
	   */
	  if (fAbort)
	    {
	      /* Setup selection notify event */
	      eventSelection.type = SelectionNotify;
	      eventSelection.send_event = True;
	      eventSelection.display = pDisplay;
	      eventSelection.requestor = event.xselectionrequest.requestor;
	      eventSelection.selection = event.xselectionrequest.selection;
	      eventSelection.target = event.xselectionrequest.target;
	      eventSelection.property = None;
	      eventSelection.time = event.xselectionrequest.time;

	      /* Notify the requesting window that the operation is complete */
	      iReturn = XSendEvent (pDisplay,
				    eventSelection.requestor,
				    False,
				    0L,
				    (XEvent *) &eventSelection);
	      if (iReturn == BadValue || iReturn == BadWindow)
		{
		  /*
		   * Should not be a problem if XSendEvent fails because
		   * the client may simply have exited.
		   */
		  ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
			  "XSendEvent () failed for abort event.\n");
		}
	    }

	  /* Close clipboard if it was opened */
	  if (fCloseClipboard)
	  {
	    fCloseClipboard = FALSE;
	    CloseClipboard ();
	  }
	  break;


	  /*
	   * SelectionNotify
	   */ 

	case SelectionNotify:

	  winDebug ("winClipboardFlushXEvents - SelectionNotify\n");
	  {
	    char		*pszAtomName;
	    pszAtomName = XGetAtomName (pDisplay,
					event.xselection.selection);

	    winDebug("winClipboardFlushXEvents - SelectionNotify - ATOM: %s\n",
                     pszAtomName);
	    XFree (pszAtomName);
	  }

	  /*
	   * Request conversion of UTF8 and CompoundText targets.
	   */
	  if (event.xselection.property == None)
	    {
	      if (event.xselection.target == XA_STRING)
		{
		  winDebug ("winClipboardFlushXEvents - SelectionNotify - "
                            "XA_STRING\n");

		  return WIN_XEVENTS_CONVERT;
		}
	      else if (event.xselection.target == atomUTF8String)
		{
		  winDebug("winClipboardFlushXEvents - SelectionNotify - "
                           "Requesting conversion of UTF8 target.\n");

		  XConvertSelection (pDisplay,
				     event.xselection.selection,
				     XA_STRING,
				     atomLocalProperty,
				     iWindow,
				     CurrentTime);

		  /* Process the ConvertSelection event */
		  XFlush (pDisplay);
		  return WIN_XEVENTS_CONVERT;
		}
#ifdef X_HAVE_UTF8_STRING
	      else if (event.xselection.target == atomCompoundText)
		{
		  winDebug("winClipboardFlushXEvents - SelectionNotify - "
                           "Requesting conversion of CompoundText target.\n");

		  XConvertSelection (pDisplay,
				     event.xselection.selection,
				     atomUTF8String,
				     atomLocalProperty,
				     iWindow,
				     CurrentTime);

		  /* Process the ConvertSelection event */
		  XFlush (pDisplay);
		  return WIN_XEVENTS_CONVERT;
		}
#endif
	      else
		{
		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
			  "Unknown format.  Cannot request conversion, "
			  "aborting.\n");
		  break;
		}
	    }

	  /* Retrieve the size of the stored data */
	  iReturn = XGetWindowProperty (pDisplay,
					iWindow,
					atomLocalProperty,
					0,
					0, /* Don't get data, just size */
					False,
					AnyPropertyType,
					&xtpText.encoding,
					&xtpText.format,
					&xtpText.nitems,
					&ulReturnBytesLeft,
					&xtpText.value);
	  if (iReturn != Success)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
		      "XGetWindowProperty () failed, aborting: %d\n",
		      iReturn);
	      break;
	    }

	  winDebug("SelectionNotify - returned data %d left %d\n",
                   xtpText.nitems, ulReturnBytesLeft);

	  /* Request the selection data */
	  iReturn = XGetWindowProperty (pDisplay,
					iWindow,
					atomLocalProperty,
					0,
					ulReturnBytesLeft,
					False,
					AnyPropertyType,
					&xtpText.encoding,
					&xtpText.format,
					&xtpText.nitems,
					&ulReturnBytesLeft,
					&xtpText.value);
	  if (iReturn != Success)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
		      "XGetWindowProperty () failed, aborting: %d\n",
		      iReturn);
	      break;
	    }

	    {
	      char		*pszAtomName = NULL;

	      winDebug("SelectionNotify - returned data %d left %d\n",
                       xtpText.nitems, ulReturnBytesLeft);
	      pszAtomName = XGetAtomName(pDisplay, xtpText.encoding);
	      winDebug("Notify atom name %s\n", pszAtomName);
	      XFree (pszAtomName);
	      pszAtomName = NULL;
	    }

	  if (fUseUnicode)
	    {
#ifdef X_HAVE_UTF8_STRING
	      /* Convert the text property to a text list */
	      iReturn = Xutf8TextPropertyToTextList (pDisplay,
						     &xtpText,
						     &ppszTextList,
						     &iCount);
#endif
	    }
	  else
	    {
	      iReturn = XmbTextPropertyToTextList (pDisplay,
						   &xtpText,
						   &ppszTextList,
						   &iCount);
	    }
	  if (iReturn == Success || iReturn > 0)
	    {
	      /* Conversion succeeded or some unconvertible characters */
	      if (ppszTextList != NULL)
		{
		  iReturnDataLen = 0;
		  for (i = 0; i < iCount; i++)
		    {
		      iReturnDataLen += strlen(ppszTextList[i]);
		    }
		  pszReturnData = malloc (iReturnDataLen + 1);
		  pszReturnData[0] = '\0';
		  for (i = 0; i < iCount; i++)
		    {
		      strcat (pszReturnData, ppszTextList[i]);
		    }
		}
	      else
		{
		  ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
			  "X*TextPropertyToTextList list_return is NULL.\n");
		  pszReturnData = malloc (1);
		  pszReturnData[0] = '\0';
		}
	    }
	  else
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
		      "X*TextPropertyToTextList returned: ");
	      switch (iReturn)
		{
		case XNoMemory:
		  ErrorF ("XNoMemory\n");
		  break;
		case XConverterNotFound:
		  ErrorF ("XConverterNotFound\n");
		  break;
		default:
		  ErrorF ("%d", iReturn);
		  break;
		}
	      pszReturnData = malloc (1);
	      pszReturnData[0] = '\0';
	    }

	  /* Free the data returned from XGetWindowProperty */
	  if (ppszTextList)
	    XFreeStringList (ppszTextList);
	  ppszTextList = NULL;
	  XFree (xtpText.value);
	  xtpText.value = NULL;
	  xtpText.nitems = 0;

	  /* Convert the X clipboard string to DOS format */
	  winClipboardUNIXtoDOS (&pszReturnData, strlen (pszReturnData));

	  if (fUseUnicode)
	    {
	      /* Find out how much space needed to convert MBCS to Unicode */
	      iUnicodeLen = MultiByteToWideChar (CP_UTF8,
						 0,
						 pszReturnData,
						 -1,
						 NULL,
						 0);

	      /* Allocate memory for the Unicode string */
	      pwszUnicodeStr
		= (wchar_t*) malloc (sizeof (wchar_t) * (iUnicodeLen + 1));
	      if (!pwszUnicodeStr)
		{
		  ErrorF ("winClipboardFlushXEvents - SelectionNotify "
			  "malloc failed for pwszUnicodeStr, aborting.\n");

		  /* Abort */
		  fAbort = TRUE;
		  goto winClipboardFlushXEvents_SelectionNotify_Done;
		}

	      /* Do the actual conversion */
	      MultiByteToWideChar (CP_UTF8,
				   0,
				   pszReturnData,
				   -1,
				   pwszUnicodeStr,
				   iUnicodeLen);
	      
	      /* Allocate global memory for the X clipboard data */
	      hGlobal = GlobalAlloc (GMEM_MOVEABLE,
				     sizeof (wchar_t) * (iUnicodeLen + 1));
	    }
	  else
	    {
	      pszConvertData = strdup (pszReturnData);
	      iConvertDataLen = strlen (pszConvertData) + 1;

	      /* Allocate global memory for the X clipboard data */
	      hGlobal = GlobalAlloc (GMEM_MOVEABLE, iConvertDataLen);
	    }

	  free (pszReturnData);

	  /* Check that global memory was allocated */
	  if (!hGlobal)
	    {
	      ErrorF ("winClipboardFlushXEvents - SelectionNotify "
		      "GlobalAlloc failed, aborting: %ld\n",
		      GetLastError ());

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionNotify_Done;
	    }

	  /* Obtain a pointer to the global memory */
	  pszGlobalData = GlobalLock (hGlobal);
	  if (pszGlobalData == NULL)
	    {
	      ErrorF ("winClipboardFlushXEvents - Could not lock global "
		      "memory for clipboard transfer\n");

	      /* Abort */
	      fAbort = TRUE;
	      goto winClipboardFlushXEvents_SelectionNotify_Done;
	    }

	  /* Copy the returned string into the global memory */
	  if (fUseUnicode)
	    {
	      memcpy (pszGlobalData,
		      pwszUnicodeStr,
		      sizeof (wchar_t) * (iUnicodeLen + 1));
	      free (pwszUnicodeStr);
	      pwszUnicodeStr = NULL;
	    }
	  else
	    {
	      strcpy (pszGlobalData, pszConvertData);
	      free (pszConvertData);
	      pszConvertData = NULL;
	    }

	  /* Release the pointer to the global memory */
	  GlobalUnlock (hGlobal);
	  pszGlobalData = NULL;

	  /* Push the selection data to the Windows clipboard */
	  if (fUseUnicode)
	    SetClipboardData (CF_UNICODETEXT, hGlobal);
	  else
	    SetClipboardData (CF_TEXT, hGlobal);

	  /* Flag that SetClipboardData has been called */
	  fSetClipboardData = FALSE;

	  /*
	   * NOTE: Do not try to free pszGlobalData, it is owned by
	   * Windows after the call to SetClipboardData ().
	   */

	winClipboardFlushXEvents_SelectionNotify_Done:
	  /* Free allocated resources */
	  if (ppszTextList)
	    XFreeStringList (ppszTextList);
	  if (xtpText.value)
	  {
	    XFree (xtpText.value);
	    xtpText.value = NULL;
	    xtpText.nitems = 0;
	  }
	  free(pszConvertData);
	  free(pwszUnicodeStr);
	  if (hGlobal && pszGlobalData)
	    GlobalUnlock (hGlobal);
	  if (fSetClipboardData && g_fUnicodeSupport)
	    SetClipboardData (CF_UNICODETEXT, NULL);
	  if (fSetClipboardData)
	    SetClipboardData (CF_TEXT, NULL);
	  return WIN_XEVENTS_NOTIFY;

        case SelectionClear:
          winDebug("SelectionClear - doing nothing\n");
          break;

	case PropertyNotify:
	  break;

	case MappingNotify:
	  break;

	default:
          ErrorF ("winClipboardFlushXEvents - unexpected event type %d\n", event.type);
	  break;
	}
    }

  return WIN_XEVENTS_SUCCESS;
}
Example #18
0
/*
 * WindowProc - handle messages for the main application window
 */
LONG _EXPORT FAR PASCAL WindowProc( HWND hwnd, unsigned msg,
                                     WORD wparam, LONG lparam )
{
    FARPROC     proc;
    HANDLE      hinst;
    LPEDATA     ed;
    DWORD       sel;
    int         state;
    HDC         hdc;

    ed = (LPEDATA) GetWindowLong( hwnd, EXTRA_DATA_OFFSET );

    /*
     * all messages are in alphabetical order, except WM_COMMAND, at the end
     */
    switch( msg ) {
    case WM_CLOSE:
        /*
         * see if it is okay to close down
         */
        if( CheckFileSave( ed ) ) {
            DestroyWindow( hwnd );
        }
        break;

    case WM_CREATE:
        /*
         * try to get printer support.  If it works, delete the DC,
         * since these are a system resource
         */
        hdc = PrinterDC();
        if( hdc ) {
            DeleteDC( hdc );
        }
        break;

    case WM_DESTROY:
        if( ed->font != NULL ) DeleteObject( ed->font );
        PostQuitMessage( 0 );
        break;

    case WM_DEVMODECHANGE:
    case WM_WININICHANGE:
        /*
         * handle user changing printer info
         */
        hdc = PrinterDC();
        if( hdc ) {
            DeleteDC( hdc );
        }
        break;

    case WM_FONTCHANGE:
        GetAllFonts( ed );
        break;

    case WM_INITMENU:
        /*
         * initial menu state set here
         */
        if( wparam == GetMenu( hwnd ) ) {

            state = MF_GRAYED;
            if( OpenClipboard( ed->hwnd ) ) {
                if( IsClipboardFormatAvailable( CF_TEXT ) ||
                    IsClipboardFormatAvailable( CF_OEMTEXT )) {
                    state = MF_ENABLED;
                }
                CloseClipboard();
            }
            EnableMenuItem( wparam, MENU_PASTE, state );

            state = MF_GRAYED;
            if( SendMessage( ed->editwnd, EM_CANUNDO, 0, 0L ) ) {
                state = MF_ENABLED;
            }
            EnableMenuItem( wparam, MENU_UNDO, state );
            sel = SendMessage( ed->editwnd, EM_GETSEL, 0, 0L );

            state = MF_GRAYED;
            if( HIWORD( sel ) != LOWORD( sel ) ) state = MF_ENABLED;
            EnableMenuItem( wparam, MENU_CLEAR, state );
            EnableMenuItem( wparam, MENU_COPY, state );
            EnableMenuItem( wparam, MENU_CUT, state );

            state = MF_GRAYED;
            if( PrinterSupport != PSUPP_NONE ) state = MF_ENABLED;
            EnableMenuItem( wparam, MENU_PRINT, state );
            state = MF_GRAYED;
            if( PrinterSupport == PSUPP_CANPRINTANDSET ) state = MF_ENABLED;
            EnableMenuItem( wparam, MENU_PRINT_SETUP, state );

        }
        return( NULL );

    case WM_QUERYENDSESSION:
        /*
         * check if it is okay to end the session
         */
        return( CheckFileSave( ed ) );

    case WM_SETFOCUS:
        /*
         * move the focus to our editor, rather than to the frame
         */
        SetFocus( ed->editwnd );
        break;

    case WM_SIZE:
        /*
         * resize edit window to match size of our client area
         */
        MoveWindow( ed->editwnd, 0, 0, LOWORD( lparam ),
                        HIWORD( lparam ), TRUE );
        break;


    case WM_COMMAND:
        switch( wparam ) {
        case EDIT_ID:
            switch( HIWORD( lparam ) ){
            case EN_CHANGE:
                ed->needs_saving = TRUE;
                break;
            case EN_ERRSPACE:
                MessageBox( hwnd, "Out of Space", EditTitle, MB_OK );
                break;
            }
            break;
        case MENU_ABOUT:
            hinst = GetWindowWord( hwnd, GWW_HINSTANCE );
            proc = MakeProcInstance( (FARPROC)AboutDlgProc, hinst );
            DialogBox( hinst,"AboutBox", hwnd, (DLGPROC)proc );
            FreeProcInstance( proc );
            break;
        case MENU_CLEAR:
            SendMessage( ed->editwnd, EM_REPLACESEL, 0, (LONG) (LPSTR)"" );
            break;
        case MENU_COPY:
            SendMessage( ed->editwnd, WM_COPY, 0, 0L );
            break;
        case MENU_CUT:
            SendMessage( ed->editwnd, WM_CUT, 0, 0L );
            break;
        case MENU_EXIT:
            if( CheckFileSave( ed ) ) {
                DestroyWindow( hwnd );
            }
            break;
        case MENU_FONT_SELECT:
            FontSelect( ed );
            break;
        case MENU_NEW:
            FileEdit( ed, FALSE );
            break;
        case MENU_OPEN:
            FileEdit( ed, TRUE );
            break;
        case MENU_PASTE:
            SendMessage( ed->editwnd, WM_PASTE, 0, 0L );
            break;
        case MENU_PRINT:
            Print( ed );
            break;
        case MENU_PRINT_SETUP:
            GetPrinterSetup( hwnd );
            break;
        case MENU_SAVE:
            FileSave( ed, FALSE );
            break;
        case MENU_SAVE_AS:
            FileSave( ed, TRUE );
            break;
        case MENU_UNDO:
            SendMessage( ed->editwnd, EM_UNDO, 0, 0L );
            break;
        }
        break;

    default:
        return( DefWindowProc( hwnd, msg, wparam, lparam ) );
    }
    return( 0L );

} /* WindowProc */
Example #19
0
/**
 *      Function that attempts to retrieve a string from the O/S clipboard
 *      If this functionality is not implemented for you O/S or if it fails then
 *      OSWRAP_FALSE will be returned. Otherwise OSWRAP_TRUE will be returned.
 *      It is assumed that dest has points to size number of allocated bytes.
 *      The actual number of bytes written into the destination buffer is
 *      written into wbytes. If you wish to retrieve all text on the clipboard
 *      you might want to continue calling this function as long as wbytes
 *      equals size. Do note that any other proccess can empty the clipboard
 *      in between calls.
 */
UInt32
StringFromClipboard( char *dest     ,
                     UInt32 size    ,
                     UInt32 *wbytes )
{
        #ifdef GUCEF_MSWIN_BUILD

        HWND whandle = GetCurrentHWND();
        HGLOBAL hglb;
        UInt32 success = OSWRAP_FALSE;

        #ifdef SDL_SUPPORT

        SDL_SysWMinfo winfo;

        #endif /* SDL_SUPPORT */

        if ( IsClipboardFormatAvailable( CF_TEXT ) )
        {
                /*
                 *      Open the clipboard with the current task as the owner
                 */
                if ( !OpenClipboard( whandle ) ) return OSWRAP_FALSE;

                /*
                 *      Get a pointer to the data using the global handle we will
                 *      obtain if possible. Then copy the data pointed to by the handle
                 *      into the buffer provided by the user
                 */
                hglb = GetClipboardData( CF_TEXT );
                if ( hglb != NULL )
                {
                        LPTSTR lptstr = (LPTSTR) GlobalLock( hglb );
                        if ( lptstr != NULL )
                        {
                                UInt32 offset = *wbytes;
                                UInt32 dsize = (UInt32) strlen( lptstr );
                                if ( dsize > offset )
                                {
                                        dsize -= offset;
                                        if ( dsize > size-1 ) dsize = size-1;
                                        strncpy( dest, lptstr+offset, dsize );
                                        *wbytes += dsize;

                                        success = OSWRAP_TRUE;
                                }
                                GlobalUnlock( hglb );
                        }
                        else
                        {
                                *wbytes = 0;
                        }
                }

                /*
                 *      Close the clipboard so that other tasks have access again
                 */
                CloseClipboard();

                return success;
        }
        return OSWRAP_FALSE;

        #else /* GUCEF_MSWIN_BUILD */

        return OSWRAP_FALSE;

        #endif /* OS WRAPPING */
}
Example #20
0
/* interface between MATLAB and the C function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
	/* declare variables */
	int ns, n2, m, n, put = 0;
	char *str;
	char *pchData;
	HGLOBAL hClipboardData;

	if ( !OpenClipboard(NULL) )
		mexErrMsgTxt("CLIPBD ERROR: Error while opening clipboard.\n");

	put = nrhs;

	EmptyClipboard();

	if (put && mxIsChar(prhs[0])) {
		str = (char *)mxArrayToString(prhs[0]);
		ns = strlen(str) + 1;

		hClipboardData = GlobalAlloc(GMEM_DDESHARE, ns);

		pchData = (char*)GlobalLock(hClipboardData);
		  
		strcpy(pchData, str);
		  
		GlobalUnlock(hClipboardData);
		  
		SetClipboardData(CF_TEXT,hClipboardData);
		  
	}
	else if (put && mxIsNumeric(prhs[0])) {
		UINT format = RegisterClipboardFormat("000_FMT");
		int is_single = 0, is_double = 0;
		clip_matFormat data; 

		if (mxIsSingle(prhs[0]))
			is_single = 1;

		else if (mxIsDouble(prhs[0]))
			is_double = 1;

		data.ny = mxGetM(prhs[0]);	data.nx = mxGetN(prhs[0]);
		if (nrhs == 2) {
			if ( mxGetM(prhs[1]) == 9 || mxGetN(prhs[1]) == 9 )
				data.head = mxGetPr(prhs[1]);
		}

		if (is_single)
			data.z_s = (float *)mxGetData(prhs[0]);
		else
			data.z_d = mxGetPr(prhs[0]);

		hClipboardData = GlobalAlloc(GMEM_DDESHARE, sizeof(clip_matFormat));
		clip_matFormat *buffer = (clip_matFormat *)GlobalLock(hClipboardData);

		/* put the data into that memory */
		*buffer = data;

		/* Put it on the clipboard */
		GlobalUnlock(hClipboardData);
		SetClipboardData(format,hClipboardData);
		mexPrintf("FFSSS %d\n;", format);
		mexPrintf("FDS %d\n", IsClipboardFormatAvailable(format));
	}
	else if (!put) {
		UINT format = RegisterClipboardFormat("000_FMT");

		/* No idea why it is not working. The 'format' is no
		   longer recognized as a registered one .*/
		mexPrintf("FDS %d\n", IsClipboardFormatAvailable(format));
		if ( !IsClipboardFormatAvailable(format) )
			mexErrMsgTxt("fd-se.\n");

		clip_matFormat data; 
		HANDLE hData = GetClipboardData(format);
		clip_matFormat *buffer = (clip_matFormat *)GlobalLock(hData);

		/* make a local copy */
		data = *buffer;

		mexPrintf("mmm %d\n", (buffer->ny));

		GlobalUnlock( hData );
	}

	CloseClipboard();
}
Example #21
0
void CMainFrame::OnUpdateEditPaste(CCmdUI* pCmdUI) 
{
	if(!(IsClipboardFormatAvailable(CF_DIB)||IsClipboardFormatAvailable(CF_ENHMETAFILE))) pCmdUI->Enable(FALSE);
}
Example #22
0
int clipboardhastext()
{
    return (int) IsClipboardFormatAvailable(CF_TEXT);
}
Example #23
0
//
//	Main Window message handler
//
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    NMHDR *hdr;
    POINT pt;
    RECT  rect;
    HMENU hMenu;
    HWND hwndHV = GetActiveHexView(hwnd);//g_hwndHexView;
    int i;
    TCITEM tci;

    MAINWND *mainWnd = (MAINWND *)GetWindowLongPtr(hwnd, 0);

    switch(msg)
    {
    case WM_NCCREATE:

        if((mainWnd = malloc(sizeof(MAINWND))) == 0)
            return FALSE;

        SetWindowLongPtr(hwnd, 0, (LONG_PTR)mainWnd);
        ZeroMemory(mainWnd, sizeof(MAINWND));
        return TRUE;

    case WM_NCDESTROY:
        free(mainWnd);
        return 0;

    case WM_CREATE:

        g_hwndMain = hwnd;

        SetWindowIcon(hwnd, IDI_APP);

        // create a child-window EDIT control
        //g_hwndHexView	= CreateHexViewCtrl(hwnd);
        g_hwndTabView	= CreateWindow(WC_TABVIEW, TEXT(""), WS_CHILD|WS_VISIBLE,0,0,0,0,hwnd, 0, g_hInstance, 0);
        g_hwndStatusBar = CreateStatusBar(hwnd);

        SendMessage(g_hwndTabView, TCM_SETITEMSIZE, 0, MAKELPARAM(150, 0));

        SetStatusBarParts(g_hwndStatusBar);

        hwndHV = g_hwndHexView;

        mainWnd->hwndMain		= hwnd;
        mainWnd->hwndStatusBar	= g_hwndStatusBar;
        mainWnd->hwndTabView	= g_hwndTabView;

        CreateToolTip(g_hwndHexView);

//		g_hwndDock[0] = CreateDockWnd(&dock, hwnd, TEXT("Toolbar"));



        //g_hwndToolbar   = InitToolbar(hwnd);
        //g_hwndSearchBar = CreateSearchBar(hwnd);
        //g_hwndTypeView  = CreateTypeView(hwnd);


        SetFocus(hwndHV);


        // tell windows that we can handle drag+drop'd files
        DragAcceptFiles(hwnd, TRUE);

        UpdateRecentMenu(GetSubMenu(GetMenu(hwnd), 0));

        SetTimer(hwnd, 0xdeadbeef, 1000, 0);

        return TRUE;

    case WM_TIMER:
        if(wParam == 0xdeadbeef)
        {
            KillTimer(hwnd, wParam);
            //FirstTimeOptions(hwnd);
        }
        return 0;

    case WM_DROPFILES:

        // get the screen coordinates of the drop-location
        if(DragQueryPoint((HDROP)wParam, &pt))
            ClientToScreen(hwnd, &pt);

        GetWindowRect(hwndHV, &rect);

        // drop anywhere *except* the hexview, as that does D&D itself
        if(!PtInRect(&rect, pt))
        {
            HandleDropFiles(hwnd, (HDROP)wParam);
        }

        //CreateToolTip(mainWnd->hwndTabView);
        return 0;

    case WM_ENABLE:
        EnableWindow(g_hwndSearch, (BOOL)wParam);
        EnableWindow(g_hwndGoto, (BOOL)wParam);
        return 0;

    case WM_CONTEXTMENU:
        if((HWND)wParam == DockWnd_GetWindow(hwnd, DWID_TYPEVIEW))
        {
            HMENU hMenu = GetSubMenu(LoadMenu(g_hInstance, MAKEINTRESOURCE(IDR_TYPECONTEXT)), 0);
            UINT  u;

            MenuCheckMark(hMenu, IDM_TYPEVIEW_HEX, g_fDisplayHex);
            MenuCheckMark(hMenu, IDM_TYPEVIEW_BIGENDIAN, g_fDisplayBigEndian);
            u = TrackPopupMenu(hMenu, TPM_RETURNCMD, (short)LOWORD(lParam), (short)HIWORD(lParam), 0, hwnd, 0);

            SendMessage(DockWnd_GetContents(hwnd, DWID_TYPEVIEW), WM_COMMAND, u, 0);
        }

        break;

    case WM_COMMAND:
        return HexEdit_OnCommand(hwnd, LOWORD(wParam), HIWORD(wParam), (HWND)lParam);

    case WM_NOTIFY:
        hdr = (NMHDR *)lParam;
        if(hdr->hwndFrom == hwndHV)
            return HexViewNotifyHandler(mainWnd, hwnd, hdr);
        else
            return HexEdit_OnNotify(mainWnd, hwnd, (UINT)wParam, (NMHDR *)lParam);

    case WM_CLOSE:

        tci.mask = TCIF_PARAM;

        for(i = 0; (hwndHV = EnumHexView(hwnd, i)) != NULL; )
        {
            UINT uAnswer = HexFileCloseNotify(hwnd, hwndHV);

            if(uAnswer == IDCANCEL)
            {
                return 0;
            }
            else if(uAnswer == IDNO)
            {
                SaveHighlights(hwndHV);
                TabCtrl_DeleteItem(mainWnd->hwndTabView, i);
            }
            else
            {
                i++;
            }
        }

        // save settings *before* we destroy anything!
        DockWnd_SaveSettings(hwnd);

        // shut program down
        DestroyWindow(hwnd);
        return 0;

    case WM_DESTROY:
        DestroyWindow(hwndHV);

        //
        PostQuitMessage(0);
        return 0;

    case WM_SETFOCUS:
        SetFocus(hwndHV);
        return 0;

    case WM_SIZE:

        MainWndSize(mainWnd, LOWORD(lParam), HIWORD(lParam));
        UpdateStatusbar(mainWnd->hwndStatusBar);

        return 0;

    case WM_INITMENUPOPUP:
        hMenu = (HMENU)wParam;//GetMenu(hwnd);

        MenuCheckMark(hMenu, IDM_VIEW_TOOLBAR, DockWnd_IsOpen(hwnd, DWID_TOOLBAR));
        MenuCheckMark(hMenu, IDM_TOOLS_TYPEVIEW, DockWnd_IsOpen(hwnd, DWID_TYPEVIEW));
        MenuCheckMark(hMenu, IDM_TOOLS_SEARCHBAR, DockWnd_IsOpen(hwnd, DWID_SEARCHBAR));

        CheckMenuRadioItem(hMenu, IDM_VIEW_HEX, IDM_VIEW_BIN,
                           IDM_VIEW_HEX + (HexView_GetStyle(hwndHV) & HVS_FORMAT_MASK),
                           MF_BYCOMMAND);

        {   int look[32] = { 0, 0, 1, 0, 2 };
            CheckMenuRadioItem(hMenu, IDM_GROUP_BYTE, IDM_GROUP_DWORD,
                               IDM_GROUP_BYTE + look[HexView_GetGrouping(hwndHV)],
                               MF_BYCOMMAND);
        }

        {
            size_w selsize;
            UINT   edmode  = HexView_GetEditMode(hwndHV);
            BOOL   cftext  = IsClipboardFormatAvailable(CF_TEXT);
            BOOL   canundo = HexView_CanUndo(hwndHV);
            BOOL   canredo = HexView_CanRedo(hwndHV);

            HexView_GetSelSize(hwndHV, &selsize);

            //hMenu = GetSubMenu(GetMenu(hwnd), 1);

            EnableMenuCmdItem(hMenu, IDM_EDIT_UNDO,  canundo);
            EnableMenuCmdItem(hMenu, IDM_EDIT_REDO,  canredo);
            EnableMenuCmdItem(hMenu, IDM_EDIT_CUT,  selsize > 0 && edmode == HVMODE_INSERT);
            EnableMenuCmdItem(hMenu, IDM_EDIT_COPY, selsize > 0);
            EnableMenuCmdItem(hMenu, IDM_EDIT_COPYAS, selsize > 0);
            EnableMenuCmdItem(hMenu, IDM_EDIT_PASTE, cftext && edmode != HVMODE_READONLY  );
            EnableMenuCmdItem(hMenu, IDM_EDIT_PASTESPECIAL, edmode != HVMODE_READONLY  );
            EnableMenuCmdItem(hMenu, IDM_EDIT_DELETE, selsize > 0 && edmode != HVMODE_READONLY );

            EnableMenuCmdItem(hMenu, IDM_EDIT_REVERSE, selsize > 0 && edmode != HVMODE_READONLY );
            EnableMenuCmdItem(hMenu, IDM_TOOLS_TRANSFORM, selsize > 0 && edmode != HVMODE_READONLY );

            EnableMenuCmdItem(hMenu, IDM_FILE_REVERT, canundo || canredo);
        }

        return 0;
    }

    return DefWindowProc(hwnd, msg, wParam, lParam);
}
Example #24
0
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
     static BOOL      bNeedSave = FALSE ;
     static HINSTANCE hInst ;
     static HWND      hwndEdit ;
     static int       iOffset ;
     static TCHAR     szFileName[MAX_PATH], szTitleName[MAX_PATH] ;
     static UINT      messageFindReplace ;
     int              iSelBeg, iSelEnd, iEnable ;
     LPFINDREPLACE    pfr ;
     
     switch (message)
     {
     case WM_CREATE:
          hInst = ((LPCREATESTRUCT) lParam) -> hInstance ;
          
               // Create the edit control child window
          
          hwndEdit = CreateWindow (TEXT ("edit"), NULL,
                              WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL |
                              WS_BORDER | ES_LEFT | ES_MULTILINE |
                              ES_NOHIDESEL | ES_AUTOHSCROLL | ES_AUTOVSCROLL,
                              0, 0, 0, 0,
                              hwnd, (HMENU) EDITID, hInst, NULL) ;
          
          SendMessage (hwndEdit, EM_LIMITTEXT, 32000, 0L) ;
          
               // Initialize common dialog box stuff
          
          PopFileInitialize (hwnd) ;
          PopFontInitialize (hwndEdit) ;
          
          messageFindReplace = RegisterWindowMessage (FINDMSGSTRING) ;
          
          DoCaption (hwnd, szTitleName) ;
          return 0 ;
          
     case WM_SETFOCUS:
          SetFocus (hwndEdit) ;
          return 0 ;
          
     case WM_SIZE: 
          MoveWindow (hwndEdit, 0, 0, LOWORD (lParam), HIWORD (lParam), TRUE) ;
          return 0 ;
          
     case WM_INITMENUPOPUP:
          switch (lParam)
          {
          case 1:             // Edit menu
               
                    // Enable Undo if edit control can do it
               
               EnableMenuItem ((HMENU) wParam, IDM_EDIT_UNDO,
                    SendMessage (hwndEdit, EM_CANUNDO, 0, 0L) ?
                                             MF_ENABLED : MF_GRAYED) ;
               
                    // Enable Paste if text is in the clipboard
               
               EnableMenuItem ((HMENU) wParam, IDM_EDIT_PASTE,
                    IsClipboardFormatAvailable (CF_TEXT) ?
                                             MF_ENABLED : MF_GRAYED) ;
               
                    // Enable Cut, Copy, and Del if text is selected
               
               SendMessage (hwndEdit, EM_GETSEL, (WPARAM) &iSelBeg,
                                                 (LPARAM) &iSelEnd) ;
               
               iEnable = iSelBeg != iSelEnd ? MF_ENABLED : MF_GRAYED ;
               
               EnableMenuItem ((HMENU) wParam, IDM_EDIT_CUT,   iEnable) ;
               EnableMenuItem ((HMENU) wParam, IDM_EDIT_COPY,  iEnable) ;
               EnableMenuItem ((HMENU) wParam, IDM_EDIT_CLEAR, iEnable) ;
               break ;
               
          case 2:             // Search menu
               
               // Enable Find, Next, and Replace if modeless
               //   dialogs are not already active
               
               iEnable = hDlgModeless == NULL ?
                              MF_ENABLED : MF_GRAYED ;
               
               EnableMenuItem ((HMENU) wParam, IDM_SEARCH_FIND,    iEnable) ;
               EnableMenuItem ((HMENU) wParam, IDM_SEARCH_NEXT,    iEnable) ;
               EnableMenuItem ((HMENU) wParam, IDM_SEARCH_REPLACE, iEnable) ;
               break ;
          }
          return 0 ;
     
     case WM_COMMAND:
               // Messages from edit control
          
          if (lParam && LOWORD (wParam) == EDITID)
          {
               switch (HIWORD (wParam))
               {
               case EN_UPDATE :
                    bNeedSave = TRUE ;
                    return 0 ;
                    
               case EN_ERRSPACE :
               case EN_MAXTEXT :
                    MessageBox (hwnd, TEXT ("Edit control out of space."),
                                szAppName, MB_OK | MB_ICONSTOP) ;
                    return 0 ;
               }
               break ;
          }
          
          switch (LOWORD (wParam))
          {
               // Messages from File menu
               
          case IDM_FILE_NEW:
               if (bNeedSave && IDCANCEL == AskAboutSave (hwnd, szTitleName))
                    return 0 ;
               
               SetWindowText (hwndEdit, TEXT ("\0")) ;
               szFileName[0]  = '\0' ;
               szTitleName[0] = '\0' ;
               DoCaption (hwnd, szTitleName) ;
               bNeedSave = FALSE ;
               return 0 ;
               
          case IDM_FILE_OPEN:
               if (bNeedSave && IDCANCEL == AskAboutSave (hwnd, szTitleName))
                    return 0 ;
               
               if (PopFileOpenDlg (hwnd, szFileName, szTitleName))
               {
                    if (!PopFileRead (hwndEdit, szFileName))
                    {
                         OkMessage (hwnd, TEXT ("Could not read file %s!"),
                                    szTitleName) ;
                         szFileName[0]  = '\0' ;
                         szTitleName[0] = '\0' ;
                    }
               }
               
               DoCaption (hwnd, szTitleName) ;
               bNeedSave = FALSE ;
               return 0 ;
               
          case IDM_FILE_SAVE:
               if (szFileName[0])
               {
                    if (PopFileWrite (hwndEdit, szFileName))
                    {
                         bNeedSave = FALSE ;
                         return 1 ;
                    }
                    else
                    {
                         OkMessage (hwnd, TEXT ("Could not write file %s"),
                                    szTitleName) ;
                         return 0 ;
                    }
               }
                                   // fall through
          case IDM_FILE_SAVE_AS:
               if (PopFileSaveDlg (hwnd, szFileName, szTitleName))
               {
                    DoCaption (hwnd, szTitleName) ;
                    
                    if (PopFileWrite (hwndEdit, szFileName))
                    {
                         bNeedSave = FALSE ;
                         return 1 ;
                    }
                    else
                    {
                         OkMessage (hwnd, TEXT ("Could not write file %s"),
                                    szTitleName) ;
                         return 0 ;
                    }
               }
               return 0 ;
               
          case IDM_FILE_PRINT:
               if (!PopPrntPrintFile (hInst, hwnd, hwndEdit, szTitleName))
                    OkMessage (hwnd, TEXT ("Could not print file %s"),
                                     szTitleName) ;
               return 0 ;
               
          case IDM_APP_EXIT:
               SendMessage (hwnd, WM_CLOSE, 0, 0) ;
               return 0 ;
               
                    // Messages from Edit menu
               
          case IDM_EDIT_UNDO:
               SendMessage (hwndEdit, WM_UNDO, 0, 0) ;
               return 0 ;
               
          case IDM_EDIT_CUT:
               SendMessage (hwndEdit, WM_CUT, 0, 0) ;
               return 0 ;
               
          case IDM_EDIT_COPY:
               SendMessage (hwndEdit, WM_COPY, 0, 0) ;
               return 0 ;
               
          case IDM_EDIT_PASTE:
               SendMessage (hwndEdit, WM_PASTE, 0, 0) ;
               return 0 ;
               
          case IDM_EDIT_CLEAR:
               SendMessage (hwndEdit, WM_CLEAR, 0, 0) ;
               return 0 ;
               
          case IDM_EDIT_SELECT_ALL:
               SendMessage (hwndEdit, EM_SETSEL, 0, -1) ;
               return 0 ;
               
                    // Messages from Search menu
               
          case IDM_SEARCH_FIND:
               SendMessage (hwndEdit, EM_GETSEL, 0, (LPARAM) &iOffset) ;
               hDlgModeless = PopFindFindDlg (hwnd) ;
               return 0 ;
               
          case IDM_SEARCH_NEXT:
               SendMessage (hwndEdit, EM_GETSEL, 0, (LPARAM) &iOffset) ;
               
               if (PopFindValidFind ())
                    PopFindNextText (hwndEdit, &iOffset) ;
               else
                    hDlgModeless = PopFindFindDlg (hwnd) ;
               
               return 0 ;
               
          case IDM_SEARCH_REPLACE:
               SendMessage (hwndEdit, EM_GETSEL, 0, (LPARAM) &iOffset) ;
               hDlgModeless = PopFindReplaceDlg (hwnd) ;
               return 0 ;
               
          case IDM_FORMAT_FONT:
               if (PopFontChooseFont (hwnd))
                    PopFontSetFont (hwndEdit) ;
               
               return 0 ;
               
                    // Messages from Help menu
               
          case IDM_HELP:
               OkMessage (hwnd, TEXT ("Help not yet implemented!"), 
                                TEXT ("\0")) ;
               return 0 ;
               
          case IDM_APP_ABOUT:
               DialogBox (hInst, TEXT ("AboutBox"), hwnd, AboutDlgProc) ;
               return 0 ;
          }
          break ;
               
     case WM_CLOSE:
          if (!bNeedSave || IDCANCEL != AskAboutSave (hwnd, szTitleName))
               DestroyWindow (hwnd) ;
          
          return 0 ;
          
     case WM_QUERYENDSESSION :
          if (!bNeedSave || IDCANCEL != AskAboutSave (hwnd, szTitleName))
               return 1 ;
          
          return 0 ;
          
     case WM_DESTROY:
          PopFontDeinitialize () ;
          PostQuitMessage (0) ;
          return 0 ;
          
     default:
               // Process "Find-Replace" messages
          
          if (message == messageFindReplace)
          {
               pfr = (LPFINDREPLACE) lParam ;
               
               if (pfr->Flags & FR_DIALOGTERM)
                    hDlgModeless = NULL ;
               
               if (pfr->Flags & FR_FINDNEXT)
                    if (!PopFindFindText (hwndEdit, &iOffset, pfr))
                         OkMessage (hwnd, TEXT ("Text not found!"), 
                                          TEXT ("\0")) ;
                    
               if (pfr->Flags & FR_REPLACE || pfr->Flags & FR_REPLACEALL)
                    if (!PopFindReplaceText (hwndEdit, &iOffset, pfr))
                         OkMessage (hwnd, TEXT ("Text not found!"), 
                                          TEXT ("\0")) ;
                         
               if (pfr->Flags & FR_REPLACEALL)
                    while (PopFindReplaceText (hwndEdit, &iOffset, pfr)) ;
                              
               return 0 ;
          }
          break ;
     }
     return DefWindowProc (hwnd, message, wParam, lParam) ;
}
Example #25
0
LRESULT CALLBACK
winClipboardWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static HWND s_hwndNextViewer;
    static Bool s_fCBCInitialized;

    /* Branch on message type */
    switch (message) {
    case WM_DESTROY:
    {
        winDebug("winClipboardWindowProc - WM_DESTROY\n");

        /* Remove ourselves from the clipboard chain */
        ChangeClipboardChain(hwnd, s_hwndNextViewer);

        s_hwndNextViewer = NULL;

        PostQuitMessage(0);
    }
        return 0;

    case WM_CREATE:
    {
        HWND first, next;
        DWORD error_code = 0;

        winDebug("winClipboardWindowProc - WM_CREATE\n");

        first = GetClipboardViewer();   /* Get handle to first viewer in chain. */
        if (first == hwnd)
            return 0;           /* Make sure it's not us! */
        /* Add ourselves to the clipboard viewer chain */
        next = SetClipboardViewer(hwnd);
        error_code = GetLastError();
        if (SUCCEEDED(error_code) && (next == first))   /* SetClipboardViewer must have succeeded, and the handle */
            s_hwndNextViewer = next;    /* it returned must have been the first window in the chain */
        else
            s_fCBCInitialized = FALSE;
    }
        return 0;

    case WM_CHANGECBCHAIN:
    {
        winDebug("winClipboardWindowProc - WM_CHANGECBCHAIN: wParam(%x) "
                 "lParam(%x) s_hwndNextViewer(%x)\n",
                 wParam, lParam, s_hwndNextViewer);

        if ((HWND) wParam == s_hwndNextViewer) {
            s_hwndNextViewer = (HWND) lParam;
            if (s_hwndNextViewer == hwnd) {
                s_hwndNextViewer = NULL;
                winErrorFVerb(1, "winClipboardWindowProc - WM_CHANGECBCHAIN: "
                              "attempted to set next window to ourselves.");
            }
        }
        else if (s_hwndNextViewer)
            SendMessage(s_hwndNextViewer, message, wParam, lParam);

    }
        winDebug("winClipboardWindowProc - WM_CHANGECBCHAIN: Exit\n");
        return 0;

    case WM_WM_REINIT:
    {
        /* Ensure that we're in the clipboard chain.  Some apps,
         * WinXP's remote desktop for one, don't play nice with the
         * chain.  This message is called whenever we receive a
         * WM_ACTIVATEAPP message to ensure that we continue to
         * receive clipboard messages.
         *
         * It might be possible to detect if we're still in the chain
         * by calling SendMessage (GetClipboardViewer(),
         * WM_DRAWCLIPBOARD, 0, 0); and then seeing if we get the
         * WM_DRAWCLIPBOARD message.  That, however, might be more
         * expensive than just putting ourselves back into the chain.
         */

        HWND first, next;
        DWORD error_code = 0;

        winDebug("winClipboardWindowProc - WM_WM_REINIT: Enter\n");

        first = GetClipboardViewer();   /* Get handle to first viewer in chain. */
        if (first == hwnd)
            return 0;           /* Make sure it's not us! */
        winDebug("  WM_WM_REINIT: Replacing us(%x) with %x at head "
                 "of chain\n", hwnd, s_hwndNextViewer);
        s_fCBCInitialized = FALSE;
        ChangeClipboardChain(hwnd, s_hwndNextViewer);
        s_hwndNextViewer = NULL;
        s_fCBCInitialized = FALSE;
        winDebug("  WM_WM_REINIT: Putting us back at head of chain.\n");
        first = GetClipboardViewer();   /* Get handle to first viewer in chain. */
        if (first == hwnd)
            return 0;           /* Make sure it's not us! */
        next = SetClipboardViewer(hwnd);
        error_code = GetLastError();
        if (SUCCEEDED(error_code) && (next == first))   /* SetClipboardViewer must have succeeded, and the handle */
            s_hwndNextViewer = next;    /* it returned must have been the first window in the chain */
        else
            s_fCBCInitialized = FALSE;
    }
        winDebug("winClipboardWindowProc - WM_WM_REINIT: Exit\n");
        return 0;

    case WM_DRAWCLIPBOARD:
    {
        static Atom atomClipboard;
        static int generation;
        static Bool s_fProcessingDrawClipboard = FALSE;
        Display *pDisplay = g_pClipboardDisplay;
        Window iWindow = g_iClipboardWindow;
        int iReturn;

        winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD: Enter\n");

        if (generation != serverGeneration) {
            generation = serverGeneration;
            atomClipboard = XInternAtom(pDisplay, "CLIPBOARD", False);
        }

        /*
         * We've occasionally seen a loop in the clipboard chain.
         * Try and fix it on the first hint of recursion.
         */
        if (!s_fProcessingDrawClipboard) {
            s_fProcessingDrawClipboard = TRUE;
        }
        else {
            /* Attempt to break the nesting by getting out of the chain, twice?, and then fix and bail */
            s_fCBCInitialized = FALSE;
            ChangeClipboardChain(hwnd, s_hwndNextViewer);
            winFixClipboardChain();
            winErrorFVerb(1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                          "Nested calls detected.  Re-initing.\n");
            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
            s_fProcessingDrawClipboard = FALSE;
            return 0;
        }

        /* Bail on first message */
        if (!s_fCBCInitialized) {
            s_fCBCInitialized = TRUE;
            s_fProcessingDrawClipboard = FALSE;
            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
            return 0;
        }

        /*
         * NOTE: We cannot bail out when NULL == GetClipboardOwner ()
         * because some applications deal with the clipboard in a manner
         * that causes the clipboard owner to be NULL when they are in
         * fact taking ownership.  One example of this is the Win32
         * native compile of emacs.
         */

        /* Bail when we still own the clipboard */
        if (hwnd == GetClipboardOwner()) {

            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                     "We own the clipboard, returning.\n");
            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
            s_fProcessingDrawClipboard = FALSE;
            if (s_hwndNextViewer)
                SendMessage(s_hwndNextViewer, message, wParam, lParam);
            return 0;
        }

        /*
         * Do not take ownership of the X11 selections when something
         * other than CF_TEXT or CF_UNICODETEXT has been copied
         * into the Win32 clipboard.
         */
        if (!IsClipboardFormatAvailable(CF_TEXT)
            && !IsClipboardFormatAvailable(CF_UNICODETEXT)) {

            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                     "Clipboard does not contain CF_TEXT nor "
                     "CF_UNICODETEXT.\n");

            /*
             * We need to make sure that the X Server has processed
             * previous XSetSelectionOwner messages.
             */
            XSync(pDisplay, FALSE);

            winDebug("winClipboardWindowProc - XSync done.\n");

            /* Release PRIMARY selection if owned */
            iReturn = XGetSelectionOwner(pDisplay, XA_PRIMARY);
            if (iReturn == g_iClipboardWindow) {
                winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                         "PRIMARY selection is owned by us.\n");
                XSetSelectionOwner(pDisplay, XA_PRIMARY, None, CurrentTime);
            }
            else if (BadWindow == iReturn || BadAtom == iReturn)
                winErrorFVerb(1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                              "XGetSelection failed for PRIMARY: %d\n",
                              iReturn);

            /* Release CLIPBOARD selection if owned */
            iReturn = XGetSelectionOwner(pDisplay, atomClipboard);
            if (iReturn == g_iClipboardWindow) {
                winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                         "CLIPBOARD selection is owned by us.\n");
                XSetSelectionOwner(pDisplay, atomClipboard, None, CurrentTime);
            }
            else if (BadWindow == iReturn || BadAtom == iReturn)
                winErrorFVerb(1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                              "XGetSelection failed for CLIPBOARD: %d\n",
                              iReturn);

            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
            s_fProcessingDrawClipboard = FALSE;
            if (s_hwndNextViewer)
                SendMessage(s_hwndNextViewer, message, wParam, lParam);
            return 0;
        }

        /* Reassert ownership of PRIMARY */
        iReturn = XSetSelectionOwner(pDisplay,
                                     XA_PRIMARY, iWindow, CurrentTime);
        if (iReturn == BadAtom || iReturn == BadWindow ||
            XGetSelectionOwner(pDisplay, XA_PRIMARY) != iWindow) {
            winErrorFVerb(1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                          "Could not reassert ownership of PRIMARY\n");
        }
        else {
            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                     "Reasserted ownership of PRIMARY\n");
        }

        /* Reassert ownership of the CLIPBOARD */
        iReturn = XSetSelectionOwner(pDisplay,
                                     atomClipboard, iWindow, CurrentTime);

        if (iReturn == BadAtom || iReturn == BadWindow ||
            XGetSelectionOwner(pDisplay, atomClipboard) != iWindow) {
            winErrorFVerb(1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                          "Could not reassert ownership of CLIPBOARD\n");
        }
        else {
            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                     "Reasserted ownership of CLIPBOARD\n");
        }

        /* Flush the pending SetSelectionOwner event now */
        XFlush(pDisplay);

        s_fProcessingDrawClipboard = FALSE;
    }
        winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
        /* Pass the message on the next window in the clipboard viewer chain */
        if (s_hwndNextViewer)
            SendMessage(s_hwndNextViewer, message, wParam, lParam);
        return 0;

    case WM_DESTROYCLIPBOARD:
        /*
         * NOTE: Intentionally do nothing.
         * Changes in the Win32 clipboard are handled by WM_DRAWCLIPBOARD
         * above.  We only process this message to conform to the specs
         * for delayed clipboard rendering in Win32.  You might think
         * that we need to release ownership of the X11 selections, but
         * we do not, because a WM_DRAWCLIPBOARD message will closely
         * follow this message and reassert ownership of the X11
         * selections, handling the issue for us.
         */
        winDebug("winClipboardWindowProc - WM_DESTROYCLIPBOARD - Ignored.\n");
        return 0;

    case WM_RENDERFORMAT:
    case WM_RENDERALLFORMATS:
    {
        int iReturn;
        Display *pDisplay = g_pClipboardDisplay;
        Window iWindow = g_iClipboardWindow;
        Bool fConvertToUnicode;

        winDebug("winClipboardWindowProc - WM_RENDER*FORMAT - Hello.\n");

        /* Flag whether to convert to Unicode or not */
        if (message == WM_RENDERALLFORMATS)
            fConvertToUnicode = FALSE;
        else
            fConvertToUnicode = g_fUnicodeSupport && (CF_UNICODETEXT == wParam);

        /* Request the selection contents */
        iReturn = XConvertSelection(pDisplay,
                                    g_atomLastOwnedSelection,
                                    XInternAtom(pDisplay,
                                                "COMPOUND_TEXT", False),
                                    XInternAtom(pDisplay,
                                                "CYGX_CUT_BUFFER", False),
                                    iWindow, CurrentTime);
        if (iReturn == BadAtom || iReturn == BadWindow) {
            winErrorFVerb(1, "winClipboardWindowProc - WM_RENDER*FORMAT - "
                          "XConvertSelection () failed\n");
            break;
        }

        /* Special handling for WM_RENDERALLFORMATS */
        if (message == WM_RENDERALLFORMATS) {
            /* We must open and empty the clipboard */

            /* Close clipboard if we have it open already */
            if (GetOpenClipboardWindow() == hwnd) {
                CloseClipboard();
            }

            if (!OpenClipboard(hwnd)) {
                winErrorFVerb(1, "winClipboardWindowProc - WM_RENDER*FORMATS - "
                              "OpenClipboard () failed: %08x\n",
                              GetLastError());
                break;
            }

            if (!EmptyClipboard()) {
                winErrorFVerb(1, "winClipboardWindowProc - WM_RENDER*FORMATS - "
                              "EmptyClipboard () failed: %08x\n",
                              GetLastError());
                break;
            }
        }

        /* Process the SelectionNotify event */
        iReturn = winProcessXEventsTimeout(hwnd,
                                           iWindow,
                                           pDisplay,
                                           fConvertToUnicode, WIN_POLL_TIMEOUT);

        /*
         * The last call to winProcessXEventsTimeout
         * from above had better have seen a notify event, or else we
         * are dealing with a buggy or old X11 app.  In these cases we
         * have to paste some fake data to the Win32 clipboard to
         * satisfy the requirement that we write something to it.
         */
        if (WIN_XEVENTS_NOTIFY != iReturn) {
            /* Paste no data, to satisfy required call to SetClipboardData */
            if (g_fUnicodeSupport)
                SetClipboardData(CF_UNICODETEXT, NULL);
            SetClipboardData(CF_TEXT, NULL);

            ErrorF
                ("winClipboardWindowProc - timed out waiting for WIN_XEVENTS_NOTIFY\n");
        }

        /* Special handling for WM_RENDERALLFORMATS */
        if (message == WM_RENDERALLFORMATS) {
            /* We must close the clipboard */

            if (!CloseClipboard()) {
                winErrorFVerb(1,
                              "winClipboardWindowProc - WM_RENDERALLFORMATS - "
                              "CloseClipboard () failed: %08x\n",
                              GetLastError());
                break;
            }
        }

        winDebug("winClipboardWindowProc - WM_RENDER*FORMAT - Returning.\n");
        return 0;
    }
    }

    /* Let Windows perform default processing for unhandled messages */
    return DefWindowProc(hwnd, message, wParam, lParam);
}
Example #26
0
//
// I_GetClipboardText
//
// by Denis Lukianov - 20 Mar 2006
// Cross-platform clipboard functionality
//
std::string I_GetClipboardText (void)
{
#ifdef X11
	std::string ret;

	Display *dis = XOpenDisplay(NULL);
	int screen = DefaultScreen(dis);

	if(!dis)
	{
		Printf(PRINT_HIGH, "I_GetClipboardText: XOpenDisplay failed");
		return "";
	}

	XLockDisplay(dis);

	Window WindowEvents = XCreateSimpleWindow(dis, RootWindow(dis, screen), 0, 0, 1, 1, 0, BlackPixel(dis, screen), BlackPixel(dis, screen));

	if(XGetSelectionOwner(dis, XA_PRIMARY) != None)
	{
		if(!XConvertSelection(dis, XA_PRIMARY, XA_STRING, XA_PRIMARY, WindowEvents, CurrentTime))
		{
			XDestroyWindow(dis, WindowEvents);
			XUnlockDisplay(dis);
			XCloseDisplay(dis);
			Printf(PRINT_HIGH, "I_GetClipboardText: XConvertSelection failed");
			return "";
		}

		XFlush (dis);

		// Wait for the reply
		for(;;)
		{
			XEvent e;
			XNextEvent(dis, &e);

			if(e.type == SelectionNotify)
				break;
		}

		Atom type;
		int format, result;
		u_long len, bytes_left, temp;
		u_char *data;

		result = XGetWindowProperty(dis, WindowEvents, XA_PRIMARY, 0, 0, False, AnyPropertyType, &type, &format, &len, &bytes_left, &data);
		if(result != Success)
		{
			XDestroyWindow(dis, WindowEvents);
			XUnlockDisplay(dis);
			XCloseDisplay(dis);
			Printf(PRINT_HIGH, "I_GetClipboardText: XGetWindowProperty failed(1)");
			return "";
		}

		if(!bytes_left)
		{
			XDestroyWindow(dis, WindowEvents);
			DPrintf("I_GetClipboardText: Len was: %d", len);
			XUnlockDisplay(dis);
			XCloseDisplay(dis);
			return "";
		}

		result = XGetWindowProperty(dis, WindowEvents, XA_PRIMARY, 0, bytes_left, False, AnyPropertyType, &type, &format, &len, &temp, &data);
		if(result != Success)
		{
			XDestroyWindow(dis, WindowEvents);
			XUnlockDisplay(dis);
			XCloseDisplay(dis);
			Printf(PRINT_HIGH, "I_GetClipboardText: XGetWindowProperty failed(2)");
			return "";
		}

		ret = std::string((const char *)data, len);
		XFree(data);
	}

	XDestroyWindow(dis, WindowEvents);
	XUnlockDisplay(dis);
	XCloseDisplay(dis);

	return ret;
#endif

#if defined _WIN32 && !defined _XBOX
	std::string ret;

	if(!IsClipboardFormatAvailable(CF_TEXT))
		return "";

	if(!OpenClipboard(NULL))
		return "";

	HANDLE hClipboardData = GetClipboardData(CF_TEXT);

	if(!hClipboardData)
	{
		CloseClipboard();
		return "";
	}

	const char *cData = reinterpret_cast<const char *>(GlobalLock(hClipboardData));
	SIZE_T uiSize = static_cast<SIZE_T>(GlobalSize(hClipboardData));

	if(cData && uiSize)
	{
		for(size_t i = 0; i < uiSize; i++)
		{
			if(!cData[i])
			{
				uiSize = i;
				break;
			}
		}

		ret = std::string(cData, uiSize);
	}

	GlobalUnlock(hClipboardData);

	CloseClipboard();

	return ret;
#endif

#ifdef OSX
	ScrapRef scrap;
	Size size;

	int err = GetCurrentScrap(&scrap);

	if(err)
	{
		Printf(PRINT_HIGH, "GetCurrentScrap error: %d", err);
		return "";
	}

	err = GetScrapFlavorSize(scrap, FOUR_CHAR_CODE('TEXT'), &size);

	if(err)
	{
		Printf(PRINT_HIGH, "GetScrapFlavorSize error: %d", err);
		return "";
	}

	char *data = new char[size+1];

	err = GetScrapFlavorData(scrap, FOUR_CHAR_CODE('TEXT'), &size, data);
	data[size] = 0;

	if(err)
	{
		Printf(PRINT_HIGH, "GetScrapFlavorData error: %d", err);
		delete[] data;

		return "";
	}

	std::string ret(data);

	delete[] data;

	return ret;
#endif

	return "";
}
Example #27
0
WINEXPORT LRESULT CALLBACK WMainWndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
    HMENU           menu;
#if 0
    HWND            win;
#endif
    LRESULT         ret;
    bool            pass_to_def;
    WAccelEditInfo  *einfo;
    WORD            wp;
    MINMAXINFO      *minmax;
    about_info      ai;

    pass_to_def = TRUE;
    ret = FALSE;
    einfo = (WAccelEditInfo *)GET_WNDLONGPTR( hWnd, 0 );
    WSetCurrentEditInfo( einfo );

    if( einfo != NULL && einfo->getting_key ) {
        if( WGetKeyPressProc( einfo, message, wParam, lParam ) ) {
            einfo->getting_key = FALSE;
            DestroyWindow( einfo->key_info.text_win );
            ReleaseCapture();
            WHandleChange( einfo );
            pass_to_def = FALSE;
        }
    }

    switch( message ) {
    case WM_ACTIVATE:
        if( GET_WM_ACTIVATE_FACTIVE( wParam, lParam ) &&
            !GET_WM_ACTIVATE_FMINIMIZED( wParam, lParam ) &&
            einfo != NULL && einfo->edit_dlg != (HWND)NULL ) {
            SetFocus( einfo->edit_dlg );
            pass_to_def = FALSE;
        }
        break;

    case WM_INITMENU:
        if( wParam == (WPARAM)GetMenu( hWnd ) ) {
            // set the cut and copy menu items
            if( SendDlgItemMessage( einfo->edit_dlg, IDM_ACCEDLIST, LB_GETCURSEL, 0, 0 ) != LB_ERR ) {
                EnableMenuItem( (HMENU)wParam, IDM_ACC_CUT, MF_ENABLED );
                EnableMenuItem( (HMENU)wParam, IDM_ACC_COPY, MF_ENABLED );
            } else {
                EnableMenuItem( (HMENU)wParam, IDM_ACC_CUT, MF_GRAYED );
                EnableMenuItem( (HMENU)wParam, IDM_ACC_COPY, MF_GRAYED );
            }
            // set the paste menu item
            if( OpenClipboard( hWnd ) ) {
                if( //IsClipboardFormatAvailable( WClipbdFormat ) ||
                    IsClipboardFormatAvailable( WItemClipbdFormat ) ) {
                    EnableMenuItem( (HMENU)wParam, IDM_ACC_PASTE, MF_ENABLED );
                } else {
                    EnableMenuItem( (HMENU)wParam, IDM_ACC_PASTE, MF_GRAYED );
                }
                CloseClipboard();
            }
        }
        break;

    case WM_CREATE:
        einfo = ((CREATESTRUCT *)lParam)->lpCreateParams;
        SET_WNDLONGPTR( hWnd, 0, (LONG_PTR)einfo );
        break;

    case WM_MENUSELECT:
        if( einfo != NULL ) {
            menu = WGetMenuHandle( einfo );
            WHandleMenuSelect( einfo->wsb, menu, wParam, lParam );
            setLastMenuSelect( einfo, wParam, lParam );
        }
        break;

    case WM_GETMINMAXINFO:
        minmax = (MINMAXINFO *)lParam;
        minmax->ptMinTrackSize.x = appWidth;
        minmax->ptMinTrackSize.y = appHeight;
        break;

    case WM_MOVE:
        if( einfo != NULL ) {
            if( IsZoomed( hWnd ) ) {
                WSetOption( WOptScreenMax, TRUE );
            } else if( !IsIconic( hWnd ) ) {
                WUpdateScreenPosOpt( hWnd );
                WSetOption( WOptScreenMax, FALSE );
            }
        }
        break;

    case WM_SIZE:
        if( einfo != NULL ) {
            if( wParam == SIZE_MAXIMIZED ) {
                WSetOption( WOptScreenMax, TRUE );
            } else if( wParam != SIZE_MINIMIZED ) {
                WUpdateScreenPosOpt( hWnd );
                WSetOption( WOptScreenMax, FALSE );
            }
            WResizeWindows( einfo );
        }
        break;

#if 0
    case WM_ACTIVATE:
        if( GET_WM_ACTIVATE_FACTIVE( wParam, lParam ) != WA_INACTIVE ) {
            einfo = (WAccelEditInfo *)GET_WNDLONGPTR( hWnd, 0 );
            if( einfo != NULL && einfo->edit_dlg != (HWND)NULL ) {
                SetFocus( einfo->edit_dlg );
            }
            WSetCurrentEditInfo( einfo );
        } else {
            WSetCurrentEditInfo( NULL );
        }
        break;
#endif

    case WM_COMMAND:
        wp = LOWORD( wParam );
        switch( wp ) {
        case IDM_ACC_CLEAR:
            WHandleClear( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_UPDATE:
            SendMessage( einfo->info->parent, ACCEL_PLEASE_SAVEME, 0, (LPARAM)einfo->hndl );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_OPEN:
            pass_to_def = FALSE;
            if( einfo->info->modified ) {
                ret = WQuerySave( einfo, FALSE );
                if( !ret ) {
                    break;
                }
            }
            ret = SendMessage( einfo->info->parent, ACCEL_PLEASE_OPENME, 0,
                               (LPARAM)einfo->hndl );
            ret = FALSE;
            break;

        case IDM_ACC_SAVE:
            WSaveObject( einfo, FALSE, FALSE );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_SAVEAS:
            WSaveObject( einfo, TRUE, FALSE );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_SAVEINTO:
            WSaveObject( einfo, TRUE, TRUE );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_EXIT:
            /* clean up before we exit */
            PostMessage( einfo->win, WM_CLOSE, 0, 0 );
            break;

        case IDM_ACC_PASTE:
            WPasteAccelItem( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_COPY:
        case IDM_ACC_CUT:
            WClipAccelItem( einfo, wp == IDM_ACC_CUT );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_DELETE:
            WDeleteAccelEntry( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_NEWITEM:
            WInsertAccelEntry( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_KEYVALUE:
            WSetStatusByID( einfo->wsb, W_GETTINGKEYS, -1 );
            WHandleGetKeyValue( einfo, einfo->last_menu_select == IDM_ACC_KEYVALUE );
            WSetStatusReadyText( einfo->wsb );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_SYMBOLS:
            handleSymbols( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_LOAD_SYMBOLS:
            handleLoadSymbols( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_SHOWRIBBON:
            menu = WGetMenuHandle( einfo );
            WShowRibbon( einfo, menu );
            pass_to_def = FALSE;
            break;

        case IDM_ACC_MEM_FLAGS:
            WSetStatusByID( einfo->wsb, W_CHANGEACCELMEMFLAGS, -1 );
            einfo->info->modified |= WChangeMemFlags( einfo->win, &einfo->info->MemFlags,
                                                      einfo->info->res_name,
                                                      WGetEditInstance(),
                                                      WAccHelpRoutine );
            pass_to_def = FALSE;
            WSetStatusReadyText( einfo->wsb );
            break;

        case IDM_ACC_RENAME:
            WHandleRename( einfo );
            pass_to_def = FALSE;
            break;

        case IDM_HELP:
            WAccHelpRoutine();
            pass_to_def = FALSE;
            break;

        case IDM_HELP_SEARCH:
            WAccHelpSearchRoutine();
            pass_to_def = FALSE;
            break;

        case IDM_HELP_ON_HELP:
            WAccHelpOnHelpRoutine();
            pass_to_def = FALSE;
            break;

        case IDM_ACC_ABOUT:
            ai.owner = hWnd;
            ai.inst = WGetEditInstance();
            ai.name = AllocRCString( W_ABOUT_NAME );
            ai.version = AllocRCString( W_ABOUT_VERSION );
            ai.first_cr_year = "2002";
            ai.title = AllocRCString( W_ABOUT_TITLE );
            DoAbout( &ai );
            FreeRCString( ai.name );
            FreeRCString( ai.version );
            FreeRCString( ai.title );
            pass_to_def = FALSE;
            break;
        }
        break;

    case WM_DESTROY:
        WWinHelp( hWnd, "resacc.hlp", HELP_QUIT, 0 );
        WCleanup( einfo );
        break;

    case WM_CLOSE:
        ret = TRUE;
        pass_to_def = WHandleWM_CLOSE( einfo, wParam != 0 );
        wParam = 0;
        break;
    }

    if( pass_to_def ) {
        ret = DefWindowProc( hWnd, message, wParam, lParam );
    }

    return( ret );
}
Example #28
0
BOOL AddKeyClipboard(HWND hwnd,void *PGPsc,void *PGPtls)
{
	PGPContextRef context;
	char *pInput;
	DWORD dwInputSize;
	UINT ClipboardFormat;
	MYSTATE *ms;
	PGPtlsContextRef tls;
	PGPError err;

	// Check for files copied into clipboard from explorer
	if(OpenClipboard(hwnd)) 
	{
		if(IsClipboardFormatAvailable(CF_HDROP))
		{
			FILELIST *ListHead;
			HDROP hDrop;

			hDrop=(HDROP)GetClipboardData(CF_HDROP);
			ListHead=HDropToFileList(hDrop);

			if(ListHead!=0)
			{
				CloseClipboard();

				return AddKeyFileList(hwnd,
					PGPsc,PGPtls,ListHead);
			}
		}
		CloseClipboard();
	}

	err=kPGPError_NoErr;

	context=(PGPContextRef)PGPsc;
	tls=(PGPtlsContextRef)PGPtls;

	if(IsPGPError(PGPclEvalExpired(hwnd, PGPCL_ALLEXPIRED)))
		return FALSE;

	pInput=RetrieveClipboardData(hwnd, &ClipboardFormat, 
			                     &dwInputSize);

	if(!pInput)
	{
		PGPscMessageBox (hwnd,IDS_PGPERROR,IDS_NOCLIPBOARDCONTENTS,
					MB_OK|MB_ICONSTOP);
	}
	else
	{
		if((ClipboardFormat != CF_TEXT)||(*pInput==0))
		{
			PGPscMessageBox (hwnd,IDS_PGPERROR,IDS_NOCLIPBOARDTEXT,
				MB_OK|MB_ICONSTOP);
		}
		else
		{
			ms=(MYSTATE *)malloc(sizeof(MYSTATE));

			if(ms)
			{
				memset(ms, 0x00, sizeof(MYSTATE) );

				ms->context=context;
				ms->tlsContext=tls;
				ms->pInput=pInput;
				ms->dwInputSize=dwInputSize;
				ms->Operation=MS_ADDKEYCLIPBOARD;

				if(OpenRings(hwnd,context,&(ms->KeySet)))
				{
					err=SCProgressDialog(hwnd,DoWorkThread,ms,
						  0,"Adding Keys from Clipboard...",
						  "","",IDR_PROGAVI);

// If no PGP data in clipboard, warn....
					if(!(ms->FoundPGPData))
						PGPscMessageBox (hwnd,IDS_PGPERROR,IDS_NOPGPKEYSINCLIPBOARD,
							MB_OK|MB_ICONEXCLAMATION);

					PGPFreeKeySet(ms->KeySet);
				}
				free(ms);
			}
		}
		memset(pInput,0x00,dwInputSize);
		free(pInput);
	}

	if(IsPGPError(err))
		return FALSE;

	return TRUE;
}
Example #29
0
BOOL cIMEWnd::OnKey(HWND hWnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
	switch(wparam)
	{
	case VK_LEFT:
		if( m_pDockingEx->GetValidCheckMethod() != VCM_NUMBER )
			m_pDockingEx->CaretMoveLeft();
		break;

	case VK_RIGHT:
		m_pDockingEx->CaretMoveRight();
		break;

	case VK_UP:
		m_pDockingEx->CaretMoveUp();
		break;

	case VK_DOWN:
		m_pDockingEx->CaretMoveDown();
		break;

	case VK_HOME:
		if( m_pDockingEx->GetValidCheckMethod() != VCM_NUMBER )
			m_pDockingEx->CaretMoveHome();
		break;

	case VK_END:
		m_pDockingEx->CaretMoveEnd();
		break;

	case VK_RETURN:
		{
			m_pDockingEx->Enter();

//			if( m_pDockingEx->GetParentEdit() )
//				m_pDockingEx->GetParentEdit()->IMEEvent( eIMEE_ENTER );
			if( m_pDockingEx->GetParentEdit() )
				m_pDockingEx->GetParentEdit()->ExcuteCBFunc( WE_RETURN );
		}
		break;

	case VK_DELETE:
		m_pDockingEx->DeleteAfter();
		break;

	case VK_BACK:	//IME COMPOSING 시에는 안들어온다...
		m_pDockingEx->DeleteBefore();
		break;

	case VK_TAB:
		{
			//
			WINDOWMGR->SetNextEditFocus();
		}
		break;

	case VK_CONTROL:
		{
			m_bCtrlPushed = TRUE;
		}
		break;

#ifndef _TL_LOCAL_
	case 'V':
		{
			if( m_bCtrlPushed )
			if( IsClipboardFormatAvailable(CF_TEXT) )
			{
				if( OpenClipboard(hWnd) )
				{
					m_pDockingEx->Paste( (char*)GetClipboardData( CF_TEXT ) );
					CloseClipboard();
				}
			}
		}
		break;
#endif
	}

	return TRUE;
}
Example #30
0
BOOL 
GMDataToPaste (VOID) 
{
	if (IsClipboardFormatAvailable (CF_TEXT)) return TRUE;
	return FALSE;
}