OSDN Git Service

Is64ProcessHwnd invokes OpenProcess with PROCESS_QUERY_INFORMATION. #25429
[xkeymacs/xkeymacs.git] / xkeymacsdll / xkeymacsdll.cpp
1 // xkeymacsdll.cpp : Defines the initialization routines for the DLL.\r
2 //\r
3 \r
4 #include "stdafx.h"\r
5 #include "resource.h"\r
6 #include "Utils.h"\r
7 #include "Commands.h"\r
8 #include <afxdllx.h>\r
9 #include <math.h>\r
10 #include <Imm.h>\r
11 #include <vector>\r
12 \r
13 #ifdef _DEBUG\r
14 #define new DEBUG_NEW\r
15 #undef THIS_FILE\r
16 static char THIS_FILE[] = __FILE__;\r
17 #endif\r
18 \r
19 struct Modifier {\r
20         LPCTSTR name;\r
21         int id;\r
22 };\r
23 \r
24 static const Modifier Modifiers[] = {\r
25 //      { _T("A-"), ALT },\r
26         { _T("C-"), CONTROL},\r
27 //      { _T("H-"), HYPER },\r
28         { _T("M-"), META },\r
29         { _T("S-"), SHIFT },\r
30 //      { _T("s-"), SUPER },\r
31         { _T("Ctrl+"), WIN_CTRL },\r
32         { _T("Alt+"), WIN_ALT },\r
33         { _T("Win+"), WIN_WIN },\r
34 };\r
35 static const int MAX_MODIFIER = _countof(Modifiers);\r
36 \r
37 static const KeyName KeyNames[] = {\r
38 //      { VK_LBUTTON,           _T("mouse-1") },                                // does not work well\r
39 //      { VK_RBUTTON,           _T("mouse-3") },                                // does not work well\r
40         { VK_CANCEL,            _T("break") },\r
41 //      { VK_MBUTTON,           _T("mouse-2") },                                // does not work well\r
42         { VK_BACK,                      _T("backspace") },\r
43         { VK_TAB,                       _T("tab") },\r
44         { VK_RETURN,            _T("return") },\r
45         { VK_CAPITAL,           _T("capslock") },\r
46         { VK_KANA,                      _T("kana") },\r
47         { VK_KANJI,                     _T("kanji") },\r
48         { VK_ESCAPE,            _T("escape") },\r
49         { VK_CONVERT,           _T("convert") },\r
50         { VK_NONCONVERT,        _T("nonconvert") },\r
51 //      { VK_SPACE,                     _T("SPC") },                                    // [? ]\r
52         { VK_PRIOR,                     _T("prior") },\r
53         { VK_NEXT,                      _T("next") },\r
54         { VK_END,                       _T("end") },\r
55         { VK_HOME,                      _T("home") },\r
56         { VK_LEFT,                      _T("left") },\r
57         { VK_UP,                        _T("up") },\r
58         { VK_RIGHT,                     _T("right") },\r
59         { VK_DOWN,                      _T("down") },\r
60         { VK_SELECT,            _T("select") },\r
61         { VK_PRINT,                     _T("print") },\r
62         { VK_EXECUTE,           _T("execute") },\r
63         { VK_SNAPSHOT,          _T("printscreen") },                    // work as print\r
64         { VK_INSERT,            _T("insert") },\r
65         { VK_DELETE,            _T("delete") },\r
66         { VK_LWIN,                      _T("lwindow") },\r
67         { VK_RWIN,                      _T("rwindow") },\r
68         { VK_APPS,                      _T("apps") },\r
69         { VK_SLEEP,                     _T("sleep") },\r
70         { VK_NUMPAD0,           _T("kp-0") },\r
71         { VK_NUMPAD1,           _T("kp-1") },\r
72         { VK_NUMPAD2,           _T("kp-2") },\r
73         { VK_NUMPAD3,           _T("kp-3") },\r
74         { VK_NUMPAD4,           _T("kp-4") },\r
75         { VK_NUMPAD5,           _T("kp-5") },\r
76         { VK_NUMPAD6,           _T("kp-6") },\r
77         { VK_NUMPAD7,           _T("kp-7") },\r
78         { VK_NUMPAD8,           _T("kp-8") },\r
79         { VK_NUMPAD9,           _T("kp-9") },\r
80         { VK_MULTIPLY,          _T("kp-multiply") },\r
81         { VK_ADD,                       _T("kp-add") },\r
82         { VK_SUBTRACT,          _T("kp-subtract") },\r
83         { VK_DECIMAL,           _T("kp-decimal") },\r
84         { VK_DIVIDE,            _T("kp-divide") },\r
85 //      { VK_F1,                        _T("f1") },                                             // FIXME\r
86 //      { VK_F2,                        _T("f2") },                                             // Move at the end of definition of function keys to keep away confliction f1/f2 and f1?/f2? by _tcsncmp() i.e. strncmp()\r
87         { VK_F3,                        _T("f3") },\r
88         { VK_F4,                        _T("f4") },\r
89         { VK_F5,                        _T("f5") },\r
90         { VK_F6,                        _T("f6") },\r
91         { VK_F7,                        _T("f7") },\r
92         { VK_F8,                        _T("f8") },\r
93         { VK_F9,                        _T("f9") },\r
94         { VK_F10,                       _T("f10") },\r
95         { VK_F11,                       _T("f11") },\r
96         { VK_F12,                       _T("f12") },\r
97         { VK_F13,                       _T("f13") },\r
98         { VK_F14,                       _T("f14") },\r
99         { VK_F15,                       _T("f15") },\r
100         { VK_F16,                       _T("f16") },\r
101         { VK_F17,                       _T("f17") },\r
102         { VK_F18,                       _T("f18") },\r
103         { VK_F19,                       _T("f19") },\r
104         { VK_F20,                       _T("f20") },\r
105         { VK_F21,                       _T("f21") },\r
106         { VK_F22,                       _T("f22") },\r
107         { VK_F23,                       _T("f23") },\r
108         { VK_F24,                       _T("f24") },\r
109         { VK_F1,                        _T("f1") },\r
110         { VK_F2,                        _T("f2") },\r
111         { VK_NUMLOCK,           _T("kp-numlock") },\r
112         { VK_SCROLL,            _T("scroll") },\r
113         { 0xa6,                         _T("browser-back") },                   // VK_BROWSER_BACK\r
114         { 0xa7,                         _T("browser-forward") },                // VK_BROWSER_FORWARD\r
115         { 0xa8,                         _T("browser-refresh") },                // VK_BROWSER_REFRESH\r
116         { 0xa9,                         _T("browser-stop") },                   // VK_BROWSER_STOP\r
117         { 0xaa,                         _T("browser-search") },                 // VK_BROWSER_SEARCH\r
118         { 0xab,                         _T("browser-favorites") },              // VK_BROWSER_FAVORITES\r
119         { 0xac,                         _T("browser-home") },                   // VK_BROWSER_HOME\r
120         { 0xad,                         _T("volume-mute") },                    // VK_VOLUME_MUTE\r
121         { 0xae,                         _T("volume-down") },                    // VK_VOLUME_DOWN\r
122         { 0xaf,                         _T("volume-up") },                              // VK_VOLUME_UP\r
123         { 0xb0,                         _T("media-next-track") },               // VK_MEDIA_NEXT_TRACK\r
124         { 0xb1,                         _T("media-prev-track") },               // VK_MEDIA_PREV_TRACK\r
125         { 0xb2,                         _T("media-stop") },                             // VK_MEDIA_STOP\r
126         { 0xb3,                         _T("media-play-pause") },               // VK_MEDIA_PLAY_PAUSE\r
127         { 0xb4,                         _T("launch-mail") },                    // VK_LAUNCH_MAIL\r
128         { 0xb5,                         _T("launch-media-select") },    // VK_LAUNCH_MEDIA_SELECT\r
129         { 0xb6,                         _T("launch-1") },                               // VK_LAUNCH_APP1\r
130         { 0xb7,                         _T("launch-2") },                               // VK_LAUNCH_APP2\r
131 };\r
132 static const int MAX_KEYNAME = _countof(KeyNames);\r
133 \r
134 static AFX_EXTENSION_MODULE XkeymacsdllDLL = { NULL, NULL };\r
135 \r
136 HINSTANCE g_hDllInst = NULL;\r
137 UINT g_ImeManipulationMessage = 0;\r
138 #pragma data_seg(".xkmcs")\r
139 HHOOK g_hHookKeyboard = NULL;\r
140 HHOOK g_hHookDummy = NULL;\r
141 #pragma data_seg()\r
142 \r
143 inline bool IsWow64(HANDLE mod)\r
144 {\r
145         typedef BOOL (WINAPI *pfnIsWow64Process_t)(HANDLE, PBOOL);\r
146         if (const pfnIsWow64Process_t IsWow64Process = (pfnIsWow64Process_t)GetProcAddress(GetModuleHandle(_T("kernel32")), "IsWow64Process")) {\r
147                 BOOL b;\r
148                 return IsWow64Process(mod, &b) && b;\r
149         }\r
150         return false;\r
151 }\r
152 \r
153 inline bool Is64System()\r
154 {\r
155         SYSTEM_INFO info;\r
156         GetNativeSystemInfo(&info);\r
157         return info.wProcessorArchitecture != PROCESSOR_ARCHITECTURE_INTEL;\r
158 }\r
159 \r
160 inline bool Is64Process(HANDLE mod)\r
161 {\r
162         return Is64System() && !IsWow64(mod);\r
163 }\r
164 \r
165 const bool IsDll64 = sizeof(void *) == 8;\r
166 \r
167 inline bool Is64ProcessHwnd(HWND hwnd)\r
168 {\r
169         DWORD pid;\r
170         GetWindowThreadProcessId(hwnd, &pid);\r
171         HANDLE hmod = OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid);\r
172         bool b = Is64Process(hmod);\r
173         CloseHandle(hmod);\r
174         return b;\r
175 }\r
176 \r
177 extern "C" int APIENTRY\r
178 DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)\r
179 {\r
180         g_hDllInst = hInstance;\r
181         \r
182         // Remove this if you use lpReserved\r
183         UNREFERENCED_PARAMETER(lpReserved);\r
184 \r
185         switch (dwReason) {\r
186         case DLL_PROCESS_ATTACH:\r
187                 TRACE0("XKEYMACSDLL.DLL Initializing!\n");\r
188                 g_ImeManipulationMessage = RegisterWindowMessage(_T("XkManipulateIME"));\r
189 \r
190                 // Extension DLL one-time initialization\r
191                 if (!AfxInitExtensionModule(XkeymacsdllDLL, hInstance)) {\r
192                         return 0;\r
193                 }\r
194 \r
195                 // Insert this DLL into the resource chain\r
196                 // NOTE: If this Extension DLL is being implicitly linked to by\r
197                 //  an MFC Regular DLL (such as an ActiveX Control)\r
198                 //  instead of an MFC application, then you will want to\r
199                 //  remove this line from DllMain and put it in a separate\r
200                 //  function exported from this Extension DLL.  The Regular DLL\r
201                 //  that uses this Extension DLL should then explicitly call that\r
202                 //  function to initialize this Extension DLL.  Otherwise,\r
203                 //  the CDynLinkLibrary object will not be attached to the\r
204                 //  Regular DLL's resource chain, and serious problems will\r
205                 //  result.\r
206 \r
207                 try {\r
208                         new CDynLinkLibrary(XkeymacsdllDLL);\r
209                 }\r
210                 catch (CMemoryException* e) {\r
211                         e->Delete();\r
212 //                      CUtils::Log("DllMain: 'new' threw an exception");\r
213                 }\r
214                 break;\r
215         case DLL_PROCESS_DETACH:\r
216                 TRACE0("XKEYMACSDLL.DLL Terminating!\n");\r
217                 // Terminate the library before destructors are called\r
218                 AfxTermExtensionModule(XkeymacsdllDLL);\r
219                 break;\r
220         }\r
221         return 1;   // ok\r
222 }\r
223 \r
224 //////////////////////////////////////////////////////////////////////\r
225 // CXkeymacsDll Class\r
226 //////////////////////////////////////////////////////////////////////\r
227 \r
228 #include "xkeymacsDll.h"\r
229 #pragma data_seg(".xkmcs")\r
230         DWORD   CXkeymacsDll::m_nHookAltRelease = 0;\r
231         HHOOK   CXkeymacsDll::m_hHookCallWnd = NULL;\r
232         HHOOK   CXkeymacsDll::m_hHookCallWndRet = NULL;\r
233         HHOOK   CXkeymacsDll::m_hHookGetMessage = NULL;\r
234         HHOOK   CXkeymacsDll::m_hHookShell = NULL;\r
235         BOOL    CXkeymacsDll::m_bRightControl   = FALSE;\r
236         BOOL    CXkeymacsDll::m_bRightAlt               = FALSE;\r
237         BOOL    CXkeymacsDll::m_bRightShift             = FALSE;\r
238         BOOL    CXkeymacsDll::m_bHook                   = TRUE;\r
239         CList<CClipboardSnap *, CClipboardSnap *> CXkeymacsDll::m_oKillRing;\r
240         int             CXkeymacsDll::m_nKillRing = 0;\r
241         int             CXkeymacsDll::m_nOriginal[MAX_COMMAND_TYPE][MAX_KEY] = {'\0'};\r
242         int             CXkeymacsDll::m_nApplicationID = 0;\r
243         int             CXkeymacsDll::m_nAccelerate = 0;\r
244         int             CXkeymacsDll::m_nKeyboardSpeed = 31;\r
245         HCURSOR CXkeymacsDll::m_hCursor[MAX_STATUS] = {'\0'};\r
246         HCURSOR CXkeymacsDll::m_hCurrentCursor = NULL;\r
247         BOOL    CXkeymacsDll::m_bCursor = FALSE;\r
248         TCHAR   CXkeymacsDll::m_M_xTip[128] = "";\r
249         CONFIG  CXkeymacsDll::m_Config = {0};\r
250 #pragma data_seg()\r
251 BOOL CXkeymacsDll::m_bRecordingMacro = FALSE;\r
252 BOOL CXkeymacsDll::m_bDown[MAX_KEY] = {0};\r
253 std::list<KbdMacro> CXkeymacsDll::m_Macro;\r
254 \r
255 BOOL CXkeymacsDll::SaveConfig()\r
256 {\r
257         TCHAR szTmp[MAX_PATH];\r
258         if (!GetTempPath(MAX_PATH, szTmp))\r
259                 return FALSE;\r
260         if (_tmakepath_s(szTmp, NULL, szTmp, _T("xkeymacs"), _T("tmp")))\r
261                 return FALSE;\r
262         HANDLE hFile = CreateFile(szTmp, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);\r
263         if (hFile == INVALID_HANDLE_VALUE)\r
264                 return FALSE;\r
265         DWORD written;\r
266         BOOL res = WriteFile(hFile, &m_Config, sizeof(m_Config), &written, NULL) || written != sizeof(m_Config);\r
267         CloseHandle(hFile);\r
268         return res;\r
269 }\r
270 \r
271 BOOL CXkeymacsDll::LoadConfig()\r
272 {\r
273         TCHAR szTmp[MAX_PATH];\r
274         if (!GetTempPath(MAX_PATH, szTmp))\r
275                 return FALSE;\r
276         if (_tmakepath_s(szTmp, NULL, szTmp, _T("xkeymacs"), _T("tmp")))\r
277                 return FALSE;\r
278         HANDLE hFile = CreateFile(szTmp, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);\r
279         if (hFile == INVALID_HANDLE_VALUE)\r
280                 return FALSE;\r
281         DWORD read;\r
282         BOOL res = ReadFile(hFile, &m_Config, sizeof(m_Config), &read, NULL) && read == sizeof(m_Config);\r
283         CloseHandle(hFile);\r
284         return res;\r
285 }\r
286 \r
287 // set hooks\r
288 LRESULT WINAPI DummyProc(int code, WPARAM wp, LPARAM lp) {\r
289         return CallNextHookEx(0, code, wp, lp);\r
290 }\r
291 \r
292 void CXkeymacsDll::SetHooks()\r
293 {\r
294         m_hHookCallWnd = SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)CallWndProc, g_hDllInst, 0);\r
295         m_hHookCallWndRet = SetWindowsHookEx(WH_CALLWNDPROCRET, (HOOKPROC)CallWndRetProc, g_hDllInst, 0);\r
296         m_hHookGetMessage = SetWindowsHookEx(WH_GETMESSAGE, (HOOKPROC)GetMsgProc, g_hDllInst, 0);\r
297         m_hHookShell = SetWindowsHookEx(WH_SHELL, (HOOKPROC)ShellProc, g_hDllInst, 0);\r
298         g_hHookDummy = SetWindowsHookEx(WH_GETMESSAGE, (HOOKPROC)DummyProc, g_hDllInst, 0);\r
299         g_hHookKeyboard = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)KeyboardProc, g_hDllInst, 0);\r
300 }\r
301 \r
302 inline void unhook(HHOOK &hh) {\r
303         if (hh)\r
304                 UnhookWindowsHookEx(hh);\r
305         hh = NULL;\r
306 }\r
307 \r
308 void CXkeymacsDll::ResetHooks() \r
309 {\r
310         ReleaseHooks();\r
311         SetHooks();\r
312 }\r
313 \r
314 // release hooks\r
315 void CXkeymacsDll::ReleaseHooks()\r
316 {\r
317         unhook(m_hHookCallWnd);\r
318         unhook(m_hHookCallWndRet);\r
319         unhook(m_hHookGetMessage);\r
320         unhook(m_hHookShell);\r
321         unhook(g_hHookKeyboard);\r
322         unhook(g_hHookDummy);\r
323 }\r
324 \r
325 void CXkeymacsDll::ToggleKeyboardHookState()\r
326 {\r
327         m_bHook = !m_bHook;\r
328         ShowKeyboardHookState();\r
329 }\r
330 \r
331 void CXkeymacsDll::ShowKeyboardHookState()\r
332 {\r
333         ICONMSG msg = {MAIN_ICON,};\r
334         if (m_bHook) {\r
335                 if (CCommands::IsTemporarilyDisableXKeymacs()) {\r
336                         msg.nState = STATUS_DISABLE_TMP;\r
337                         m_hCurrentCursor = m_hCursor[STATUS_DISABLE_TMP];\r
338                 } else {\r
339                         msg.nState = STATUS_ENABLE;\r
340                         m_hCurrentCursor = m_hCursor[STATUS_ENABLE];\r
341                 }\r
342         } else {\r
343                 msg.nState = STATUS_DISABLE_WOCQ;\r
344         }\r
345         if (m_Config.nSettingStyle[m_nApplicationID] == SETTING_DISABLE\r
346          || (!_tcsicmp(m_Config.szSpecialApp[m_nApplicationID], _T("Default"))\r
347           && CUtils::IsDefaultIgnoreApplication())) {\r
348                 msg.nState = STATUS_DISABLE;\r
349                 m_hCurrentCursor = m_hCursor[STATUS_DISABLE];\r
350         }\r
351         SendIconMessage(&msg, 1);\r
352         DoSetCursor();\r
353 }\r
354 \r
355 BOOL CXkeymacsDll::IsKeyboardHook()\r
356 {\r
357         return m_bHook;\r
358 }\r
359 \r
360 LRESULT CALLBACK CXkeymacsDll::CallWndProc(int nCode, WPARAM wParam, LPARAM lParam)\r
361 {\r
362         if (nCode < 0)\r
363                 return CallNextHookEx(m_hHookCallWnd, nCode, wParam, lParam);\r
364         const CWPSTRUCT *cwps = reinterpret_cast<CWPSTRUCT *>(lParam);\r
365         switch (cwps->message) {\r
366         case WM_IME_STARTCOMPOSITION:\r
367                 InitKeyboardProc(TRUE);\r
368                 break;\r
369         case WM_IME_ENDCOMPOSITION:\r
370                 InitKeyboardProc(FALSE);\r
371                 break;\r
372         case WM_SETFOCUS:\r
373                 if (cwps->hwnd == GetForegroundWindow()) {\r
374                         InitKeyboardProc(FALSE);\r
375                         ShowKeyboardHookState();\r
376                 }\r
377                 break;\r
378         case WM_NCACTIVATE:\r
379                 if (cwps->wParam && cwps->hwnd == GetForegroundWindow()) {\r
380                         InitKeyboardProc(FALSE);\r
381                         ShowKeyboardHookState();\r
382                 }\r
383                 break;\r
384         }\r
385         return CallNextHookEx(m_hHookCallWnd, nCode, wParam, lParam);\r
386 }\r
387 \r
388 LRESULT CALLBACK CXkeymacsDll::CallWndRetProc(int nCode, WPARAM wParam, LPARAM lParam)\r
389 {\r
390         if (nCode >= 0) {\r
391                 const CWPRETSTRUCT *cwprets = reinterpret_cast<CWPRETSTRUCT *>(lParam);\r
392                 switch (cwprets->message) {\r
393                 case WM_SETTEXT:\r
394                         if (cwprets->hwnd == GetForegroundWindow())\r
395                                 InitKeyboardProc(FALSE);\r
396                         break;\r
397                 case WM_SETCURSOR:\r
398                         DoSetCursor();\r
399                         break;\r
400                 }\r
401         }\r
402         return CallNextHookEx(m_hHookCallWndRet, nCode, wParam, lParam);\r
403 }\r
404 \r
405 LRESULT CALLBACK CXkeymacsDll::GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)\r
406 {\r
407         const MSG *msg = reinterpret_cast<MSG *>(lParam);\r
408         if (msg->message == g_ImeManipulationMessage) {\r
409                 if (wParam)\r
410                         CCommands::DoSetInputMethodOpenStatus(static_cast<INPUT_METHOD_OPEN_STATUS>(msg->wParam), static_cast<BOOL>(msg->lParam));\r
411                 return 1;\r
412         }\r
413         switch (msg->message) {\r
414         case WM_IME_STARTCOMPOSITION:\r
415                 InitKeyboardProc(TRUE);\r
416                 break;\r
417         case WM_IME_ENDCOMPOSITION:\r
418                 InitKeyboardProc(FALSE);\r
419                 break;\r
420         }\r
421         return CallNextHookEx(m_hHookGetMessage, nCode, wParam, lParam);\r
422 }\r
423 \r
424 LRESULT CALLBACK CXkeymacsDll::ShellProc(int nCode, WPARAM wParam, LPARAM lParam)\r
425 {\r
426         if (nCode == HSHELL_WINDOWACTIVATED) {\r
427                 TCHAR className[256];\r
428                 GetClassName((HWND)wParam, className, 255);\r
429                 if (!_tcsicmp(className, _T("ConsoleWindowClass"))) {\r
430                         InitKeyboardProc(FALSE);\r
431                         ShowKeyboardHookState();\r
432                 }\r
433         }\r
434         return CallNextHookEx( m_hHookShell, nCode, wParam, lParam );\r
435 }\r
436 \r
437 UINT CXkeymacsDll::GetModifierState(BOOL bPhysicalKey)\r
438 {\r
439         UINT result = 0;\r
440         if (IsDown(VK_SHIFT, bPhysicalKey))\r
441                 result |= SHIFT;\r
442         if (IsDown(VK_CONTROL, bPhysicalKey))\r
443                 result |= CONTROL;\r
444         if (IsDown(VK_MENU, bPhysicalKey))\r
445                 result |= META;\r
446         return result;\r
447 }\r
448 \r
449 void CXkeymacsDll::SetModifierState(const UINT after, const UINT before)\r
450 {\r
451         if (after & SHIFT && !(before & SHIFT))\r
452                 DepressKey(VK_SHIFT);\r
453         else if (!(after & SHIFT) && before & SHIFT)\r
454                 ReleaseKey(VK_SHIFT);\r
455 \r
456         if (after & CONTROL && !(before & CONTROL)) {\r
457                 UpdateKeyboardState(VK_CONTROL, 1);\r
458                 DepressKey(VK_CONTROL);\r
459         } else if (!(after & CONTROL) && before & CONTROL) {\r
460                 ReleaseKey(VK_CONTROL);\r
461                 UpdateKeyboardState(VK_CONTROL, 0);\r
462         }\r
463 \r
464         const BOOL bHookApp = CUtils::IsVisualCpp() || CUtils::IsFirefox() || CUtils::IsVisualStudio() || CUtils::IsInternetExplorer();\r
465         if (after & META && !(before & META)) {\r
466                 if (bHookApp)\r
467                         m_nHookAltRelease |= HOOK_ALT_LATER;\r
468                 DepressKey(VK_MENU);\r
469         } else if (!(after & META) && before & META) {\r
470                 if (bHookApp)\r
471                         m_nHookAltRelease++;\r
472                 ReleaseKey(VK_MENU);\r
473         }\r
474 }\r
475 \r
476 BOOL CXkeymacsDll::UpdateKeyboardState(BYTE bVk, BYTE bState)\r
477 {\r
478         BYTE ks[256] = {'\0'};\r
479         if (!GetKeyboardState(ks))\r
480                 return FALSE;\r
481         ks[bVk] = bState;\r
482         return SetKeyboardState(ks);\r
483 }\r
484 \r
485 BOOL CXkeymacsDll::IsDown(BYTE bVk, BOOL bPhysicalKey)\r
486 {\r
487         return bPhysicalKey ? GetAsyncKeyState(bVk) < 0 : GetKeyState(bVk) < 0;\r
488 }\r
489 \r
490 // Do keybd_event\r
491 void CXkeymacsDll::DoKeybd_event(BYTE bVk, DWORD dwFlags)\r
492 {\r
493         // Set KEYEVENTF_EXTENDEDKEY if needed\r
494         switch (bVk) {\r
495         case VK_CONTROL:\r
496                 if (m_bRightControl)\r
497                         dwFlags |= KEYEVENTF_EXTENDEDKEY;\r
498                 break;\r
499 \r
500         case VK_MENU:\r
501                 if (m_bRightAlt)\r
502                         dwFlags |= KEYEVENTF_EXTENDEDKEY;\r
503                 break;\r
504 \r
505         case VK_SHIFT:\r
506                 if (m_bRightShift) {\r
507                         if (CUtils::IsXPorLater())\r
508                                 bVk = VK_RSHIFT;\r
509                         else\r
510                                 dwFlags |= KEYEVENTF_EXTENDEDKEY;\r
511                 }\r
512                 break;\r
513         case VK_PAUSE:\r
514                 if (IsDown(VK_CONTROL, FALSE)) // Break\r
515                         dwFlags |= KEYEVENTF_EXTENDEDKEY;\r
516                 break;\r
517         case VK_INSERT:\r
518         case VK_DELETE:\r
519         case VK_HOME:\r
520         case VK_END:\r
521         case VK_NEXT:\r
522         case VK_PRIOR:\r
523         case VK_UP:\r
524         case VK_DOWN:\r
525         case VK_RIGHT:\r
526         case VK_LEFT:\r
527         case VK_NUMLOCK:\r
528         case VK_PRINT:\r
529                 dwFlags |= KEYEVENTF_EXTENDEDKEY;\r
530                 break;\r
531         }\r
532 //      CUtils::Log(_T("b: %x, %x, %x, %#hx, %#hx"), bVk, dwFlags, GetMessageExtraInfo(), GetKeyState(bVk), GetAsyncKeyState(bVk));\r
533         keybd_event(bVk, 0, dwFlags, GetMessageExtraInfo());\r
534 //      CUtils::Log(_T("a: %x, %x, %x, %#hx, %#hx"), bVk, dwFlags, GetMessageExtraInfo(), GetKeyState(bVk), GetAsyncKeyState(bVk));\r
535 }\r
536 \r
537 // the key is being depressed\r
538 void CXkeymacsDll::DepressKey(BYTE bVk, BOOL bOriginal) // bVk is virtual-key code, MSDN said\r
539 {\r
540         if (bOriginal) {\r
541 //              CUtils::Log(_T("i: %x, %d, %d, %d, %d, %d, %d, %d, %d"), bVk,\r
542 //                      IsDown(VK_CONTROL), IsDown(VK_CONTROL, FALSE), IsDepressedModifier(CCommands::C_), IsDepressedModifier(CCommands::C_, FALSE),\r
543 //                      IsDown(VK_MENU), IsDown(VK_MENU, FALSE), IsDepressedModifier(CCommands::MetaAlt), IsDepressedModifier(CCommands::MetaAlt, FALSE));\r
544                 SetOriginal(GetModifierState(), bVk);\r
545         }\r
546         DoKeybd_event(bVk, 0);\r
547 }\r
548 \r
549 // the key is being released\r
550 void CXkeymacsDll::ReleaseKey(BYTE bVk) // bVk is virtual-key code, MSDN said\r
551 {\r
552         DoKeybd_event(bVk, KEYEVENTF_KEYUP);\r
553 }\r
554 \r
555 // bVk down, bVk up\r
556 void CXkeymacsDll::Kdu(BYTE bVk, DWORD n, BOOL bOriginal)\r
557 {\r
558         while (n--) {\r
559                 DepressKey(bVk, bOriginal);\r
560                 ReleaseKey(bVk);\r
561         }\r
562 }\r
563 \r
564 void CXkeymacsDll::InitKeyboardProc(BOOL bImeComposition)\r
565 {\r
566         CUtils::SetApplicationName(bImeComposition);\r
567         if (_tcsnicmp(m_Config.szSpecialApp[m_nApplicationID], CUtils::GetApplicationName(), 0xF) || !IsMatchWindowText(m_Config.szWindowText[m_nApplicationID])) {     // PROCESSENTRY32 has only 0xF bytes of Name\r
568                 m_nApplicationID = -1;\r
569                 for (int nAppID = 0; nAppID < MAX_APP; nAppID++) {\r
570                         if (_tcsnicmp(m_Config.szSpecialApp[nAppID], CUtils::GetApplicationName(), 0xF) || !IsMatchWindowText(m_Config.szWindowText[nAppID]))\r
571                                 continue;\r
572                         if (m_nApplicationID < 0)\r
573                                 m_nApplicationID = nAppID;\r
574                         else {\r
575                                 const LPCSTR curText = m_Config.szWindowText[m_nApplicationID];\r
576                                 const LPCSTR newText = m_Config.szWindowText[nAppID];\r
577                                 const int curType = CUtils::GetWindowTextType(curText);\r
578                                 const int newType = CUtils::GetWindowTextType(newText);\r
579                                 if (curType < newType || curType == newType && _tcscmp(curText, newText) <= 0)\r
580                                         m_nApplicationID = nAppID;\r
581                         }\r
582                 }\r
583                 if (m_nApplicationID < 0)\r
584                         m_nApplicationID = GetAppID(_T("Default"), 0);\r
585         }\r
586         if (m_Config.nSettingStyle[m_nApplicationID] != SETTING_DISABLE &&\r
587                         (_tcsicmp(m_Config.szSpecialApp[m_nApplicationID], _T("Default")) || !CUtils::IsDefaultIgnoreApplication()) &&\r
588                         !bImeComposition && CUtils::IsDialog() && m_Config.bUseDialogSetting[m_nApplicationID])\r
589                 // Use Dialog Setting\r
590                 m_nApplicationID = GetAppID(_T("Dialog"), m_nApplicationID);\r
591 \r
592         ICONMSG msg[3] = {\r
593                 {CX_ICON, OFF_ICON, ""},\r
594                 {MX_ICON, OFF_ICON, ""},\r
595                 {META_ICON, OFF_ICON, ""}\r
596         };\r
597         SendIconMessage(msg, 3);\r
598         CCommands::SetMark(FALSE);\r
599         CCommands::SetTemporarilyDisableXKeymacs(FALSE);\r
600         CCommands::Reset();\r
601 }\r
602 \r
603 int CXkeymacsDll::GetAppID(const LPCSTR szName, const int fallback)\r
604 {\r
605         for (int i = 0; i < MAX_APP; i++)\r
606                 if (!_tcsicmp(m_Config.szSpecialApp[i], szName))\r
607                         return i;\r
608         return fallback;\r
609 }\r
610 \r
611 LRESULT CALLBACK CXkeymacsDll::KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)\r
612 {\r
613         ASSERT(0 <= wParam && wParam <= UCHAR_MAX);\r
614 \r
615         UINT nCommandType = NONE;\r
616         BYTE nOrigKey = (BYTE)wParam;\r
617 \r
618         static BOOL bLocked = FALSE;\r
619         static const BYTE RECURSIVE_KEY = 0x07;\r
620         static int (*fCommand)() = NULL;\r
621         static BYTE nOneShotModifier[MAX_KEY] = {'\0'};\r
622         static BOOL bCherryOneShotModifier = FALSE;\r
623 \r
624 //      CUtils::Log(_T("nCode = %#x, nKey = %#x, lParam = %p, %d, %d"), nOrigCode, nKey, lParam, IsDll64, Is64ProcessHwnd(GetForegroundWindow()));\r
625 \r
626         if (Is64ProcessHwnd(GetForegroundWindow()) != IsDll64 || CUtils::IsXkeymacs())\r
627                 return CallNextHookEx(g_hHookKeyboard, nCode, wParam, lParam);\r
628 \r
629         if (nCode < 0 || nCode == HC_NOREMOVE) {\r
630                 goto DO_NOTHING;\r
631         }\r
632 \r
633 //      CUtils::Log(_T("nKey = %#x, ext = %d, rel = %d, pre = %d, %#hx, %#hx"), nOrigKey,\r
634 //              (lParam & EXTENDED_KEY) ? 1 : 0, (lParam & BEING_RELEASED) ? 1 : 0, (lParam & REPEATED_KEY) ? 1 : 0,\r
635 //              GetKeyState(nOrigKey), GetAsyncKeyState(nOrigKey));\r
636 \r
637         if (nOrigKey == RECURSIVE_KEY) {\r
638                 if (lParam & BEING_RELEASED) {\r
639                         goto HOOK_RECURSIVE_KEY;\r
640                 } else {\r
641                         goto RECURSIVE_COMMAND;\r
642                 }\r
643         }\r
644 \r
645         {\r
646                 static BOOL bShift = FALSE;\r
647                 if (IsDepressedShiftKeyOnly(nOrigKey)) {\r
648                         if (lParam & BEING_RELEASED) {\r
649                                 if (bShift) {\r
650                                         CCommands::SetMark(FALSE);\r
651                                 }\r
652                         } else {\r
653                                 bShift = TRUE;\r
654                         }\r
655                 } else {\r
656                         bShift = FALSE;\r
657                 }\r
658         }\r
659 \r
660         BYTE nKey = nOrigKey;\r
661         switch (nKey) {\r
662         case VK_CONTROL:\r
663                 if (lParam & EXTENDED_KEY) {\r
664                         nKey = VK_RCONTROL;\r
665                 } else {\r
666                         nKey = VK_LCONTROL;\r
667                 }\r
668                 break;\r
669         case VK_MENU:\r
670                 if (lParam & EXTENDED_KEY) {\r
671                         nKey = VK_RMENU;\r
672                 } else {\r
673                         nKey = VK_LMENU;\r
674                 }\r
675                 break;\r
676         case VK_SHIFT:\r
677                 if (lParam & EXTENDED_KEY) {\r
678                         nKey = VK_RSHIFT;\r
679                 } else {\r
680                         nKey = VK_LSHIFT;\r
681                 }\r
682                 break;\r
683         default:\r
684                 break;\r
685         }\r
686 \r
687         if (lParam & BEING_RELEASED) {\r
688                 switch (nOrigKey) {\r
689                 case VK_MENU:\r
690                         if (m_nHookAltRelease) {\r
691                                 if (m_nHookAltRelease & ~HOOK_ALT_LATER)\r
692                                         m_nHookAltRelease--;\r
693                                 else if (m_nHookAltRelease & HOOK_ALT_LATER)\r
694                                         m_nHookAltRelease = 0;\r
695                                 goto HOOK;\r
696                         }\r
697                         // pass through\r
698                 case VK_LWIN:\r
699                 case VK_RWIN:\r
700                 case VK_APPS:\r
701                         for (int i = 0; i < MAX_COMMAND_TYPE; i++) {\r
702                                 int (*func)() = Commands[m_Config.nCommandID[m_nApplicationID][i][nKey]].fCommand;\r
703                                 if (func && !(nOrigKey == VK_MENU && func == CCommands::MetaAlt))\r
704                                         goto HOOK;\r
705                         }\r
706                 }\r
707                 if (nOneShotModifier[nKey]) {\r
708                         ReleaseKey(nOneShotModifier[nKey]);\r
709                         nOneShotModifier[nKey] = 0;\r
710 \r
711                         if (bCherryOneShotModifier) {\r
712                                 bCherryOneShotModifier = FALSE;\r
713                                 Kdu(nKey);\r
714                         }\r
715                 }\r
716                 goto DO_NOTHING;\r
717         }\r
718 \r
719         if (m_Config.nSettingStyle[m_nApplicationID] == SETTING_DISABLE) {\r
720                 goto DO_NOTHING;\r
721         }\r
722 \r
723         // Do Nothing for Meadow, Mule for Win32, ... if those use default setting.\r
724         if (!_tcsicmp(m_Config.szSpecialApp[m_nApplicationID], _T("Default"))\r
725          && CUtils::IsDefaultIgnoreApplication()) {\r
726                 goto DO_NOTHING;\r
727         }\r
728 \r
729         switch (IsPassThrough(nKey)) {\r
730         case GOTO_DO_NOTHING:\r
731                 goto DO_NOTHING;\r
732         case GOTO_HOOK:\r
733                 goto HOOK;\r
734         case CONTINUE:\r
735                 break;\r
736         default:\r
737                 ASSERT(0);\r
738                 break;\r
739         }\r
740 \r
741         // set command type\r
742         nCommandType = IsDown(VK_SHIFT) * SHIFT | IsControl() * CONTROL | IsMeta() * META | CCommands::bC_x() * CONTROLX;\r
743         // Ignore undefined C-x ?\r
744         if (nCommandType & CONTROLX) {\r
745                 if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == NULL\r
746                  && m_Config.nFunctionID[m_nApplicationID][nCommandType][nKey] < 0) {\r
747                         if (m_Config.bIgnoreUndefinedC_x[m_nApplicationID]) {\r
748                                 CCommands::Reset(GOTO_HOOK);\r
749                                 goto HOOK;\r
750                         }\r
751                         nCommandType &= ~CONTROLX;\r
752                 }\r
753         }\r
754         // Ignore undefined Meta Ctrl+?\r
755         if (CCommands::bM_() && (nCommandType & CONTROL)) {\r
756                 if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == NULL\r
757                  && m_Config.nFunctionID[m_nApplicationID][nCommandType][nKey] < 0) {\r
758                         if (m_Config.bIgnoreUndefinedMetaCtrl[m_nApplicationID]) {\r
759                                 if (CheckOriginal(CONTROL, nKey)) {\r
760                                         goto DO_NOTHING;\r
761                                 }\r
762                                 CCommands::Reset(GOTO_HOOK);\r
763                                 goto HOOK;\r
764                         }\r
765                         nCommandType &= ~META;\r
766                 }\r
767         }\r
768 \r
769         int nVirtualCommandType = GetModifierState(FALSE);\r
770         if (nOrigKey == VK_CONTROL)\r
771                 nVirtualCommandType &= ~CONTROL;\r
772         if (nOrigKey == VK_MENU)\r
773                 nVirtualCommandType &= ~META;\r
774         if (CheckOriginal(nVirtualCommandType, nOrigKey)) {\r
775                 goto DO_NOTHING;\r
776         }\r
777 \r
778         if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::EnableOrDisableXKeymacs) {\r
779                 ToggleKeyboardHookState();\r
780                 goto HOOK;\r
781         }\r
782         if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::EnableXKeymacs) {\r
783                 if (!m_bHook) {\r
784                         ToggleKeyboardHookState();\r
785                 }\r
786                 goto HOOK;\r
787         }\r
788         if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::DisableXKeymacs) {\r
789                 if (m_bHook) {\r
790                         ToggleKeyboardHookState();\r
791                 }\r
792                 goto HOOK;\r
793         }\r
794         if (!m_bHook) {\r
795                 goto DO_NOTHING;\r
796         }\r
797 \r
798         if (CCommands::bM_x()) {\r
799                 static unsigned int index = 0;\r
800                 static TCHAR szPath[MAX_PATH] = {'\0'};\r
801 \r
802                 if (lParam & BEING_RELEASED) {\r
803                         // ignore\r
804                 } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::BackwardChar) {\r
805                         if (index) {\r
806                                 --index;\r
807                         }\r
808                         goto HOOKX;\r
809                 } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::BeginningOfLine) {\r
810                         index = 0;\r
811                         goto HOOKX;\r
812                 } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::DeleteBackwardChar) {\r
813                         if (index) {\r
814                                 --index;\r
815                                 memmove(&szPath[index], &szPath[index + 1], _tcslen(szPath) - index);\r
816                                 SetM_xTip(szPath);\r
817                         }\r
818                         goto HOOKX;\r
819                 } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::DeleteChar) {\r
820                         if (index < _tcslen(szPath)) {\r
821                                 memmove(&szPath[index], &szPath[index + 1], _tcslen(szPath) - index);\r
822                                 SetM_xTip(szPath);\r
823                         }\r
824                         goto HOOKX;\r
825                 } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::EndOfLine) {\r
826                         index = _tcslen(szPath);\r
827                         goto HOOKX;\r
828                 } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::ForwardChar) {\r
829                         if (index < _tcslen(szPath)) {\r
830                                 ++index;\r
831                         }\r
832                         goto HOOKX;\r
833                 } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::KeyboardQuit) {\r
834                         CCommands::bM_x(FALSE);\r
835                         index = 0;\r
836                         memset(szPath, 0, sizeof(szPath));\r
837                         goto HOOK;\r
838                 } else if (nKey == VK_RETURN\r
839                                 || Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::Newline) {\r
840                         InvokeM_x(szPath);\r
841 \r
842                         CCommands::bM_x(FALSE);\r
843                         index = 0;\r
844                         memset(szPath, 0, sizeof(szPath));\r
845                         goto HOOK;\r
846                 } else if (index < MAX_PATH - 1) {\r
847                         const BOOL bIsShiftDown = IsDown(VK_SHIFT, FALSE);\r
848                         for (TCHAR nAscii = 1; nAscii != 0; ++nAscii) { // repeat until overflow\r
849                                 if (nKey != 0 && a2v(nAscii) == nKey && bIsShiftDown == IsShift(nAscii)) {\r
850 //                                      CUtils::Log("M-x: %#X (%c), %#X (%c)", nKey, nKey, nAscii, nAscii);\r
851                                         if (index < _tcslen(szPath)) {\r
852                                                 memmove(&szPath[index + 1], &szPath[index], __min(_tcslen(szPath) - index, MAX_PATH - (index + 1) - 1));\r
853                                         }\r
854                                         szPath[index++] = nAscii;\r
855 //                                      CUtils::Log("M-x: %c(%#04x)", nAscii, nAscii);\r
856                                         SetM_xTip(szPath);\r
857                                         goto HOOKX;\r
858                                 }\r
859                         }\r
860                 }\r
861         }\r
862 \r
863         if (CCommands::bC_u()) {\r
864                 if ((nCommandType == NONE) && ('0' <= nKey) && (nKey <= '9')) {\r
865                         CCommands::NumericArgument(nKey - '0');\r
866                         goto HOOK0_9;\r
867                 }\r
868                 if ((nCommandType == NONE) && (nKey == 0xBD)) {\r
869                         CCommands::NumericArgumentMinus();\r
870                         goto HOOK0_9;\r
871                 }\r
872         }\r
873 \r
874         if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType & ~CONTROL][nKey]].fCommand == CCommands::OneShotModifierCtrl) {\r
875                 nOneShotModifier[nKey] = VK_CONTROL;\r
876                 DepressKey(VK_CONTROL);\r
877                 bCherryOneShotModifier = TRUE;\r
878                 goto HOOK;\r
879         } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::OneShotModifierCtrlRepeat) {\r
880                 nOneShotModifier[nKey] = VK_CONTROL;\r
881                 DepressKey(VK_CONTROL);\r
882                 bCherryOneShotModifier = TRUE;\r
883                 goto HOOK;\r
884         } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType & ~CONTROL][nKey]].fCommand == CCommands::OneShotModifierCtrlRepeat) {\r
885                 ReleaseKey(VK_CONTROL);\r
886                 bCherryOneShotModifier = FALSE;\r
887                 Kdu(nKey);\r
888                 goto HOOK;\r
889         } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType & ~META][nKey]].fCommand == CCommands::OneShotModifierAlt) {\r
890                 nOneShotModifier[nKey] = VK_MENU;\r
891                 DepressKey(VK_MENU);\r
892                 bCherryOneShotModifier = TRUE;\r
893                 goto HOOK;\r
894         } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::OneShotModifierAltRepeat) {\r
895                 nOneShotModifier[nKey] = VK_MENU;\r
896                 DepressKey(VK_MENU);\r
897                 bCherryOneShotModifier = TRUE;\r
898                 goto HOOK;\r
899         } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType & ~META][nKey]].fCommand == CCommands::OneShotModifierAltRepeat) {\r
900                 ReleaseKey(VK_MENU);\r
901                 bCherryOneShotModifier = FALSE;\r
902                 Kdu(nKey);\r
903                 goto HOOK;\r
904         } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType & ~SHIFT][nKey]].fCommand == CCommands::OneShotModifierShift) {\r
905                 nOneShotModifier[nKey] = VK_SHIFT;\r
906                 DepressKey(VK_SHIFT);\r
907                 bCherryOneShotModifier = TRUE;\r
908                 goto HOOK;\r
909         } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand == CCommands::OneShotModifierShiftRepeat) {\r
910                 nOneShotModifier[nKey] = VK_SHIFT;\r
911                 DepressKey(VK_SHIFT);\r
912                 bCherryOneShotModifier = TRUE;\r
913                 goto HOOK;\r
914         } else if (Commands[m_Config.nCommandID[m_nApplicationID][nCommandType & ~SHIFT][nKey]].fCommand == CCommands::OneShotModifierShiftRepeat) {\r
915                 ReleaseKey(VK_SHIFT);\r
916                 bCherryOneShotModifier = FALSE;\r
917                 Kdu(nKey);\r
918                 goto HOOK;\r
919         } else {\r
920                 int i;\r
921                 for (i = 0; i < MAX_KEY; ++i) {\r
922                         if (nOneShotModifier[i] == nKey) {\r
923                                 break;\r
924                         }\r
925                 }\r
926                 if (i == MAX_KEY) {\r
927                         bCherryOneShotModifier = FALSE;\r
928                 }\r
929         }\r
930 \r
931         if (0 <= m_Config.nFunctionID[m_nApplicationID][nCommandType][nKey]\r
932          && m_Config.nFunctionID[m_nApplicationID][nCommandType][nKey] < MAX_FUNCTION\r
933          && _tcslen(m_Config.szFunctionDefinition[m_Config.nFunctionID[m_nApplicationID][nCommandType][nKey]])) {\r
934                 CallFunction(m_Config.nFunctionID[m_nApplicationID][nCommandType][nKey]);\r
935                 CCommands::Reset(GOTO_HOOK);\r
936                 goto HOOK;\r
937         }\r
938 \r
939         if (!Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand) {\r
940                 if (nOrigKey == VK_CONTROL || nOrigKey == VK_MENU || nOrigKey == VK_SHIFT) {\r
941                         goto DO_NOTHING;\r
942                 }\r
943 \r
944                 if (!(nCommandType & SHIFT)) {\r
945                         if (CCommands::IsSetMark()) {\r
946                                 if (CCommands::MoveCaret(nKey, nCommandType & CONTROL) != CONTINUE) {\r
947                                         CCommands::ClearNumericArgument();\r
948                                         goto HOOK;\r
949                                 }\r
950                                 CCommands::SetMark(FALSE);\r
951                         }\r
952                 }\r
953 \r
954                 if (1 < CCommands::GetNumericArgument()) {\r
955                         Kdu(nKey, CCommands::GetNumericArgument());\r
956                         CCommands::ClearNumericArgument();\r
957                         goto HOOK;\r
958                 }\r
959 \r
960                 goto DO_NOTHING;\r
961         }\r
962 \r
963         if (CCommands::IsTemporarilyDisableXKeymacs()\r
964          && Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand != CCommands::KeyboardQuit) {\r
965                 CCommands::SetTemporarilyDisableXKeymacs(FALSE);\r
966                 goto DO_NOTHING;\r
967         }\r
968 \r
969         m_bRightControl = IsDown(VK_RCONTROL, FALSE);\r
970         m_bRightAlt = IsDown(VK_RMENU, FALSE);\r
971         m_bRightShift = IsDown(VK_RSHIFT, FALSE);\r
972 \r
973         if (!bLocked) {\r
974                 bLocked = TRUE;\r
975                 fCommand = Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][nKey]].fCommand;\r
976 RECURSIVE_COMMAND:\r
977                 switch (fCommand()) {\r
978                 case GOTO_DO_NOTHING:\r
979                         bLocked = FALSE;\r
980                         goto DO_NOTHING;\r
981                 case GOTO_HOOK:\r
982                         bLocked = FALSE;\r
983                         goto HOOK;\r
984                 case GOTO_RECURSIVE:\r
985                         goto RECURSIVE;\r
986                 case GOTO_HOOKX:\r
987                         bLocked = FALSE;\r
988                         goto HOOKX;\r
989                 case GOTO_HOOK0_9:\r
990                         bLocked = FALSE;\r
991                         goto HOOK0_9;\r
992                 default:\r
993                         ASSERT(0);\r
994                         bLocked = FALSE;\r
995                         goto DO_NOTHING;\r
996                 }\r
997         } else {\r
998                 goto HOOK_RECURSIVE_KEY;\r
999         }\r
1000 \r
1001 DO_NOTHING:\r
1002         SetModifierIcons();\r
1003         if (m_bRecordingMacro && (!(lParam & BEING_RELEASED) || m_bDown[wParam])) {\r
1004                 KbdMacro m = { nCode, wParam, lParam, TRUE };\r
1005                 m_Macro.push_back(m);\r
1006                 m_bDown[wParam] |= !(lParam & BEING_RELEASED);\r
1007         }\r
1008         return CallNextHookEx(g_hHookKeyboard, nCode, wParam, lParam);\r
1009 \r
1010 RECURSIVE:\r
1011         Kdu(RECURSIVE_KEY, 1, FALSE);\r
1012         goto HOOKX;\r
1013 HOOK:\r
1014         CCommands::SetLastCommand(fCommand);\r
1015 HOOK0_9:\r
1016 HOOKX:\r
1017         SetModifierIcons();\r
1018 HOOK_RECURSIVE_KEY:\r
1019         return TRUE;\r
1020 }\r
1021 \r
1022 void CXkeymacsDll::SetModifierIcons()\r
1023 {\r
1024 #define IconState(x) ((x) ? ON_ICON : OFF_ICON)\r
1025         ICONMSG msg[6] = {\r
1026                 {MX_ICON, IconState(CCommands::bM_x()), ""},\r
1027                 {CX_ICON, IconState(CCommands::bC_x()), ""},\r
1028                 {META_ICON, IconState(CCommands::bM_()), ""},\r
1029                 {SHIFT_ICON, IconState(IsDown(VK_SHIFT, FALSE)), ""},\r
1030                 {CTRL_ICON, IconState(IsControl()), ""},\r
1031                 {ALT_ICON, IconState(IsDown(VK_MENU, FALSE)), ""}\r
1032         };\r
1033         _tcscpy_s(msg[0].szTip, m_M_xTip);\r
1034         SendIconMessage(msg, 6);\r
1035 }\r
1036 \r
1037 void CXkeymacsDll::SetApplicationName(int nApplicationID, CString szApplicationName)\r
1038 {\r
1039         ZeroMemory(m_Config.szSpecialApp[nApplicationID], CLASS_NAME_LENGTH);\r
1040         _tcsncpy_s(m_Config.szSpecialApp[nApplicationID], szApplicationName, _TRUNCATE);\r
1041 }\r
1042 \r
1043 void CXkeymacsDll::SetWindowText(int nApplicationID, CString szWindowText)\r
1044 {\r
1045         ZeroMemory(m_Config.szWindowText[nApplicationID], WINDOW_TEXT_LENGTH);\r
1046         _tcsncpy_s(m_Config.szWindowText[nApplicationID], szWindowText, _TRUNCATE);\r
1047 }\r
1048 \r
1049 void CXkeymacsDll::SetCommandID(int nApplicationID, int nCommandType, int nKey, int nCommandID)\r
1050 {\r
1051         m_Config.nCommandID[nApplicationID][nCommandType][nKey] = nCommandID;\r
1052 }\r
1053 \r
1054 void CXkeymacsDll::SetKillRingMax(int nApplicationID, int nKillRingMax)\r
1055 {\r
1056         m_Config.nKillRingMax[nApplicationID] = nKillRingMax;\r
1057 }\r
1058 \r
1059 void CXkeymacsDll::SetUseDialogSetting(int nApplicationID, BOOL bUseDialogSetting)\r
1060 {\r
1061         m_Config.bUseDialogSetting[nApplicationID] = bUseDialogSetting;\r
1062 }\r
1063 \r
1064 // Clear data of nApplicationID\r
1065 void CXkeymacsDll::Clear(int nApplicationID)\r
1066 {\r
1067         if (0 <= nApplicationID && nApplicationID < MAX_APP) {\r
1068                 ZeroMemory(m_Config.szSpecialApp[nApplicationID], sizeof(m_Config.szSpecialApp[nApplicationID]));\r
1069                 ZeroMemory(m_Config.nCommandID[nApplicationID], sizeof(m_Config.nCommandID[nApplicationID]));\r
1070                 m_Config.nKillRingMax[nApplicationID] = 0;\r
1071                 m_Config.bUseDialogSetting[nApplicationID] = FALSE;\r
1072                 m_Config.nSettingStyle[nApplicationID] = 0;\r
1073         } else {\r
1074                 ASSERT(0);\r
1075         }\r
1076 }\r
1077 \r
1078 BOOL CXkeymacsDll::IsValidKey(BYTE bVk)\r
1079 {\r
1080         if (bVk == 0xf0) {      // 0xf0: Eisu key. GetAsyncKeyState returns the wrong state of Eisu key.\r
1081                 return FALSE;\r
1082         }\r
1083 \r
1084         switch (bVk) {\r
1085         case VK_CONTROL:\r
1086         case VK_MENU:\r
1087         case VK_SHIFT:\r
1088                 return FALSE;\r
1089         default:\r
1090                 break;\r
1091         }\r
1092 \r
1093         return TRUE;\r
1094 }\r
1095 \r
1096 BOOL CXkeymacsDll::IsDepressedModifier(int (__cdecl *Modifier)(void), BOOL bPhysicalKey)\r
1097 {\r
1098         BYTE bVk = 0;\r
1099         do {\r
1100                 if (IsValidKey(bVk) && IsDown(bVk, bPhysicalKey) &&\r
1101                                 Commands[m_Config.nCommandID[m_nApplicationID][NONE][bVk]].fCommand == Modifier)\r
1102                         return TRUE;\r
1103         } while (++bVk);\r
1104         return FALSE;\r
1105 }\r
1106 \r
1107 BOOL CXkeymacsDll::IsDepressedShiftKeyOnly(BYTE nKey)\r
1108 {\r
1109         if (nKey != VK_SHIFT\r
1110          && nKey != VK_LSHIFT\r
1111          && nKey != VK_RSHIFT) {\r
1112                 return FALSE;\r
1113         }\r
1114 \r
1115         BYTE bVk = 0;\r
1116         do {\r
1117                 if (bVk == VK_SHIFT\r
1118                  || bVk == VK_LSHIFT\r
1119                  || bVk == VK_RSHIFT) {\r
1120                         continue;\r
1121                 }\r
1122 \r
1123                 if (IsDown(bVk, FALSE)) {\r
1124                         return FALSE;\r
1125                 }\r
1126         } while (++bVk);\r
1127         return TRUE;\r
1128 }\r
1129 \r
1130 BOOL CXkeymacsDll::IsControl()\r
1131 {\r
1132         return CCommands::bC_() || IsDepressedModifier(CCommands::C_);\r
1133 }\r
1134 \r
1135 BOOL CXkeymacsDll::IsMeta()\r
1136 {\r
1137         return CCommands::bM_() || IsDepressedModifier(CCommands::MetaAlt);\r
1138 }\r
1139 \r
1140 void CXkeymacsDll::AddKillRing(BOOL bNewData)\r
1141 {\r
1142         if (m_Config.nKillRingMax[m_nApplicationID] == 0) {\r
1143                 return;\r
1144         }\r
1145 \r
1146         CClipboardSnap *pSnap = new CClipboardSnap;\r
1147         if( !pSnap ) return;\r
1148 \r
1149         BOOL bCapture = pSnap->Capture();\r
1150         bCapture = pSnap->Capture();    // for "office drawing shape format". Can CClipboardSnap care this problem?\r
1151 \r
1152         if( bCapture ) {\r
1153                 if (bNewData) {\r
1154                         m_oKillRing.AddHead(pSnap);\r
1155                 } else {\r
1156                         if (m_oKillRing.IsEmpty()) {\r
1157                                 m_oKillRing.AddHead(pSnap);\r
1158                         } else {\r
1159                                 CClipboardSnap *pParent;\r
1160                                 for (pParent = m_oKillRing.GetHead(); pParent->GetNext(); pParent = pParent->GetNext()) {\r
1161                                         ;\r
1162                                 }\r
1163                                 pParent->SetNext(pSnap);\r
1164                         }\r
1165                 }\r
1166         } else {\r
1167                 delete pSnap;\r
1168                 pSnap = NULL;\r
1169         }\r
1170 \r
1171         m_nKillRing = 0;\r
1172 \r
1173         if (m_Config.nKillRingMax[m_nApplicationID] < m_oKillRing.GetCount()) {\r
1174                 CClipboardSnap *pSnap = m_oKillRing.GetTail();\r
1175                 delete pSnap;\r
1176                 pSnap = NULL;\r
1177                 m_oKillRing.RemoveTail();\r
1178         }\r
1179 }\r
1180 \r
1181 // Return TRUE if there is another data\r
1182 // Return FALSE if there is no more data\r
1183 CClipboardSnap* CXkeymacsDll::GetKillRing(CClipboardSnap* pSnap, BOOL bForce)\r
1184 {\r
1185         if (m_Config.nKillRingMax[m_nApplicationID] == 0) {\r
1186                 return NULL;\r
1187         }\r
1188 \r
1189         if (m_oKillRing.IsEmpty()) {\r
1190                 return NULL;\r
1191         }\r
1192 \r
1193         m_nKillRing %= m_oKillRing.GetCount();\r
1194 \r
1195         if (!bForce) {\r
1196                 CClipboardSnap oCurrentSnap;\r
1197                 oCurrentSnap.Capture();\r
1198 \r
1199                 CClipboardSnap *pKillRing = m_oKillRing.GetAt(m_oKillRing.FindIndex(m_nKillRing));\r
1200                 if (!pKillRing) {\r
1201                         return NULL;\r
1202                 }\r
1203                 for (; pKillRing->GetNext(); pKillRing = pKillRing->GetNext()) {\r
1204                         ;\r
1205                 }\r
1206                 if (*pKillRing != oCurrentSnap) {\r
1207                         return NULL;\r
1208                 }\r
1209         }\r
1210 \r
1211         if (!pSnap) {\r
1212                 pSnap = m_oKillRing.GetAt(m_oKillRing.FindIndex(m_nKillRing));\r
1213         }\r
1214         pSnap->Restore();\r
1215 \r
1216         return pSnap->GetNext();\r
1217 }\r
1218 \r
1219 void CXkeymacsDll::SetOriginal(UINT nCommandType, BYTE bVk)\r
1220 {\r
1221         m_nOriginal[nCommandType & ~SHIFT][bVk]++;\r
1222 }\r
1223 \r
1224 int CXkeymacsDll::CheckOriginal(UINT nCommandType, BYTE bVk)\r
1225 {\r
1226         nCommandType &= ~SHIFT;\r
1227         if (m_nOriginal[nCommandType][bVk])\r
1228                 return m_nOriginal[nCommandType][bVk]--;\r
1229         return 0;\r
1230 }\r
1231 \r
1232 void CXkeymacsDll::IncreaseKillRingIndex(int nKillRing)\r
1233 {\r
1234         m_nKillRing += nKillRing;\r
1235 }\r
1236 \r
1237 void CXkeymacsDll::SetSettingStyle(int nApplicationID, int nSettingStyle)\r
1238 {\r
1239         m_Config.nSettingStyle[nApplicationID] = nSettingStyle;\r
1240 }\r
1241 \r
1242 void CXkeymacsDll::SetIgnoreUndefinedMetaCtrl(int nApplicationID, BOOL bIgnoreUndefinedMetaCtrl)\r
1243 {\r
1244         m_Config.bIgnoreUndefinedMetaCtrl[nApplicationID] = bIgnoreUndefinedMetaCtrl;\r
1245 }\r
1246 \r
1247 void CXkeymacsDll::SetIgnoreUndefinedC_x(int nApplicationID, BOOL bIgnoreUndefinedC_x)\r
1248 {\r
1249         m_Config.bIgnoreUndefinedC_x[nApplicationID] = bIgnoreUndefinedC_x;\r
1250 }\r
1251 \r
1252 void CXkeymacsDll::SetEnableCUA(int nApplicationID, BOOL bEnableCUA)\r
1253 {\r
1254         m_Config.bEnableCUA[nApplicationID] = bEnableCUA;\r
1255 }\r
1256 \r
1257 BOOL CXkeymacsDll::GetEnableCUA()\r
1258 {\r
1259         return m_Config.bEnableCUA[m_nApplicationID];\r
1260 }\r
1261 \r
1262 void CXkeymacsDll::StartRecordMacro()\r
1263 {\r
1264         if (CCommands::bC_u())\r
1265                 CallMacro();\r
1266         m_bRecordingMacro = TRUE;\r
1267         m_Macro.erase(m_Macro.begin(), m_Macro.end());\r
1268         ZeroMemory(m_bDown, MAX_KEY);\r
1269 }\r
1270 \r
1271 void CXkeymacsDll::EndRecordMacro()\r
1272 {\r
1273         m_bRecordingMacro = FALSE;\r
1274         while (!m_Macro.empty()) { // remove not released push\r
1275                 const KbdMacro& m = m_Macro.back();\r
1276                 if (m.lParam & BEING_RELEASED)\r
1277                         break;\r
1278                 m_Macro.pop_back();\r
1279         }\r
1280 }\r
1281 \r
1282 void CXkeymacsDll::CallMacro()\r
1283 {\r
1284         if (m_bRecordingMacro)\r
1285                 m_bRecordingMacro = FALSE;\r
1286         UINT before = GetModifierState(FALSE);\r
1287         SetModifierState(0, before);\r
1288         for (auto m = m_Macro.begin(); m != m_Macro.end(); m++)\r
1289                 if (m->lParam & BEING_RELEASED)\r
1290                         ReleaseKey(static_cast<BYTE>(m->wParam));\r
1291                 else\r
1292                         DepressKey(static_cast<BYTE>(m->wParam), m->bOriginal);\r
1293         SetModifierState(before, 0);\r
1294 }\r
1295 \r
1296 void CXkeymacsDll::Set106Keyboard(BOOL b106Keyboard)\r
1297 {\r
1298         m_Config.b106Keyboard = b106Keyboard;\r
1299 }\r
1300 \r
1301 BOOL CXkeymacsDll::Is106Keyboard()\r
1302 {\r
1303         return m_Config.b106Keyboard;\r
1304 }\r
1305 \r
1306 int CXkeymacsDll::IsPassThrough(BYTE nKey)\r
1307 {\r
1308         BYTE bVk = 0;\r
1309         do {\r
1310                 if (IsDown(bVk)\r
1311                  && (Commands[m_Config.nCommandID[m_nApplicationID][NONE][bVk]].fCommand == CCommands::PassThrough)) {\r
1312                         if (bVk == nKey) {\r
1313                                 return GOTO_HOOK;\r
1314                         }\r
1315 \r
1316                         return GOTO_DO_NOTHING;\r
1317                 }\r
1318         } while (++bVk);\r
1319         return CONTINUE;\r
1320 }\r
1321 \r
1322 void CXkeymacsDll::SetFunctionKey(int nFunctionID, int nApplicationID, int nCommandType, int nKey)\r
1323 {\r
1324         if (nApplicationID      < 0 || MAX_APP                  <= nApplicationID\r
1325          || nCommandType        < 0 || MAX_COMMAND_TYPE <= nCommandType\r
1326          || nKey                        < 0 || MAX_KEY                  <= nKey) {\r
1327                 return;\r
1328         }\r
1329 \r
1330         m_Config.nFunctionID[nApplicationID][nCommandType][nKey] = nFunctionID;\r
1331 }\r
1332 \r
1333 void CXkeymacsDll::ClearFunctionDefinition()\r
1334 {\r
1335         memset(m_Config.nFunctionID, -1, sizeof(m_Config.nFunctionID));\r
1336         memset(m_Config.szFunctionDefinition, 0, sizeof(m_Config.szFunctionDefinition));\r
1337 }\r
1338 \r
1339 void CXkeymacsDll::SetFunctionDefinition(int nFunctionID, CString szDefinition)\r
1340 {\r
1341         if (nFunctionID < 0 || nFunctionID >= MAX_FUNCTION)\r
1342                 return;\r
1343         memset(m_Config.szFunctionDefinition[nFunctionID], 0, sizeof(m_Config.szFunctionDefinition[nFunctionID]));\r
1344         _tcscpy_s(m_Config.szFunctionDefinition[nFunctionID], szDefinition);\r
1345         return;\r
1346 }\r
1347 \r
1348 // call an original command which is defined in dot.xkeymacs\r
1349 void CXkeymacsDll::CallFunction(int nFunctionID)\r
1350 {\r
1351         if (nFunctionID < 0 || nFunctionID >= MAX_FUNCTION)\r
1352                 return;\r
1353         LPCTSTR def = m_Config.szFunctionDefinition[nFunctionID];\r
1354         if (!def[0])\r
1355                 return;\r
1356         std::vector<KeyBind> keybinds;\r
1357         const LPCTSTR last = def + _tcslen(def) - 1;\r
1358         if (*def == _T('"') && *last == _T('"')) {\r
1359                 def++; // skip '"'\r
1360                 while (def < last)\r
1361                         keybinds.push_back(ParseKey(def));\r
1362         } else if (*def == _T('[') && *last == _T(']')) {\r
1363                 while (++def < last) { // skip '[', ']', and ' '\r
1364                         if (*def == _T('?')) { // [?f ?o ?o]\r
1365                                 keybinds.push_back(ParseKey(++def));\r
1366                                 continue;\r
1367                         }\r
1368                         // [VK]\r
1369                         for (int i = 0; i < MAX_KEYNAME; i++) {\r
1370                                 size_t keylen = _tcslen(KeyNames[i].name);\r
1371                                 if (!_tcsncmp(def, KeyNames[i].name, keylen)) {\r
1372                                         KeyBind keybind = {NONE, KeyNames[i].bVk};\r
1373                                         keybinds.push_back(keybind);\r
1374                                         def += keylen;\r
1375                                         break;\r
1376                                 }\r
1377                         }\r
1378                 }\r
1379         } else\r
1380                 return;\r
1381 \r
1382         BOOL bM_x = FALSE;\r
1383         TCHAR szPath[MAX_PATH] = {'\0'};\r
1384         unsigned int index = 0;\r
1385         BOOL bInitialized = FALSE;\r
1386         UINT before = GetModifierState(FALSE);\r
1387 \r
1388         for (auto p = keybinds.begin(); p != keybinds.end(); p++) {\r
1389                 const int nCommandType = p->nCommandType;\r
1390                 const BYTE bVk = p->bVk;\r
1391                 int (*fCommand)() = nCommandType < MAX_COMMAND_TYPE ? Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][bVk]].fCommand : NULL;\r
1392                 if (fCommand) {\r
1393                         if (fCommand == CCommands::ExecuteExtendedCommand)\r
1394                                 bM_x = TRUE;\r
1395                         else if (!bInitialized) {\r
1396                                 SetModifierState(0, before);\r
1397                                 bInitialized = TRUE;\r
1398                         }\r
1399 //                      CUtils::Log("CallFunction: Command Name: %s", Commands[m_Config.nCommandID[m_nApplicationID][nCommandType][bVk]].szCommandName);\r
1400                         while (fCommand() == GOTO_RECURSIVE)\r
1401                                 ;\r
1402                         continue;\r
1403                 }\r
1404                 if (bM_x) {\r
1405                         if (bVk == VK_RETURN)\r
1406                                 InvokeM_x(szPath);\r
1407                         else if (bVk != 0) {\r
1408                                 TCHAR nAscii = 0;\r
1409                                 do { // 1-127\r
1410                                         if (a2v(++nAscii) == bVk && ((nCommandType & SHIFT) != 0) == IsShift(nAscii)) {\r
1411 //                                              CUtils::Log("M-x: %#X (%c), %#X (%c)", bVk, bVk, nAscii, nAscii);\r
1412                                                 szPath[index++] = nAscii;\r
1413                                                 break;\r
1414                                         }\r
1415                                 } while (nAscii != 127);\r
1416                         }\r
1417                         continue;\r
1418                 }\r
1419                 if (!bInitialized) {\r
1420                         SetModifierState(0, before);\r
1421                         bInitialized = TRUE;\r
1422                 }\r
1423                 if (nCommandType & WIN_WIN)\r
1424                         DepressKey(VK_LWIN);\r
1425                 if (nCommandType & WIN_CTRL)\r
1426                         DepressKey(VK_CONTROL);\r
1427                 if (nCommandType & WIN_ALT)\r
1428                         DepressKey(VK_MENU);\r
1429                 if (nCommandType & SHIFT)\r
1430                         DepressKey(VK_SHIFT);\r
1431                 Kdu(bVk);\r
1432                 const int nNextType = (p + 1) != keybinds.end() ? (p + 1)->nCommandType : 0;\r
1433                 if (nCommandType & SHIFT && !(nNextType & SHIFT))\r
1434                         ReleaseKey(VK_SHIFT);\r
1435                 if (nCommandType & WIN_ALT && !(nNextType & WIN_ALT))\r
1436                         ReleaseKey(VK_MENU);\r
1437                 if (nCommandType & WIN_CTRL && !(nNextType & WIN_CTRL))\r
1438                         ReleaseKey(VK_CONTROL);\r
1439                 if (nCommandType & WIN_WIN && !(nNextType & WIN_WIN))\r
1440                         ReleaseKey(VK_LWIN);\r
1441         }\r
1442 \r
1443         if (bInitialized)\r
1444                 // If this lines is invoked on M-x, a window transition does not work well.\r
1445                 SetModifierState(before, 0);\r
1446         return;\r
1447 }\r
1448 \r
1449 KeyBind CXkeymacsDll::ParseKey(LPCTSTR& def)\r
1450 {\r
1451         KeyBind keybind = {NONE};\r
1452         if (*def == _T('\\')) { // set modifiers\r
1453                 def++;\r
1454         LOOP:\r
1455                 for (int i = 0; i < MAX_MODIFIER; i++) {\r
1456                         size_t len = _tcslen(Modifiers[i].name);\r
1457                         if (!_tcsncmp(def, Modifiers[i].name, len)) {\r
1458                                 keybind.nCommandType |= Modifiers[i].id;\r
1459                                 def += len;\r
1460                                 goto LOOP;\r
1461                         }\r
1462                 }\r
1463         }\r
1464         if (IsShift(*def) && !(keybind.nCommandType & (WIN_CTRL | WIN_ALT | WIN_WIN)))\r
1465                 keybind.nCommandType |= SHIFT;\r
1466         int i = 0;\r
1467         for (; i < MAX_KEYNAME; i++) {\r
1468                 size_t len = _tcslen(KeyNames[i].name);\r
1469                 if (!_tcsncmp(def, KeyNames[i].name, len)) {\r
1470                         def += len;\r
1471                         break;\r
1472                 }\r
1473         }\r
1474         keybind.bVk = i < MAX_KEYNAME ? KeyNames[i].bVk : a2v(*def++);\r
1475         return keybind;\r
1476 }\r
1477 \r
1478 BOOL CXkeymacsDll::IsShift(TCHAR nAscii)\r
1479 {\r
1480         switch (nAscii) {\r
1481         case _T(' '):\r
1482                 return FALSE;\r
1483         case _T('!'):\r
1484         case _T('"'):\r
1485         case _T('#'):\r
1486         case _T('$'):\r
1487         case _T('%'):\r
1488         case _T('&'):\r
1489                 return TRUE;\r
1490         case _T('\''):\r
1491                 return m_Config.b106Keyboard;\r
1492         case _T('('):\r
1493         case _T(')'):\r
1494         case _T('*'):\r
1495         case _T('+'):\r
1496                 return TRUE;\r
1497         case _T(','):\r
1498         case _T('-'):\r
1499         case _T('.'):\r
1500         case _T('/'):\r
1501         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'):\r
1502                 return FALSE;\r
1503         case _T(':'):\r
1504                 return !m_Config.b106Keyboard;\r
1505         case _T(';'):\r
1506                 return FALSE;\r
1507         case _T('<'):\r
1508                 return TRUE;\r
1509         case _T('='):\r
1510                 return m_Config.b106Keyboard;\r
1511         case _T('>'):\r
1512         case _T('?'):\r
1513                 return TRUE;\r
1514         case _T('@'):\r
1515                 return !m_Config.b106Keyboard;\r
1516         case _T('A'): case _T('B'): case _T('C'): case _T('D'): case _T('E'): case _T('F'): case _T('G'): case _T('H'): case _T('I'): case _T('J'): \r
1517         case _T('K'): case _T('L'): case _T('M'): case _T('N'): case _T('O'): case _T('P'): case _T('Q'): case _T('R'): case _T('S'): case _T('T'): \r
1518         case _T('U'): case _T('V'): case _T('W'): case _T('X'): case _T('Y'): case _T('Z'): \r
1519                 return TRUE;\r
1520         case _T('['):\r
1521         case _T('\\'):\r
1522         case _T(']'):\r
1523                 return FALSE;\r
1524         case _T('^'):\r
1525                 return !m_Config.b106Keyboard;\r
1526         case _T('_'):\r
1527                 return TRUE;\r
1528         case _T('`'):\r
1529                 return m_Config.b106Keyboard;\r
1530         case _T('a'): case _T('b'): case _T('c'): case _T('d'): case _T('e'): case _T('f'): case _T('g'): case _T('h'): case _T('i'): case _T('j'): \r
1531         case _T('k'): case _T('l'): case _T('m'): case _T('n'): case _T('o'): case _T('p'): case _T('q'): case _T('r'): case _T('s'): case _T('t'): \r
1532         case _T('u'): case _T('v'): case _T('w'): case _T('x'): case _T('y'): case _T('z'): \r
1533                 return FALSE;\r
1534         case _T('{'):\r
1535         case _T('|'):\r
1536         case _T('}'):\r
1537         case _T('~'):\r
1538                 return TRUE;\r
1539         default:\r
1540                 return FALSE;\r
1541         }\r
1542 }\r
1543 \r
1544 BYTE CXkeymacsDll::a2v(TCHAR nAscii)\r
1545 {\r
1546         switch (nAscii) {\r
1547         case _T(' '):\r
1548                 return VK_SPACE;\r
1549         case _T('!'):\r
1550                 return '1';\r
1551         case _T('"'):\r
1552                 return m_Config.b106Keyboard ? '2' : (BYTE) 0xde;       // VK_OEM_7\r
1553         case _T('#'):\r
1554                 return '3';\r
1555         case _T('$'):\r
1556                 return '4';\r
1557         case _T('%'):\r
1558                 return '5';\r
1559         case _T('&'):\r
1560                 return m_Config.b106Keyboard ? '6' : '7';\r
1561         case _T('\''):\r
1562                 return m_Config.b106Keyboard ? '7' : (BYTE) 0xde;       // VK_OEM_7\r
1563         case _T('('):\r
1564                 return m_Config.b106Keyboard ? '8' : '9';\r
1565         case _T(')'):\r
1566                 return m_Config.b106Keyboard ? '9' : '0';\r
1567         case _T('*'):\r
1568                 return m_Config.b106Keyboard ? (BYTE) 0xba : '8';       // VK_OEM_1\r
1569         case _T('+'):\r
1570                 return 0xbb;    // VK_OEM_PLUS\r
1571         case _T(','):\r
1572                 return 0xbc;    // VK_OEM_COMMA\r
1573         case _T('-'):\r
1574                 return 0xbd;    // VK_OEM_MINUS\r
1575         case _T('.'):\r
1576                 return 0xbe;    // VK_OEM_PERIOD\r
1577         case _T('/'):\r
1578                 return 0xbf;    // VK_OEM_2\r
1579         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'):\r
1580                 return nAscii;\r
1581         case _T(':'):\r
1582                 return 0xba;    // VK_OEM_1\r
1583         case _T(';'):\r
1584                 return m_Config.b106Keyboard ? (BYTE) 0xbb : (BYTE) 0xba;       // VK_OEM_PLUS  VK_OEM_1\r
1585         case _T('<'):\r
1586                 return 0xbc;    // VK_OEM_COMMA\r
1587         case _T('='):\r
1588                 return m_Config.b106Keyboard ? (BYTE) 0xbd : (BYTE) 0xbb;       // VK_OEM_MINUS VK_OEM_PLUS\r
1589         case _T('>'):\r
1590                 return 0xbe;    // VK_OEM_PERIOD\r
1591         case _T('?'):\r
1592                 return 0xbf;    // VK_OEM_2\r
1593         case _T('@'):\r
1594                 return m_Config.b106Keyboard ? (BYTE) 0xc0 : '2';\r
1595         case _T('A'): case _T('B'): case _T('C'): case _T('D'): case _T('E'): case _T('F'): case _T('G'): case _T('H'): case _T('I'): case _T('J'): \r
1596         case _T('K'): case _T('L'): case _T('M'): case _T('N'): case _T('O'): case _T('P'): case _T('Q'): case _T('R'): case _T('S'): case _T('T'): \r
1597         case _T('U'): case _T('V'): case _T('W'): case _T('X'): case _T('Y'): case _T('Z'): \r
1598                 return nAscii;\r
1599         case _T('['):\r
1600                 return 0xdb;    // VK_OEM_4\r
1601         case _T('\\'):\r
1602                 return 0xdc;    // VK_OEM_5\r
1603         case _T(']'):\r
1604                 return 0xdd;    // VK_OEM_6\r
1605         case _T('^'):\r
1606                 return m_Config.b106Keyboard ? (BYTE) 0xde : '6';       // VK_OEM_7\r
1607         case _T('_'):\r
1608                 return m_Config.b106Keyboard ? (BYTE) 0xe2 : (BYTE) 0xbd;       // VK_OEM_102   VK_OEM_MINUS\r
1609         case _T('`'):\r
1610                 return 0xc0;    // VK_OEM_3\r
1611         case _T('a'): case _T('b'): case _T('c'): case _T('d'): case _T('e'): case _T('f'): case _T('g'): case _T('h'): case _T('i'): case _T('j'): \r
1612         case _T('k'): case _T('l'): case _T('m'): case _T('n'): case _T('o'): case _T('p'): case _T('q'): case _T('r'): case _T('s'): case _T('t'): \r
1613         case _T('u'): case _T('v'): case _T('w'): case _T('x'): case _T('y'): case _T('z'): \r
1614                 return (BYTE) (nAscii - (_T('a') - _T('A')));\r
1615         case _T('{'):\r
1616                 return 0xdb;    // VK_OEM_4\r
1617         case _T('|'):\r
1618                 return 0xdc;    // VK_OEM_5\r
1619         case _T('}'):\r
1620                 return 0xdd;    // VK_OEM_6\r
1621         case _T('~'):\r
1622                 return m_Config.b106Keyboard ? (BYTE) 0xde : (BYTE) 0xc0;       // VK_OEM_7     VK_OEM_3\r
1623         default:\r
1624                 return 0;\r
1625         }\r
1626 }\r
1627 \r
1628 BOOL CXkeymacsDll::IsMatchWindowText(CString szWindowText)\r
1629 {\r
1630         BOOL bIsMatchWindowText = TRUE;\r
1631 \r
1632         TCHAR szCurrentWindowText[WINDOW_TEXT_LENGTH] = {'\0'};\r
1633         GetWindowText(GetForegroundWindow(), szCurrentWindowText, sizeof(szCurrentWindowText));\r
1634 \r
1635         switch (CUtils::GetWindowTextType(szWindowText)) {\r
1636         case IDS_WINDOW_TEXT_MATCH:                                                             // *foo*\r
1637                 szWindowText.Delete(0);                                                         // Delete first '*'\r
1638                 szWindowText.Delete(szWindowText.GetLength() - 1);      // Delete last '*'\r
1639                 bIsMatchWindowText = 0 <= CString(szCurrentWindowText).Find(szWindowText);\r
1640                 break;\r
1641         case IDS_WINDOW_TEXT_MATCH_FORWARD:                                             // foo*\r
1642                 szWindowText.Delete(szWindowText.GetLength() - 1);      // Delete last '*'\r
1643                 bIsMatchWindowText = 0 == CString(szCurrentWindowText).Find(szWindowText);\r
1644                 break;\r
1645         case IDS_WINDOW_TEXT_MATCH_BACKWARD:                                    // *foo\r
1646                 szWindowText.Delete(0);                                                         // Delete first '*'\r
1647                 bIsMatchWindowText = 0 <= CString(szCurrentWindowText).Find(szWindowText, CString(szCurrentWindowText).GetLength() - szWindowText.GetLength());\r
1648                 break;\r
1649         case IDS_WINDOW_TEXT_MATCH_FULL:                                                // foo\r
1650                 bIsMatchWindowText = szWindowText == CString(szCurrentWindowText);\r
1651                 break;\r
1652         case IDS_WINDOW_TEXT_IGNORE:                                                    // *\r
1653                 bIsMatchWindowText = TRUE;\r
1654                 break;\r
1655         default:\r
1656                 ASSERT(0);\r
1657                 break;\r
1658         }\r
1659 \r
1660 //      CUtils::Log(_T("IsMatchWindowText: %d, _%s_, _%s_"), bIsMatchWindowText, szCurrentWindowText, szWindowText);\r
1661         return bIsMatchWindowText;\r
1662 }\r
1663 \r
1664 void CXkeymacsDll::SetAccelerate(int nAccelerate)\r
1665 {\r
1666         m_nAccelerate = nAccelerate;\r
1667 }\r
1668 \r
1669 int CXkeymacsDll::GetAccelerate()\r
1670 {\r
1671         return m_nAccelerate;\r
1672 }\r
1673 \r
1674 void CXkeymacsDll::SetKeyboardSpeed(int nKeyboardSpeed)\r
1675 {\r
1676         m_nKeyboardSpeed = nKeyboardSpeed;\r
1677 }\r
1678 \r
1679 unsigned int CXkeymacsDll::GetMaxKeyInterval()\r
1680 {\r
1681         // m_nKeyboardSpeed == 0:       slowest repeat rate; approximately  2 characters per second\r
1682         // m_nKeyboardSpeed == 31:      fastest repeat rate; approximately 30 characters per second\r
1683         // 47 ms is max on my machine w/ KeyboardSpeed 31.\r
1684         // 1000 /  2 + 50 = 550\r
1685         // 1000 / 30 + 50 = 83\r
1686         return (unsigned int) (1000.0 / (2.0 + m_nKeyboardSpeed % 32 * 28.0 / 31.0) + 50.0);\r
1687 }\r
1688 \r
1689 void CXkeymacsDll::SetCursorData(HCURSOR hEnable, HCURSOR hDisableTMP, HCURSOR hDisableWOCQ, HICON hDisable, BOOL bEnable)\r
1690 {\r
1691         m_hCursor[STATUS_ENABLE] = hEnable;\r
1692         m_hCursor[STATUS_DISABLE_TMP] = hDisableTMP;\r
1693         m_hCursor[STATUS_DISABLE_WOCQ] = hDisableWOCQ;\r
1694         m_hCursor[STATUS_DISABLE] = hDisable;\r
1695         m_bCursor = bEnable;\r
1696 }\r
1697 \r
1698 void CXkeymacsDll::DoSetCursor()\r
1699 {\r
1700         if (m_bCursor && m_hCurrentCursor) {\r
1701                 ::SetCursor(m_hCurrentCursor);\r
1702         }\r
1703 }\r
1704 \r
1705 void CXkeymacsDll::Set326Compatible(int nApplicationID, BOOL b326Compatible)\r
1706 {\r
1707         m_Config.b326Compatible[nApplicationID] = b326Compatible;\r
1708 }\r
1709 \r
1710 BOOL CXkeymacsDll::Get326Compatible()\r
1711 {\r
1712         return m_Config.b326Compatible[m_nApplicationID];\r
1713 }\r
1714 \r
1715 void CXkeymacsDll::InvokeM_x(const TCHAR *const szPath)\r
1716 {\r
1717 //      CUtils::Log("M-x: szPath=_%s_", szPath);\r
1718         int (*fCommand)() = NULL;\r
1719 \r
1720         for (int i = 0; i < MAX_COMMAND; ++i) {\r
1721                 if (_tcsicmp(szPath, Commands[i].szCommandName) == 0) {\r
1722                         fCommand = Commands[i].fCommand;\r
1723                         break;\r
1724                 }\r
1725         }\r
1726 \r
1727         if (fCommand) {\r
1728 //              CUtils::Log("M-x: Command: _%s_", Commands[i].szCommandName);\r
1729                 fCommand();\r
1730         } else {\r
1731 //              CUtils::Log("M-x: Path: _%s_", szPath);\r
1732                 ShellExecute(NULL, NULL, szPath, NULL, NULL, SW_SHOWNORMAL);\r
1733         }\r
1734 }\r
1735 \r
1736 void CXkeymacsDll::SetM_xTip(const TCHAR *const szPath)\r
1737 {\r
1738         _tcscpy_s(m_M_xTip, "M-x LED");\r
1739         if (szPath && _tcslen(szPath) < 128 - 5)\r
1740                 _stprintf_s(m_M_xTip, "M-x %s", szPath);\r
1741 }\r
1742 \r
1743 BOOL CXkeymacsDll::SendIconMessage(ICONMSG *pMsg, DWORD num)\r
1744 {\r
1745         DWORD ack, read;\r
1746         return CallNamedPipe(ICON_PIPE, pMsg, sizeof(ICONMSG) * num, &ack, sizeof(DWORD), &read, NMPWAIT_NOWAIT);\r
1747 }\r