From 9c16d68a4c4b78c121d0c6dd114aa7a1c7c21514 Mon Sep 17 00:00:00 2001 From: "U-i7\\gimy" Date: Sun, 12 Jul 2009 01:37:29 +0900 Subject: [PATCH] change indent rule to hard tab with width 4 to adjust to default setting of VC++. and incidentally change coding style to K&R(linux) style. by command "astyle --style=linux -T4" --- array.h | 353 ++--- compiler_specific.h | 4 +- compiler_specific_func.cpp | 24 +- d/keyque.c | 163 ++- d/log.c | 245 ++-- d/mayud.c | 1836 +++++++++++++------------- d/rescue/mayudrsc.c | 38 +- dlgeditsetting.cpp | 304 +++-- dlgeditsetting.h | 11 +- dlginvestigate.cpp | 319 +++-- dlginvestigate.h | 9 +- dlglog.cpp | 319 +++-- dlglog.h | 21 +- dlgsetting.cpp | 650 +++++---- dlgsetting.h | 2 +- dlgversion.cpp | 205 ++- dlgversion.h | 2 +- driver.h | 63 +- engine.cpp | 2723 ++++++++++++++++++-------------------- engine.h | 1079 +++++++-------- errormessage.h | 98 +- focus.cpp | 102 +- focus.h | 7 +- function.cpp | 3150 +++++++++++++++++++++----------------------- function.h | 202 ++- hook.cpp | 1275 +++++++++--------- hook.h | 140 +- keyboard.cpp | 406 +++--- keyboard.h | 707 +++++----- keymap.cpp | 682 +++++----- keymap.h | 545 ++++---- layoutmanager.cpp | 330 +++-- layoutmanager.h | 174 ++- mayu.cpp | 1975 +++++++++++++-------------- mayuipc.h | 59 +- mayurc.h | 2 +- msgstream.h | 456 +++---- multithread.h | 62 +- parser.cpp | 523 ++++---- parser.h | 245 ++-- registry.cpp | 471 ++++--- registry.h | 228 ++-- s/installer.cpp | 1180 ++++++++--------- s/installer.h | 306 +++-- s/setup.cpp | 883 ++++++------- s/setuprc.h | 2 +- setting.cpp | 2579 +++++++++++++++++------------------- setting.h | 254 ++-- stringtool.cpp | 604 +++++---- stringtool.h | 175 ++- target.cpp | 396 +++--- target.h | 7 +- vkeytable.cpp | 621 +++++---- vkeytable.h | 4 +- windowstool.cpp | 548 ++++---- windowstool.h | 36 +- yamy.cpp | 93 +- yamyd.cpp | 23 +- 58 files changed, 13648 insertions(+), 14272 deletions(-) mode change 100755 => 100644 d/log.c mode change 100755 => 100644 d/rescue/mayudrsc.c mode change 100755 => 100644 dlgversion.cpp mode change 100755 => 100644 mayurc.h mode change 100755 => 100644 yamy.cpp diff --git a/array.h b/array.h index a595d59..1c03158 100644 --- a/array.h +++ b/array.h @@ -13,174 +13,207 @@ template > class Array { public: - typedef typename Allocator::reference reference; /// - typedef typename Allocator::const_reference const_reference; /// - typedef typename Allocator::pointer iterator; /// - typedef typename Allocator::const_pointer const_iterator; /// - typedef typename Allocator::size_type size_type; /// - typedef typename Allocator::difference_type difference_type; /// - typedef T value_type; /// - typedef Allocator allocator_type; /// - typedef typename Allocator::pointer pointer; /// - typedef typename Allocator::const_pointer const_pointer; /// + typedef typename Allocator::reference reference; /// + typedef typename Allocator::const_reference const_reference; /// + typedef typename Allocator::pointer iterator; /// + typedef typename Allocator::const_pointer const_iterator; /// + typedef typename Allocator::size_type size_type; /// + typedef typename Allocator::difference_type difference_type; /// + typedef T value_type; /// + typedef Allocator allocator_type; /// + typedef typename Allocator::pointer pointer; /// + typedef typename Allocator::const_pointer const_pointer; /// #if 0 - typedef std::reverse_iterator reverse_iterator; /// - typedef std::reverse_iterator const_reverse_iterator; /// -#endif + typedef std::reverse_iterator reverse_iterator; /// + typedef std::reverse_iterator const_reverse_iterator; /// +#endif private: - Allocator m_allocator; /// - size_type m_size; /// - pointer m_buf; /// array buffer + Allocator m_allocator; /// + size_type m_size; /// + pointer m_buf; /// array buffer public: - /// constructor - explicit Array(const Allocator& i_allocator = Allocator()) - : m_allocator(i_allocator), m_size(0), m_buf(NULL) { } - - /// constructor - explicit Array(size_type i_size, const T& i_value = T(), - const Allocator& i_allocator = Allocator()) - : m_allocator(i_allocator), m_size(i_size), - m_buf(m_allocator.allocate(m_size, 0)) - { - std::uninitialized_fill_n(m_buf, i_size, i_value); - } - - /// constructor - template - Array(InputIterator i_begin, InputIterator i_end, - const Allocator& i_allocator = Allocator()) - : m_allocator(i_allocator), m_size(distance(i_begin, i_end)), - m_buf(Allocator::allocate(m_size, 0)) - { - std::uninitialized_copy(i_begin, i_end, m_buf); - } - - /// copy constructor - Array(const Array& i_o) : m_size(0), m_buf(NULL) { operator=(i_o); } + /// constructor + explicit Array(const Allocator& i_allocator = Allocator()) + : m_allocator(i_allocator), m_size(0), m_buf(NULL) { } + + /// constructor + explicit Array(size_type i_size, const T& i_value = T(), + const Allocator& i_allocator = Allocator()) + : m_allocator(i_allocator), m_size(i_size), + m_buf(m_allocator.allocate(m_size, 0)) { + std::uninitialized_fill_n(m_buf, i_size, i_value); + } + + /// constructor + template + Array(InputIterator i_begin, InputIterator i_end, + const Allocator& i_allocator = Allocator()) + : m_allocator(i_allocator), m_size(distance(i_begin, i_end)), + m_buf(Allocator::allocate(m_size, 0)) { + std::uninitialized_copy(i_begin, i_end, m_buf); + } + + /// copy constructor + Array(const Array& i_o) : m_size(0), m_buf(NULL) { + operator=(i_o); + } - /// destractor - ~Array() { clear(); } + /// destractor + ~Array() { + clear(); + } - /// - Array& operator=(const Array& i_o) - { - if (&i_o != this) - { - clear(); - m_size = i_o.m_size; - m_buf = m_allocator.allocate(m_size, 0); - std::uninitialized_copy(i_o.m_buf, i_o.m_buf + m_size, m_buf); - } - return *this; - } - /// - allocator_type get_allocator() const { return Allocator(); } - /// return pointer to the array buffer - typename allocator_type::pointer get() { return m_buf; } - /// return pointer to the array buffer - typename allocator_type::const_pointer get() const { return m_buf; } - /// - iterator begin() { return m_buf; } - /// - const_iterator begin() const { return m_buf; } - /// - iterator end() { return m_buf + m_size; } - /// - const_iterator end() const { return m_buf + m_size; } + /// + Array& operator=(const Array& i_o) { + if (&i_o != this) { + clear(); + m_size = i_o.m_size; + m_buf = m_allocator.allocate(m_size, 0); + std::uninitialized_copy(i_o.m_buf, i_o.m_buf + m_size, m_buf); + } + return *this; + } + /// + allocator_type get_allocator() const { + return Allocator(); + } + /// return pointer to the array buffer + typename allocator_type::pointer get() { + return m_buf; + } + /// return pointer to the array buffer + typename allocator_type::const_pointer get() const { + return m_buf; + } + /// + iterator begin() { + return m_buf; + } + /// + const_iterator begin() const { + return m_buf; + } + /// + iterator end() { + return m_buf + m_size; + } + /// + const_iterator end() const { + return m_buf + m_size; + } #if 0 - /// - reverse_iterator rbegin() { reverse_iterator(end()); } - /// - const_reverse_iterator rbegin() const { const_reverse_iterator(end()); } - /// - reverse_iterator rend() { reverse_iterator(begin()); } - /// - const_reverse_iterator rend() const { const_reverse_iterator(begin()); } + /// + reverse_iterator rbegin() { + reverse_iterator(end()); + } + /// + const_reverse_iterator rbegin() const { + const_reverse_iterator(end()); + } + /// + reverse_iterator rend() { + reverse_iterator(begin()); + } + /// + const_reverse_iterator rend() const { + const_reverse_iterator(begin()); + } #endif - /// - size_type size() const { return m_size; } - /// - size_type max_size() const { return -1; } - /// resize the array buffer. NOTE: the original contents are cleared. - void resize(size_type i_size, const T& i_value = T()) - { - clear(); - m_size = i_size; - m_buf = m_allocator.allocate(m_size, 0); - std::uninitialized_fill_n(m_buf, i_size, i_value); - } - /// resize the array buffer. - template - void resize(InputIterator i_begin, InputIterator i_end) - { - clear(); - m_size = distance(i_begin, i_end); - m_buf = m_allocator.allocate(m_size, 0); - std::uninitialized_copy(i_begin, i_end, m_buf); - } - /// expand the array buffer. the contents of it are copied to the new one - void expand(size_type i_size, const T& i_value = T()) - { - ASSERT( m_size <= i_size ); - if (!m_buf) - resize(i_size, i_value); - else - { - pointer buf = m_allocator.allocate(i_size, 0); - std::uninitialized_copy(m_buf, m_buf + m_size, buf); - std::uninitialized_fill_n(buf + m_size, i_size - m_size, i_value); - clear(); - m_size = i_size; - m_buf = buf; - } - } - /// - bool empty() const { return !m_buf; } - /// - reference operator[](size_type i_n) { return *(m_buf + i_n); } - /// - const_reference operator[](size_type i_n) const - { return *(m_buf + i_n); } - /// - const_reference at(size_type i_n) const - { return *(m_buf + i_n); } - /// - reference at(size_type i_n) - { return *(m_buf + i_n); } - /// - reference front() { return *m_buf; } - /// - const_reference front() const { return *m_buf; } - /// - reference back() { return *(m_buf + m_size - 1); } - /// - const_reference back() const { return *(m_buf + m_size - 1); } - /// - void swap(Array &i_o) - { - if (&i_o != this) - { - pointer buf = m_buf; - size_type size = m_size; - m_buf = i_o.m_buf; - m_size = i_o.m_size; - i_o.m_buf = buf; - i_o.m_size = size; - } - } - /// - void clear() - { - if (m_buf) - { - for (size_type i = 0; i < m_size; i ++) - m_allocator.destroy(&m_buf[i]); - m_allocator.deallocate(m_buf, m_size); - m_buf = 0; - m_size = 0; - } - } + /// + size_type size() const { + return m_size; + } + /// + size_type max_size() const { + return -1; + } + /// resize the array buffer. NOTE: the original contents are cleared. + void resize(size_type i_size, const T& i_value = T()) { + clear(); + m_size = i_size; + m_buf = m_allocator.allocate(m_size, 0); + std::uninitialized_fill_n(m_buf, i_size, i_value); + } + /// resize the array buffer. + template + void resize(InputIterator i_begin, InputIterator i_end) { + clear(); + m_size = distance(i_begin, i_end); + m_buf = m_allocator.allocate(m_size, 0); + std::uninitialized_copy(i_begin, i_end, m_buf); + } + /// expand the array buffer. the contents of it are copied to the new one + void expand(size_type i_size, const T& i_value = T()) { + ASSERT( m_size <= i_size ); + if (!m_buf) + resize(i_size, i_value); + else { + pointer buf = m_allocator.allocate(i_size, 0); + std::uninitialized_copy(m_buf, m_buf + m_size, buf); + std::uninitialized_fill_n(buf + m_size, i_size - m_size, i_value); + clear(); + m_size = i_size; + m_buf = buf; + } + } + /// + bool empty() const { + return !m_buf; + } + /// + reference operator[](size_type i_n) { + return *(m_buf + i_n); + } + /// + const_reference operator[](size_type i_n) const { + return *(m_buf + i_n); + } + /// + const_reference at(size_type i_n) const { + return *(m_buf + i_n); + } + /// + reference at(size_type i_n) { + return *(m_buf + i_n); + } + /// + reference front() { + return *m_buf; + } + /// + const_reference front() const { + return *m_buf; + } + /// + reference back() { + return *(m_buf + m_size - 1); + } + /// + const_reference back() const { + return *(m_buf + m_size - 1); + } + /// + void swap(Array &i_o) { + if (&i_o != this) { + pointer buf = m_buf; + size_type size = m_size; + m_buf = i_o.m_buf; + m_size = i_o.m_size; + i_o.m_buf = buf; + i_o.m_size = size; + } + } + /// + void clear() { + if (m_buf) { + for (size_type i = 0; i < m_size; i ++) + m_allocator.destroy(&m_buf[i]); + m_allocator.deallocate(m_buf, m_size); + m_buf = 0; + m_size = 0; + } + } }; #endif // _ARRAY_H diff --git a/compiler_specific.h b/compiler_specific.h index 9fd5780..1490e6e 100644 --- a/compiler_specific.h +++ b/compiler_specific.h @@ -60,8 +60,8 @@ extern wchar_t **_wargv; extern "C" { - int WINAPI _tWinMain(HINSTANCE i_hInstance, HINSTANCE i_hPrevInstance, - LPTSTR i_lpszCmdLine, int i_nCmdShow); + int WINAPI _tWinMain(HINSTANCE i_hInstance, HINSTANCE i_hPrevInstance, + LPTSTR i_lpszCmdLine, int i_nCmdShow); } # define stati64_t stati64 diff --git a/compiler_specific_func.cpp b/compiler_specific_func.cpp index 4fec730..6da7fa0 100644 --- a/compiler_specific_func.cpp +++ b/compiler_specific_func.cpp @@ -13,12 +13,12 @@ // get compiler version string tstring getCompilerVersionString() { - TCHAR buf[200]; - _sntprintf(buf, NUMBER_OF(buf), - _T("Microsoft (R) 32-bit C/C++ Optimizing Compiler Version %d.%02d"), - _MSC_VER / 100, - _MSC_VER % 100); - return tstring(buf); + TCHAR buf[200]; + _sntprintf(buf, NUMBER_OF(buf), + _T("Microsoft (R) 32-bit C/C++ Optimizing Compiler Version %d.%02d"), + _MSC_VER / 100, + _MSC_VER % 100); + return tstring(buf); } @@ -30,12 +30,12 @@ tstring getCompilerVersionString() // get compiler version string tstring getCompilerVersionString() { - TCHAR buf[100]; - _sntprintf(buf, NUMBER_OF(buf), _T("Borland C++ %d.%d.%d"), - __BORLANDC__ / 0x100, - __BORLANDC__ / 0x10 % 0x10, - __BORLANDC__ % 0x10); - return tstring(buf); + TCHAR buf[100]; + _sntprintf(buf, NUMBER_OF(buf), _T("Borland C++ %d.%d.%d"), + __BORLANDC__ / 0x100, + __BORLANDC__ / 0x10 % 0x10, + __BORLANDC__ % 0x10); + return tstring(buf); } diff --git a/d/keyque.c b/d/keyque.c index d1b5019..0328b39 100644 --- a/d/keyque.c +++ b/d/keyque.c @@ -6,13 +6,12 @@ // Definitions -typedef struct KeyQue -{ - ULONG count; // Number of keys in the que - ULONG lengthof_que; // Length of que - KEYBOARD_INPUT_DATA *insert; // Insertion pointer for que - KEYBOARD_INPUT_DATA *remove; // Removal pointer for que - KEYBOARD_INPUT_DATA *que; +typedef struct KeyQue { + ULONG count; // Number of keys in the que + ULONG lengthof_que; // Length of que + KEYBOARD_INPUT_DATA *insert; // Insertion pointer for que + KEYBOARD_INPUT_DATA *remove; // Removal pointer for que + KEYBOARD_INPUT_DATA *que; } KeyQue; @@ -43,110 +42,102 @@ ULONG KqDeque(KeyQue *kq, OUT KEYBOARD_INPUT_DATA *buf, IN ULONG lengthof_buf); NTSTATUS KqInitialize(KeyQue *kq) { - kq->count = 0; - kq->lengthof_que = KeyQueSize; - kq->que = ExAllocatePool(NonPagedPool, - kq->lengthof_que * sizeof(KEYBOARD_INPUT_DATA)); - kq->insert = kq->que; - kq->remove = kq->que; - if (kq->que == NULL) - return STATUS_INSUFFICIENT_RESOURCES; - else - return STATUS_SUCCESS; + kq->count = 0; + kq->lengthof_que = KeyQueSize; + kq->que = ExAllocatePool(NonPagedPool, + kq->lengthof_que * sizeof(KEYBOARD_INPUT_DATA)); + kq->insert = kq->que; + kq->remove = kq->que; + if (kq->que == NULL) + return STATUS_INSUFFICIENT_RESOURCES; + else + return STATUS_SUCCESS; } void KqClear(KeyQue *kq) { - kq->count = 0; - kq->insert = kq->que; - kq->remove = kq->que; + kq->count = 0; + kq->insert = kq->que; + kq->remove = kq->que; } NTSTATUS KqFinalize(KeyQue *kq) { - if (kq->que) - ExFreePool(kq->que); - return STATUS_SUCCESS; + if (kq->que) + ExFreePool(kq->que); + return STATUS_SUCCESS; } BOOLEAN KqIsEmpty(KeyQue *kq) { - return 0 == kq->count; + return 0 == kq->count; } // return: lengthof copied data ULONG KqEnque(KeyQue *kq, IN KEYBOARD_INPUT_DATA *buf, IN ULONG lengthof_buf) { - ULONG rest; - - if (kq->lengthof_que - kq->count < lengthof_buf) // overflow - lengthof_buf = kq->lengthof_que - kq->count; // chop overflowed datum - if (lengthof_buf <= 0) - return 0; - - rest = kq->lengthof_que - (kq->insert - kq->que); - if (rest < lengthof_buf) - { - ULONG copy = rest; - if (0 < copy) - { - RtlMoveMemory((PCHAR)kq->insert, (PCHAR)buf, - sizeof(KEYBOARD_INPUT_DATA) * copy); - buf += copy; - } - copy = lengthof_buf - copy; - if (0 < copy) - RtlMoveMemory((PCHAR)kq->que, (PCHAR)buf, - sizeof(KEYBOARD_INPUT_DATA) * copy); - kq->insert = kq->que + copy; - } - else - { - RtlMoveMemory((PCHAR)kq->insert, (PCHAR)buf, - sizeof(KEYBOARD_INPUT_DATA) * lengthof_buf); - kq->insert += lengthof_buf; - } - kq->count += lengthof_buf; - return lengthof_buf; + ULONG rest; + + if (kq->lengthof_que - kq->count < lengthof_buf) // overflow + lengthof_buf = kq->lengthof_que - kq->count; // chop overflowed datum + if (lengthof_buf <= 0) + return 0; + + rest = kq->lengthof_que - (kq->insert - kq->que); + if (rest < lengthof_buf) { + ULONG copy = rest; + if (0 < copy) { + RtlMoveMemory((PCHAR)kq->insert, (PCHAR)buf, + sizeof(KEYBOARD_INPUT_DATA) * copy); + buf += copy; + } + copy = lengthof_buf - copy; + if (0 < copy) + RtlMoveMemory((PCHAR)kq->que, (PCHAR)buf, + sizeof(KEYBOARD_INPUT_DATA) * copy); + kq->insert = kq->que + copy; + } else { + RtlMoveMemory((PCHAR)kq->insert, (PCHAR)buf, + sizeof(KEYBOARD_INPUT_DATA) * lengthof_buf); + kq->insert += lengthof_buf; + } + kq->count += lengthof_buf; + return lengthof_buf; } // return: lengthof copied data ULONG KqDeque(KeyQue *kq, OUT KEYBOARD_INPUT_DATA *buf, IN ULONG lengthof_buf) { - ULONG rest; - - if (kq->count < lengthof_buf) - lengthof_buf = kq->count; - if (lengthof_buf <= 0) - return 0; - - rest = kq->lengthof_que - (kq->remove - kq->que); - if (rest < lengthof_buf) - { - ULONG copy = rest; - if (0 < copy) - { - RtlMoveMemory((PCHAR)buf, (PCHAR)kq->remove, - sizeof(KEYBOARD_INPUT_DATA) * copy); - buf += copy; - } - copy = lengthof_buf - copy; - if (0 < copy) - RtlMoveMemory((PCHAR)buf, (PCHAR)kq->que, - sizeof(KEYBOARD_INPUT_DATA) * copy); - kq->remove = kq->que + copy; - } - else - { - RtlMoveMemory((PCHAR)buf, (PCHAR)kq->remove, - sizeof(KEYBOARD_INPUT_DATA) * lengthof_buf); - kq->remove += lengthof_buf; - } - kq->count -= lengthof_buf; - return lengthof_buf; + ULONG rest; + + if (kq->count < lengthof_buf) + lengthof_buf = kq->count; + if (lengthof_buf <= 0) + return 0; + + rest = kq->lengthof_que - (kq->remove - kq->que); + if (rest < lengthof_buf) { + ULONG copy = rest; + if (0 < copy) { + RtlMoveMemory((PCHAR)buf, (PCHAR)kq->remove, + sizeof(KEYBOARD_INPUT_DATA) * copy); + buf += copy; + } + copy = lengthof_buf - copy; + if (0 < copy) + RtlMoveMemory((PCHAR)buf, (PCHAR)kq->que, + sizeof(KEYBOARD_INPUT_DATA) * copy); + kq->remove = kq->que + copy; + } else { + RtlMoveMemory((PCHAR)buf, (PCHAR)kq->remove, + sizeof(KEYBOARD_INPUT_DATA) * lengthof_buf); + kq->remove += lengthof_buf; + } + kq->count -= lengthof_buf; + return lengthof_buf; } diff --git a/d/log.c b/d/log.c old mode 100755 new mode 100644 index 9ba964b..02ecec1 --- a/d/log.c +++ b/d/log.c @@ -8,8 +8,8 @@ #define BUF_MAX_SIZE 128 typedef struct _logEntry { - LIST_ENTRY listEntry; - UNICODE_STRING log; + LIST_ENTRY listEntry; + UNICODE_STRING log; } logEntry; static LIST_ENTRY s_logList; @@ -18,147 +18,138 @@ static PIRP s_irp; void mayuLogInit(const char *message) { - InitializeListHead(&s_logList); - KeInitializeSpinLock(&s_logListLock); - s_irp = NULL; - mayuLogEnque(message); + InitializeListHead(&s_logList); + KeInitializeSpinLock(&s_logListLock); + s_irp = NULL; + mayuLogEnque(message); } void mayuLogTerm() { - if (s_irp) - { - IoReleaseCancelSpinLock(s_irp->CancelIrql); - s_irp->IoStatus.Status = STATUS_CANCELLED; - s_irp->IoStatus.Information = 0; - IoCompleteRequest(s_irp, IO_NO_INCREMENT); - s_irp = NULL; - } + if (s_irp) { + IoReleaseCancelSpinLock(s_irp->CancelIrql); + s_irp->IoStatus.Status = STATUS_CANCELLED; + s_irp->IoStatus.Information = 0; + IoCompleteRequest(s_irp, IO_NO_INCREMENT); + s_irp = NULL; + } } void mayuLogEnque(const char *fmt, ...) { - va_list argp; - logEntry *entry; - ANSI_STRING ansiBuf; - UNICODE_STRING unicodeBuf; - CHAR buf[BUF_MAX_SIZE] = ""; - WCHAR wbuf[BUF_MAX_SIZE] = L""; - USHORT i, j; - ULONG ul; - PUNICODE_STRING punicode; - - entry = (logEntry*)ExAllocatePool(NonPagedPool, sizeof(logEntry)); - if (!entry) - return; - entry->log.Length = 0; - entry->log.MaximumLength = BUF_MAX_SIZE; - entry->log.Buffer = (PWSTR)ExAllocatePool(NonPagedPool, BUF_MAX_SIZE); - - unicodeBuf.Length = 0; - unicodeBuf.MaximumLength = BUF_MAX_SIZE; - unicodeBuf.Buffer = wbuf; - - ansiBuf.Length = 0; - ansiBuf.MaximumLength = BUF_MAX_SIZE; - ansiBuf.Buffer = buf; - - va_start(argp, fmt); - for (i = j = 0; i < BUF_MAX_SIZE; ++i) - { - ansiBuf.Buffer[i - j] = fmt[i]; - if (fmt[i] == '\0') - { - ansiBuf.Length = i - j; - RtlAnsiStringToUnicodeString(&unicodeBuf, &ansiBuf, FALSE); - RtlAppendUnicodeStringToString(&entry->log, &unicodeBuf); - break; - } - if (fmt[i] == '%') - { - ansiBuf.Length = i - j; - RtlAnsiStringToUnicodeString(&unicodeBuf, &ansiBuf, FALSE); - RtlAppendUnicodeStringToString(&entry->log, &unicodeBuf); - switch(fmt[++i]) - { - case 'x': - ul = va_arg(argp, ULONG); - RtlIntegerToUnicodeString(ul, 16, &unicodeBuf); - RtlAppendUnicodeStringToString(&entry->log, &unicodeBuf); - break; - case 'd': - ul = va_arg(argp, ULONG); - RtlIntegerToUnicodeString(ul, 10, &unicodeBuf); - RtlAppendUnicodeStringToString(&entry->log, &unicodeBuf); - break; - case 'T': - punicode = va_arg(argp, PUNICODE_STRING); - RtlAppendUnicodeStringToString(&entry->log, punicode); - } - j = i + 1; - } - } - va_end(argp); - - ExInterlockedInsertTailList(&s_logList, &entry->listEntry, &s_logListLock); - - if (s_irp) - { - KIRQL cancelIrql; - - mayuLogDeque(s_irp); - IoAcquireCancelSpinLock(&cancelIrql); - IoSetCancelRoutine(s_irp, NULL); - IoReleaseCancelSpinLock(cancelIrql); - IoCompleteRequest(s_irp, IO_NO_INCREMENT); - s_irp = NULL; - } + va_list argp; + logEntry *entry; + ANSI_STRING ansiBuf; + UNICODE_STRING unicodeBuf; + CHAR buf[BUF_MAX_SIZE] = ""; + WCHAR wbuf[BUF_MAX_SIZE] = L""; + USHORT i, j; + ULONG ul; + PUNICODE_STRING punicode; + + entry = (logEntry*)ExAllocatePool(NonPagedPool, sizeof(logEntry)); + if (!entry) + return; + entry->log.Length = 0; + entry->log.MaximumLength = BUF_MAX_SIZE; + entry->log.Buffer = (PWSTR)ExAllocatePool(NonPagedPool, BUF_MAX_SIZE); + + unicodeBuf.Length = 0; + unicodeBuf.MaximumLength = BUF_MAX_SIZE; + unicodeBuf.Buffer = wbuf; + + ansiBuf.Length = 0; + ansiBuf.MaximumLength = BUF_MAX_SIZE; + ansiBuf.Buffer = buf; + + va_start(argp, fmt); + for (i = j = 0; i < BUF_MAX_SIZE; ++i) { + ansiBuf.Buffer[i - j] = fmt[i]; + if (fmt[i] == '\0') { + ansiBuf.Length = i - j; + RtlAnsiStringToUnicodeString(&unicodeBuf, &ansiBuf, FALSE); + RtlAppendUnicodeStringToString(&entry->log, &unicodeBuf); + break; + } + if (fmt[i] == '%') { + ansiBuf.Length = i - j; + RtlAnsiStringToUnicodeString(&unicodeBuf, &ansiBuf, FALSE); + RtlAppendUnicodeStringToString(&entry->log, &unicodeBuf); + switch (fmt[++i]) { + case 'x': + ul = va_arg(argp, ULONG); + RtlIntegerToUnicodeString(ul, 16, &unicodeBuf); + RtlAppendUnicodeStringToString(&entry->log, &unicodeBuf); + break; + case 'd': + ul = va_arg(argp, ULONG); + RtlIntegerToUnicodeString(ul, 10, &unicodeBuf); + RtlAppendUnicodeStringToString(&entry->log, &unicodeBuf); + break; + case 'T': + punicode = va_arg(argp, PUNICODE_STRING); + RtlAppendUnicodeStringToString(&entry->log, punicode); + } + j = i + 1; + } + } + va_end(argp); + + ExInterlockedInsertTailList(&s_logList, &entry->listEntry, &s_logListLock); + + if (s_irp) { + KIRQL cancelIrql; + + mayuLogDeque(s_irp); + IoAcquireCancelSpinLock(&cancelIrql); + IoSetCancelRoutine(s_irp, NULL); + IoReleaseCancelSpinLock(cancelIrql); + IoCompleteRequest(s_irp, IO_NO_INCREMENT); + s_irp = NULL; + } } VOID mayuLogCancel(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - s_irp = NULL; - IoReleaseCancelSpinLock(irp->CancelIrql); - irp->IoStatus.Status = STATUS_CANCELLED; - irp->IoStatus.Information = 0; - IoCompleteRequest(irp, IO_NO_INCREMENT); + s_irp = NULL; + IoReleaseCancelSpinLock(irp->CancelIrql); + irp->IoStatus.Status = STATUS_CANCELLED; + irp->IoStatus.Information = 0; + IoCompleteRequest(irp, IO_NO_INCREMENT); } NTSTATUS mayuLogDeque(PIRP irp) { - KIRQL currentIrql; - - KeAcquireSpinLock(&s_logListLock, ¤tIrql); - if (IsListEmpty(&s_logList) == TRUE) - { - KIRQL cancelIrql; - - IoAcquireCancelSpinLock(&cancelIrql); - IoMarkIrpPending(irp); - s_irp = irp; - IoSetCancelRoutine(irp, mayuLogCancel); - IoReleaseCancelSpinLock(cancelIrql); - KeReleaseSpinLock(&s_logListLock, currentIrql); - irp->IoStatus.Information = 0; - irp->IoStatus.Status = STATUS_PENDING; - } - else - { - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); - PLIST_ENTRY pListEntry; - logEntry *pEntry; - - KeReleaseSpinLock(&s_logListLock, currentIrql); - pListEntry = ExInterlockedRemoveHeadList(&s_logList, &s_logListLock); - pEntry = CONTAINING_RECORD(pListEntry, logEntry, listEntry); - RtlCopyMemory(irp->AssociatedIrp.SystemBuffer, - pEntry->log.Buffer, pEntry->log.Length); - irp->IoStatus.Information = pEntry->log.Length; - irp->IoStatus.Status = STATUS_SUCCESS; - ExFreePool(pEntry->log.Buffer); - ExFreePool(pEntry); - } - return irp->IoStatus.Status; + KIRQL currentIrql; + + KeAcquireSpinLock(&s_logListLock, ¤tIrql); + if (IsListEmpty(&s_logList) == TRUE) { + KIRQL cancelIrql; + + IoAcquireCancelSpinLock(&cancelIrql); + IoMarkIrpPending(irp); + s_irp = irp; + IoSetCancelRoutine(irp, mayuLogCancel); + IoReleaseCancelSpinLock(cancelIrql); + KeReleaseSpinLock(&s_logListLock, currentIrql); + irp->IoStatus.Information = 0; + irp->IoStatus.Status = STATUS_PENDING; + } else { + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); + PLIST_ENTRY pListEntry; + logEntry *pEntry; + + KeReleaseSpinLock(&s_logListLock, currentIrql); + pListEntry = ExInterlockedRemoveHeadList(&s_logList, &s_logListLock); + pEntry = CONTAINING_RECORD(pListEntry, logEntry, listEntry); + RtlCopyMemory(irp->AssociatedIrp.SystemBuffer, + pEntry->log.Buffer, pEntry->log.Length); + irp->IoStatus.Information = pEntry->log.Length; + irp->IoStatus.Status = STATUS_SUCCESS; + ExFreePool(pEntry->log.Buffer); + ExFreePool(pEntry); + } + return irp->IoStatus.Status; } #endif // DBG diff --git a/d/mayud.c b/d/mayud.c index b5a7f63..662657c 100644 --- a/d/mayud.c +++ b/d/mayud.c @@ -36,33 +36,31 @@ struct _DetourDeviceExtension; struct _FilterDeviceExtension; -typedef struct _DetourDeviceExtension -{ - PDRIVER_DISPATCH MajorFunction[IRP_MJ_MAXIMUM_FUNCTION + 1]; - - KSPIN_LOCK lock; // lock below datum - PDEVICE_OBJECT filterDevObj; - LONG isOpen; - BOOLEAN wasCleanupInitiated; // - PIRP irpq; - KeyQue readQue; // when IRP_MJ_READ, the contents of readQue are returned +typedef struct _DetourDeviceExtension { + PDRIVER_DISPATCH MajorFunction[IRP_MJ_MAXIMUM_FUNCTION + 1]; + + KSPIN_LOCK lock; // lock below datum + PDEVICE_OBJECT filterDevObj; + LONG isOpen; + BOOLEAN wasCleanupInitiated; // + PIRP irpq; + KeyQue readQue; // when IRP_MJ_READ, the contents of readQue are returned } DetourDeviceExtension; -typedef struct _FilterDeviceExtension -{ - PDRIVER_DISPATCH MajorFunction[IRP_MJ_MAXIMUM_FUNCTION + 1]; - - PDEVICE_OBJECT detourDevObj; - PDEVICE_OBJECT kbdClassDevObj; // keyboard class device object - +typedef struct _FilterDeviceExtension { + PDRIVER_DISPATCH MajorFunction[IRP_MJ_MAXIMUM_FUNCTION + 1]; + + PDEVICE_OBJECT detourDevObj; + PDEVICE_OBJECT kbdClassDevObj; // keyboard class device object + #ifdef USE_TOUCHPAD - BOOLEAN isKeyboard; + BOOLEAN isKeyboard; #endif - KSPIN_LOCK lock; // lock below datum - PIRP irpq; - KeyQue readQue; // when IRP_MJ_READ, the contents of readQue are returned + KSPIN_LOCK lock; // lock below datum + PIRP irpq; + KeyQue readQue; // when IRP_MJ_READ, the contents of readQue are returned #ifdef USE_TOUCHPAD - BOOLEAN isTouched; + BOOLEAN isTouched; #endif } FilterDeviceExtension; @@ -120,16 +118,16 @@ ULONG g_RequestIsPending_offset; sizeof(str) - sizeof(UNICODE_NULL), str } static UNICODE_STRING MayuDetourDeviceName = -UnicodeString(L"\\Device\\MayuDetour0"); + UnicodeString(L"\\Device\\MayuDetour0"); static UNICODE_STRING MayuDetourWin32DeviceName = -UnicodeString(L"\\DosDevices\\MayuDetour1"); + UnicodeString(L"\\DosDevices\\MayuDetour1"); static UNICODE_STRING KeyboardClassDeviceName = -UnicodeString(DD_KEYBOARD_DEVICE_NAME_U L"0"); + UnicodeString(DD_KEYBOARD_DEVICE_NAME_U L"0"); static UNICODE_STRING KeyboardClassDriverName = -UnicodeString(L"\\Driver\\kbdclass"); + UnicodeString(L"\\Driver\\kbdclass"); #ifdef USE_TOUCHPAD #define TOUCHPAD_PRESSURE_OFFSET 7 @@ -141,7 +139,7 @@ PDRIVER_DISPATCH _IopInvalidDeviceRequest; // Default dispatch function #define MAYUD_MODE L"" static UNICODE_STRING MayuDriverVersion = -UnicodeString(L"$Revision: 1.27 $" MAYUD_MODE); + UnicodeString(L"$Revision: 1.27 $" MAYUD_MODE); /////////////////////////////////////////////////////////////////////////////// @@ -149,358 +147,350 @@ UnicodeString(L"$Revision: 1.27 $" MAYUD_MODE); void DEBUG_LOGChain(PDRIVER_OBJECT driverObject) { - PDEVICE_OBJECT deviceObject = driverObject->DeviceObject; - - if (deviceObject) - { - while (deviceObject->NextDevice) - { - DEBUG_LOG(("%x->", deviceObject)); - deviceObject = deviceObject->NextDevice; - } - DEBUG_LOG(("%x", deviceObject)); - } - return; + PDEVICE_OBJECT deviceObject = driverObject->DeviceObject; + + if (deviceObject) { + while (deviceObject->NextDevice) { + DEBUG_LOG(("%x->", deviceObject)); + deviceObject = deviceObject->NextDevice; + } + DEBUG_LOG(("%x", deviceObject)); + } + return; } // initialize driver NTSTATUS DriverEntry(IN PDRIVER_OBJECT driverObject, - IN PUNICODE_STRING registryPath) + IN PUNICODE_STRING registryPath) { - NTSTATUS status; - BOOLEAN is_symbolicLinkCreated = FALSE; - ULONG i; - PDEVICE_OBJECT detourDevObj = NULL; - DetourDeviceExtension *detourDevExt = NULL; - ULONG start = 0; - RTL_QUERY_REGISTRY_TABLE query[2]; - - UNREFERENCED_PARAMETER(registryPath); - - DEBUG_LOG_INIT(("mayud: start logging")); - - // Environment specific initialize - RtlZeroMemory(query, sizeof(query)); - query[0].Name = L"Start"; - query[0].Flags = RTL_QUERY_REGISTRY_DIRECT; - query[0].EntryContext = &start; - RtlQueryRegistryValues(RTL_REGISTRY_SERVICES, L"mayud", query, NULL, NULL); - if (start == 0x03) { - g_isPnP = TRUE; - DEBUG_LOG(("is PnP")); - } else { - g_isPnP = FALSE; - DEBUG_LOG(("is not PnP")); - } + NTSTATUS status; + BOOLEAN is_symbolicLinkCreated = FALSE; + ULONG i; + PDEVICE_OBJECT detourDevObj = NULL; + DetourDeviceExtension *detourDevExt = NULL; + ULONG start = 0; + RTL_QUERY_REGISTRY_TABLE query[2]; + + UNREFERENCED_PARAMETER(registryPath); + + DEBUG_LOG_INIT(("mayud: start logging")); + + // Environment specific initialize + RtlZeroMemory(query, sizeof(query)); + query[0].Name = L"Start"; + query[0].Flags = RTL_QUERY_REGISTRY_DIRECT; + query[0].EntryContext = &start; + RtlQueryRegistryValues(RTL_REGISTRY_SERVICES, L"mayud", query, NULL, NULL); + if (start == 0x03) { + g_isPnP = TRUE; + DEBUG_LOG(("is PnP")); + } else { + g_isPnP = FALSE; + DEBUG_LOG(("is not PnP")); + } #ifdef MAYUD_NT4 - g_isXp = FALSE; - g_SpinLock_offset = 48; - g_RequestIsPending_offset = 0; + g_isXp = FALSE; + g_SpinLock_offset = 48; + g_RequestIsPending_offset = 0; #else /* !MAYUD_NT4 */ - if (IoIsWdmVersionAvailable(1, 0x20)) { // is WindowsXP - DEBUG_LOG(("is WindowsXp")); - g_isXp = TRUE; - g_SpinLock_offset = 108; - g_RequestIsPending_offset = 0; - } else if (IoIsWdmVersionAvailable(1, 0x10)) { // is Windows2000 - DEBUG_LOG(("is Windows2000")); - g_isXp =FALSE; - g_SpinLock_offset = 116; - g_RequestIsPending_offset = 48; - } else { // Unknown version - DEBUG_LOG(("unknown Windows")); - status = STATUS_UNKNOWN_REVISION; - goto error; - } + if (IoIsWdmVersionAvailable(1, 0x20)) { // is WindowsXP + DEBUG_LOG(("is WindowsXp")); + g_isXp = TRUE; + g_SpinLock_offset = 108; + g_RequestIsPending_offset = 0; + } else if (IoIsWdmVersionAvailable(1, 0x10)) { // is Windows2000 + DEBUG_LOG(("is Windows2000")); + g_isXp =FALSE; + g_SpinLock_offset = 116; + g_RequestIsPending_offset = 48; + } else { // Unknown version + DEBUG_LOG(("unknown Windows")); + status = STATUS_UNKNOWN_REVISION; + goto error; + } #endif /* MAYUD_NT4 */ - // initialize global variables - _IopInvalidDeviceRequest = driverObject->MajorFunction[IRP_MJ_CREATE]; - - // set major functions - driverObject->DriverUnload = mayuUnloadDriver; - if (g_isPnP == TRUE) { - driverObject->DriverExtension->AddDevice = mayuAddDevice; - } - for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++) + // initialize global variables + _IopInvalidDeviceRequest = driverObject->MajorFunction[IRP_MJ_CREATE]; + + // set major functions + driverObject->DriverUnload = mayuUnloadDriver; + if (g_isPnP == TRUE) { + driverObject->DriverExtension->AddDevice = mayuAddDevice; + } + for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++) #ifdef MAYUD_NT4 - if (i != IRP_MJ_POWER) + if (i != IRP_MJ_POWER) #endif // MAYUD_NT4 - driverObject->MajorFunction[i] = mayuGenericDispatch; - if (g_isPnP == TRUE) { - driverObject->MajorFunction[IRP_MJ_PNP] = mayuGenericDispatch; - } - - // create a device - { - // create detour device - status = IoCreateDevice(driverObject, sizeof(DetourDeviceExtension), - &MayuDetourDeviceName, FILE_DEVICE_KEYBOARD, - 0, FALSE, &detourDevObj); - - if (!NT_SUCCESS(status)) goto error; - DEBUG_LOG(("create detour device: %x", detourDevObj)); - DEBUG_LOGChain(driverObject); - detourDevObj->Flags |= DO_BUFFERED_IO; + driverObject->MajorFunction[i] = mayuGenericDispatch; + if (g_isPnP == TRUE) { + driverObject->MajorFunction[IRP_MJ_PNP] = mayuGenericDispatch; + } + + // create a device + { + // create detour device + status = IoCreateDevice(driverObject, sizeof(DetourDeviceExtension), + &MayuDetourDeviceName, FILE_DEVICE_KEYBOARD, + 0, FALSE, &detourDevObj); + + if (!NT_SUCCESS(status)) goto error; + DEBUG_LOG(("create detour device: %x", detourDevObj)); + DEBUG_LOGChain(driverObject); + detourDevObj->Flags |= DO_BUFFERED_IO; #ifndef MAYUD_NT4 - detourDevObj->Flags |= DO_POWER_PAGABLE; + detourDevObj->Flags |= DO_POWER_PAGABLE; #endif // !MAYUD_NT4 - // initialize detour device extension - detourDevExt = (DetourDeviceExtension*)detourDevObj->DeviceExtension; - RtlZeroMemory(detourDevExt, sizeof(DetourDeviceExtension)); - detourDevExt->filterDevObj = NULL; - - KeInitializeSpinLock(&detourDevExt->lock); - detourDevExt->isOpen = FALSE; - detourDevExt->wasCleanupInitiated = FALSE; - detourDevExt->irpq = NULL; - status = KqInitialize(&detourDevExt->readQue); - if (!NT_SUCCESS(status)) goto error; - - // create symbolic link for detour - status = - IoCreateSymbolicLink(&MayuDetourWin32DeviceName, &MayuDetourDeviceName); - if (!NT_SUCCESS(status)) goto error; - is_symbolicLinkCreated = TRUE; - - if (g_isPnP == FALSE) - // attach filter device to keyboard class device - { - PFILE_OBJECT f; - PDEVICE_OBJECT kbdClassDevObj; - - status = IoGetDeviceObjectPointer(&KeyboardClassDeviceName, - FILE_ALL_ACCESS, &f, - &kbdClassDevObj); - if (!NT_SUCCESS(status)) goto error; - ObDereferenceObject(f); - status = mayuAddDevice(driverObject, kbdClassDevObj); - - // why cannot I do below ? + // initialize detour device extension + detourDevExt = (DetourDeviceExtension*)detourDevObj->DeviceExtension; + RtlZeroMemory(detourDevExt, sizeof(DetourDeviceExtension)); + detourDevExt->filterDevObj = NULL; + + KeInitializeSpinLock(&detourDevExt->lock); + detourDevExt->isOpen = FALSE; + detourDevExt->wasCleanupInitiated = FALSE; + detourDevExt->irpq = NULL; + status = KqInitialize(&detourDevExt->readQue); + if (!NT_SUCCESS(status)) goto error; + + // create symbolic link for detour + status = + IoCreateSymbolicLink(&MayuDetourWin32DeviceName, &MayuDetourDeviceName); + if (!NT_SUCCESS(status)) goto error; + is_symbolicLinkCreated = TRUE; + + if (g_isPnP == FALSE) + // attach filter device to keyboard class device + { + PFILE_OBJECT f; + PDEVICE_OBJECT kbdClassDevObj; + + status = IoGetDeviceObjectPointer(&KeyboardClassDeviceName, + FILE_ALL_ACCESS, &f, + &kbdClassDevObj); + if (!NT_SUCCESS(status)) goto error; + ObDereferenceObject(f); + status = mayuAddDevice(driverObject, kbdClassDevObj); + + // why cannot I do below ? // status = IoAttachDevice(filterDevObj, &KeyboardClassDeviceName, // &filterDevExt->kbdClassDevObj); - if (!NT_SUCCESS(status)) goto error; - } - - // initialize Major Functions - for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++) - { - detourDevExt->MajorFunction[i] = _IopInvalidDeviceRequest; - } - - detourDevExt->MajorFunction[IRP_MJ_READ] = detourRead; - detourDevExt->MajorFunction[IRP_MJ_WRITE] = detourWrite; - detourDevExt->MajorFunction[IRP_MJ_CREATE] = detourCreate; - detourDevExt->MajorFunction[IRP_MJ_CLOSE] = detourClose; - detourDevExt->MajorFunction[IRP_MJ_CLEANUP] = detourCleanup; - detourDevExt->MajorFunction[IRP_MJ_DEVICE_CONTROL] = detourDeviceControl; + if (!NT_SUCCESS(status)) goto error; + } + + // initialize Major Functions + for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++) { + detourDevExt->MajorFunction[i] = _IopInvalidDeviceRequest; + } + + detourDevExt->MajorFunction[IRP_MJ_READ] = detourRead; + detourDevExt->MajorFunction[IRP_MJ_WRITE] = detourWrite; + detourDevExt->MajorFunction[IRP_MJ_CREATE] = detourCreate; + detourDevExt->MajorFunction[IRP_MJ_CLOSE] = detourClose; + detourDevExt->MajorFunction[IRP_MJ_CLEANUP] = detourCleanup; + detourDevExt->MajorFunction[IRP_MJ_DEVICE_CONTROL] = detourDeviceControl; #ifndef MAYUD_NT4 - detourDevExt->MajorFunction[IRP_MJ_POWER] = detourPower; + detourDevExt->MajorFunction[IRP_MJ_POWER] = detourPower; #endif // !MAYUD_NT4 - if (g_isPnP == TRUE) { - detourDevExt->MajorFunction[IRP_MJ_PNP] = detourPnP; - } - } - detourDevObj->Flags &= ~DO_DEVICE_INITIALIZING; - - return STATUS_SUCCESS; - - error: - { - if (is_symbolicLinkCreated) - IoDeleteSymbolicLink(&MayuDetourWin32DeviceName); - if (detourDevObj) - { - KqFinalize(&detourDevExt->readQue); - IoDeleteDevice(detourDevObj); - } - } - return status; + if (g_isPnP == TRUE) { + detourDevExt->MajorFunction[IRP_MJ_PNP] = detourPnP; + } + } + detourDevObj->Flags &= ~DO_DEVICE_INITIALIZING; + + return STATUS_SUCCESS; + +error: { + if (is_symbolicLinkCreated) + IoDeleteSymbolicLink(&MayuDetourWin32DeviceName); + if (detourDevObj) { + KqFinalize(&detourDevExt->readQue); + IoDeleteDevice(detourDevObj); + } + } + return status; } NTSTATUS mayuAddDevice(IN PDRIVER_OBJECT driverObject, - IN PDEVICE_OBJECT kbdClassDevObj) + IN PDEVICE_OBJECT kbdClassDevObj) { - NTSTATUS status; - PDEVICE_OBJECT devObj; - PDEVICE_OBJECT filterDevObj; - PDEVICE_OBJECT attachedDevObj; - DetourDeviceExtension *detourDevExt; - FilterDeviceExtension *filterDevExt; - ULONG i; - - DEBUG_LOG(("attach to device: %x", kbdClassDevObj)); - DEBUG_LOG(("type of device: %x", kbdClassDevObj->DeviceType)); - DEBUG_LOG(("name of driver: %T", &(kbdClassDevObj->DriverObject->DriverName))); - - // create filter device - status = IoCreateDevice(driverObject, sizeof(FilterDeviceExtension), - NULL, FILE_DEVICE_KEYBOARD, - 0, FALSE, &filterDevObj); - DEBUG_LOG(("add filter device: %x", filterDevObj)); - DEBUG_LOGChain(driverObject); - if (!NT_SUCCESS(status)) return status; - filterDevObj->Flags |= DO_BUFFERED_IO; + NTSTATUS status; + PDEVICE_OBJECT devObj; + PDEVICE_OBJECT filterDevObj; + PDEVICE_OBJECT attachedDevObj; + DetourDeviceExtension *detourDevExt; + FilterDeviceExtension *filterDevExt; + ULONG i; + + DEBUG_LOG(("attach to device: %x", kbdClassDevObj)); + DEBUG_LOG(("type of device: %x", kbdClassDevObj->DeviceType)); + DEBUG_LOG(("name of driver: %T", &(kbdClassDevObj->DriverObject->DriverName))); + + // create filter device + status = IoCreateDevice(driverObject, sizeof(FilterDeviceExtension), + NULL, FILE_DEVICE_KEYBOARD, + 0, FALSE, &filterDevObj); + DEBUG_LOG(("add filter device: %x", filterDevObj)); + DEBUG_LOGChain(driverObject); + if (!NT_SUCCESS(status)) return status; + filterDevObj->Flags |= DO_BUFFERED_IO; #ifndef MAYUD_NT4 - filterDevObj->Flags |= DO_POWER_PAGABLE; + filterDevObj->Flags |= DO_POWER_PAGABLE; #endif // !MAYUD_NT4 - // initialize filter device extension - filterDevExt = (FilterDeviceExtension*)filterDevObj->DeviceExtension; - RtlZeroMemory(filterDevExt, sizeof(FilterDeviceExtension)); + // initialize filter device extension + filterDevExt = (FilterDeviceExtension*)filterDevObj->DeviceExtension; + RtlZeroMemory(filterDevExt, sizeof(FilterDeviceExtension)); - KeInitializeSpinLock(&filterDevExt->lock); - filterDevExt->irpq = NULL; - status = KqInitialize(&filterDevExt->readQue); - if (!NT_SUCCESS(status)) goto error; + KeInitializeSpinLock(&filterDevExt->lock); + filterDevExt->irpq = NULL; + status = KqInitialize(&filterDevExt->readQue); + if (!NT_SUCCESS(status)) goto error; #ifdef USE_TOUCHPAD - filterDevExt->isKeyboard = FALSE; - filterDevExt->isTouched = FALSE; + filterDevExt->isKeyboard = FALSE; + filterDevExt->isTouched = FALSE; #endif - attachedDevObj = kbdClassDevObj->AttachedDevice; - while (attachedDevObj) - { - DEBUG_LOG(("attached to %T", &(attachedDevObj->DriverObject->DriverName))); - DEBUG_LOG(("type of attched device: %x", attachedDevObj->DeviceType)); + attachedDevObj = kbdClassDevObj->AttachedDevice; + while (attachedDevObj) { + DEBUG_LOG(("attached to %T", &(attachedDevObj->DriverObject->DriverName))); + DEBUG_LOG(("type of attched device: %x", attachedDevObj->DeviceType)); #ifdef USE_TOUCHPAD - if (RtlCompareUnicodeString(&KeyboardClassDriverName, &attachedDevObj->DriverObject->DriverName, TRUE) == 0) - filterDevExt->isKeyboard = TRUE; + if (RtlCompareUnicodeString(&KeyboardClassDriverName, &attachedDevObj->DriverObject->DriverName, TRUE) == 0) + filterDevExt->isKeyboard = TRUE; #endif - attachedDevObj = attachedDevObj->AttachedDevice; - } - - devObj = filterDevObj->NextDevice; - while (devObj->NextDevice) { - devObj = devObj->NextDevice; - } - filterDevExt->detourDevObj = devObj; - detourDevExt = (DetourDeviceExtension*)devObj->DeviceExtension; - if (!detourDevExt->filterDevObj) { - detourDevExt->filterDevObj = filterDevObj; - } - - filterDevExt->kbdClassDevObj = - IoAttachDeviceToDeviceStack(filterDevObj, kbdClassDevObj); - if (!filterDevExt->kbdClassDevObj) goto error; - - for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++) { - filterDevExt->MajorFunction[i] = - (filterDevExt->kbdClassDevObj->DriverObject->MajorFunction[i] - == _IopInvalidDeviceRequest) ? - _IopInvalidDeviceRequest : filterPassThrough; - } + attachedDevObj = attachedDevObj->AttachedDevice; + } + + devObj = filterDevObj->NextDevice; + while (devObj->NextDevice) { + devObj = devObj->NextDevice; + } + filterDevExt->detourDevObj = devObj; + detourDevExt = (DetourDeviceExtension*)devObj->DeviceExtension; + if (!detourDevExt->filterDevObj) { + detourDevExt->filterDevObj = filterDevObj; + } + + filterDevExt->kbdClassDevObj = + IoAttachDeviceToDeviceStack(filterDevObj, kbdClassDevObj); + if (!filterDevExt->kbdClassDevObj) goto error; + + for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++) { + filterDevExt->MajorFunction[i] = + (filterDevExt->kbdClassDevObj->DriverObject->MajorFunction[i] + == _IopInvalidDeviceRequest) ? + _IopInvalidDeviceRequest : filterPassThrough; + } #ifdef USE_TOUCHPAD - if (filterDevExt->isKeyboard == FALSE) - { - DEBUG_LOG(("filter read: GlidePoint")); - filterDevObj->DeviceType = FILE_DEVICE_MOUSE; - filterDevExt->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = filterTouchpad; - } - else + if (filterDevExt->isKeyboard == FALSE) { + DEBUG_LOG(("filter read: GlidePoint")); + filterDevObj->DeviceType = FILE_DEVICE_MOUSE; + filterDevExt->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = filterTouchpad; + } else #endif - { - DEBUG_LOG(("filter read: Keyboard")); - filterDevExt->MajorFunction[IRP_MJ_READ] = filterRead; - } + { + DEBUG_LOG(("filter read: Keyboard")); + filterDevExt->MajorFunction[IRP_MJ_READ] = filterRead; + } #ifndef MAYUD_NT4 - filterDevExt->MajorFunction[IRP_MJ_POWER] = filterPower; + filterDevExt->MajorFunction[IRP_MJ_POWER] = filterPower; #endif // !MAYUD_NT4 - if (g_isPnP == TRUE) { - filterDevExt->MajorFunction[IRP_MJ_PNP] = filterPnP; - } - filterDevObj->Flags &= ~DO_DEVICE_INITIALIZING; - - return STATUS_SUCCESS; - - error: - DEBUG_LOG(("mayuAddDevice: error")); - if (filterDevObj) { - KqFinalize(&filterDevExt->readQue); - IoDeleteDevice(filterDevObj); - } - return status; + if (g_isPnP == TRUE) { + filterDevExt->MajorFunction[IRP_MJ_PNP] = filterPnP; + } + filterDevObj->Flags &= ~DO_DEVICE_INITIALIZING; + + return STATUS_SUCCESS; + +error: + DEBUG_LOG(("mayuAddDevice: error")); + if (filterDevObj) { + KqFinalize(&filterDevExt->readQue); + IoDeleteDevice(filterDevObj); + } + return status; } BOOLEAN CancelKeyboardClassRead(PIRP cancelIrp, PDEVICE_OBJECT kbdClassDevObj) { - PVOID kbdClassDevExt; - BOOLEAN isSafe; - PKSPIN_LOCK SpinLock; - KIRQL currentIrql; - - kbdClassDevExt = kbdClassDevObj->DeviceExtension; - SpinLock = (PKSPIN_LOCK)((ULONG)kbdClassDevExt + g_SpinLock_offset); - KeAcquireSpinLock(SpinLock, ¤tIrql); - if (g_isXp == TRUE) { - isSafe = cancelIrp->CancelRoutine ? TRUE : FALSE; - } else { - isSafe = *(BOOLEAN*)((ULONG)kbdClassDevExt + g_RequestIsPending_offset); - } - if (isSafe == TRUE) { - KeReleaseSpinLock(SpinLock, currentIrql); - IoCancelIrp(cancelIrp); - } else { - DEBUG_LOG(("cancel irp not pending")); - KeReleaseSpinLock(SpinLock, currentIrql); - } - return isSafe; + PVOID kbdClassDevExt; + BOOLEAN isSafe; + PKSPIN_LOCK SpinLock; + KIRQL currentIrql; + + kbdClassDevExt = kbdClassDevObj->DeviceExtension; + SpinLock = (PKSPIN_LOCK)((ULONG)kbdClassDevExt + g_SpinLock_offset); + KeAcquireSpinLock(SpinLock, ¤tIrql); + if (g_isXp == TRUE) { + isSafe = cancelIrp->CancelRoutine ? TRUE : FALSE; + } else { + isSafe = *(BOOLEAN*)((ULONG)kbdClassDevExt + g_RequestIsPending_offset); + } + if (isSafe == TRUE) { + KeReleaseSpinLock(SpinLock, currentIrql); + IoCancelIrp(cancelIrp); + } else { + DEBUG_LOG(("cancel irp not pending")); + KeReleaseSpinLock(SpinLock, currentIrql); + } + return isSafe; } // unload driver VOID mayuUnloadDriver(IN PDRIVER_OBJECT driverObject) { - KIRQL currentIrql; - PIRP cancelIrp; - PDEVICE_OBJECT devObj; - DetourDeviceExtension *detourDevExt; - - // walk on device chain(the last one is detour device?) - devObj = driverObject->DeviceObject; - while (devObj->NextDevice) { - FilterDeviceExtension *filterDevExt - = (FilterDeviceExtension*)devObj->DeviceExtension; - PDEVICE_OBJECT delObj; - PDEVICE_OBJECT kbdClassDevObj; - - // detach - IoDetachDevice(filterDevExt->kbdClassDevObj); - // cancel filter IRP_MJ_READ - KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); - // TODO: at this point, the irp may be completed (but what can I do for it ?) - // finalize read que - KqFinalize(&filterDevExt->readQue); - cancelIrp = filterDevExt->irpq; - filterDevExt->irpq = NULL; - kbdClassDevObj = filterDevExt->kbdClassDevObj; - KeReleaseSpinLock(&filterDevExt->lock, currentIrql); - if (cancelIrp) { - while (CancelKeyboardClassRead(cancelIrp, kbdClassDevObj) != TRUE); - } - // delete device objects - delObj= devObj; - devObj = devObj->NextDevice; - IoDeleteDevice(delObj); - } - - detourDevExt = (DetourDeviceExtension*)devObj->DeviceExtension; - // cancel filter IRP_MJ_READ - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - // TODO: at this point, the irp may be completed (but what can I do for it ?) - cancelIrp = detourDevExt->irpq; - // finalize read que - KqFinalize(&detourDevExt->readQue); - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - if (cancelIrp) - IoCancelIrp(cancelIrp); - // delete device objects - IoDeleteDevice(devObj); - - // delete symbolic link - IoDeleteSymbolicLink(&MayuDetourWin32DeviceName); - DEBUG_LOG_TERM(()); + KIRQL currentIrql; + PIRP cancelIrp; + PDEVICE_OBJECT devObj; + DetourDeviceExtension *detourDevExt; + + // walk on device chain(the last one is detour device?) + devObj = driverObject->DeviceObject; + while (devObj->NextDevice) { + FilterDeviceExtension *filterDevExt + = (FilterDeviceExtension*)devObj->DeviceExtension; + PDEVICE_OBJECT delObj; + PDEVICE_OBJECT kbdClassDevObj; + + // detach + IoDetachDevice(filterDevExt->kbdClassDevObj); + // cancel filter IRP_MJ_READ + KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); + // TODO: at this point, the irp may be completed (but what can I do for it ?) + // finalize read que + KqFinalize(&filterDevExt->readQue); + cancelIrp = filterDevExt->irpq; + filterDevExt->irpq = NULL; + kbdClassDevObj = filterDevExt->kbdClassDevObj; + KeReleaseSpinLock(&filterDevExt->lock, currentIrql); + if (cancelIrp) { + while (CancelKeyboardClassRead(cancelIrp, kbdClassDevObj) != TRUE); + } + // delete device objects + delObj= devObj; + devObj = devObj->NextDevice; + IoDeleteDevice(delObj); + } + + detourDevExt = (DetourDeviceExtension*)devObj->DeviceExtension; + // cancel filter IRP_MJ_READ + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + // TODO: at this point, the irp may be completed (but what can I do for it ?) + cancelIrp = detourDevExt->irpq; + // finalize read que + KqFinalize(&detourDevExt->readQue); + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + if (cancelIrp) + IoCancelIrp(cancelIrp); + // delete device objects + IoDeleteDevice(devObj); + + // delete symbolic link + IoDeleteSymbolicLink(&MayuDetourWin32DeviceName); + DEBUG_LOG_TERM(()); } @@ -511,147 +501,141 @@ VOID mayuUnloadDriver(IN PDRIVER_OBJECT driverObject) // detour read cancel VOID mayuDetourReadCancel(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - DetourDeviceExtension *devExt = - (DetourDeviceExtension *)deviceObject->DeviceExtension; - KIRQL currentIrql; - - KeAcquireSpinLock(&devExt->lock, ¤tIrql); - devExt->irpq = NULL; - KeReleaseSpinLock(&devExt->lock, currentIrql); - IoReleaseCancelSpinLock(irp->CancelIrql); - DEBUG_LOG(("detourReadCancel:")); + DetourDeviceExtension *devExt = + (DetourDeviceExtension *)deviceObject->DeviceExtension; + KIRQL currentIrql; + + KeAcquireSpinLock(&devExt->lock, ¤tIrql); + devExt->irpq = NULL; + KeReleaseSpinLock(&devExt->lock, currentIrql); + IoReleaseCancelSpinLock(irp->CancelIrql); + DEBUG_LOG(("detourReadCancel:")); #if 0 - KeAcquireSpinLock(&devExt->lock, ¤tIrql); - if (devExt->irpq && irp == deviceObject->CurrentIrp) - // the current request is being cancelled - { - deviceObject->CurrentIrp = NULL; - devExt->irpq = NULL; - KeReleaseSpinLock(&devExt->lock, currentIrql); - IoStartNextPacket(deviceObject, TRUE); - } - else - { - // Cancel a request in the device queue - KIRQL cancelIrql; - - IoAcquireCancelSpinLock(&cancelIrql); - KeRemoveEntryDeviceQueue(&deviceObject->DeviceQueue, - &irp->Tail.Overlay.DeviceQueueEntry); - IoReleaseCancelSpinLock(cancelIrql); - KeReleaseSpinLock(&devExt->lock, currentIrql); - } + KeAcquireSpinLock(&devExt->lock, ¤tIrql); + if (devExt->irpq && irp == deviceObject->CurrentIrp) + // the current request is being cancelled + { + deviceObject->CurrentIrp = NULL; + devExt->irpq = NULL; + KeReleaseSpinLock(&devExt->lock, currentIrql); + IoStartNextPacket(deviceObject, TRUE); + } else { + // Cancel a request in the device queue + KIRQL cancelIrql; + + IoAcquireCancelSpinLock(&cancelIrql); + KeRemoveEntryDeviceQueue(&deviceObject->DeviceQueue, + &irp->Tail.Overlay.DeviceQueueEntry); + IoReleaseCancelSpinLock(cancelIrql); + KeReleaseSpinLock(&devExt->lock, currentIrql); + } #endif - - irp->IoStatus.Status = STATUS_CANCELLED; - irp->IoStatus.Information = 0; - IoCompleteRequest(irp, IO_KEYBOARD_INCREMENT); + + irp->IoStatus.Status = STATUS_CANCELLED; + irp->IoStatus.Information = 0; + IoCompleteRequest(irp, IO_KEYBOARD_INCREMENT); } /////////////////////////////////////////////////////////////////////////////// // Complete Functions -// +// NTSTATUS filterGenericCompletion(IN PDEVICE_OBJECT deviceObject, - IN PIRP irp, IN PVOID context) + IN PIRP irp, IN PVOID context) { - UNREFERENCED_PARAMETER(deviceObject); - UNREFERENCED_PARAMETER(context); - - if (irp->PendingReturned) - IoMarkIrpPending(irp); - return STATUS_SUCCESS; + UNREFERENCED_PARAMETER(deviceObject); + UNREFERENCED_PARAMETER(context); + + if (irp->PendingReturned) + IoMarkIrpPending(irp); + return STATUS_SUCCESS; } -// +// NTSTATUS filterReadCompletion(IN PDEVICE_OBJECT deviceObject, - IN PIRP irp, IN PVOID context) + IN PIRP irp, IN PVOID context) { - NTSTATUS status; - KIRQL currentIrql, cancelIrql; - PIRP irpCancel = NULL; - FilterDeviceExtension *filterDevExt = - (FilterDeviceExtension*)deviceObject->DeviceExtension; - PDEVICE_OBJECT detourDevObj = filterDevExt->detourDevObj; - DetourDeviceExtension *detourDevExt = - (DetourDeviceExtension*)detourDevObj->DeviceExtension; - - UNREFERENCED_PARAMETER(context); - - KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); - filterDevExt->irpq = NULL; - KeReleaseSpinLock(&filterDevExt->lock, currentIrql); - if (irp->PendingReturned) { - status = STATUS_PENDING; - IoMarkIrpPending(irp); - } else { - status = STATUS_SUCCESS; - } - - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - if (detourDevExt->isOpen && !detourDevExt->wasCleanupInitiated) - { - // if detour is opened, key datum are forwarded to detour - if (irp->IoStatus.Status == STATUS_SUCCESS) - { - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); - - KqEnque(&detourDevExt->readQue, - (KEYBOARD_INPUT_DATA *)irp->AssociatedIrp.SystemBuffer, - irp->IoStatus.Information / sizeof(KEYBOARD_INPUT_DATA)); - - irp->IoStatus.Status = STATUS_CANCELLED; - irp->IoStatus.Information = 0; - detourDevExt->filterDevObj = deviceObject; - } - - IoAcquireCancelSpinLock(&cancelIrql); - if (detourDevExt->irpq) { - if (readq(&detourDevExt->readQue, detourDevExt->irpq) == - STATUS_SUCCESS) { - IoSetCancelRoutine(detourDevExt->irpq, NULL); - IoCompleteRequest(detourDevExt->irpq, IO_KEYBOARD_INCREMENT); - detourDevExt->irpq = NULL; - } - } - IoReleaseCancelSpinLock(cancelIrql); - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - - KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); - status = readq(&filterDevExt->readQue, irp); - KeReleaseSpinLock(&filterDevExt->lock, currentIrql); - } - else - { - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - } - - if (status == STATUS_SUCCESS) - irp->IoStatus.Status = STATUS_SUCCESS; - return irp->IoStatus.Status; + NTSTATUS status; + KIRQL currentIrql, cancelIrql; + PIRP irpCancel = NULL; + FilterDeviceExtension *filterDevExt = + (FilterDeviceExtension*)deviceObject->DeviceExtension; + PDEVICE_OBJECT detourDevObj = filterDevExt->detourDevObj; + DetourDeviceExtension *detourDevExt = + (DetourDeviceExtension*)detourDevObj->DeviceExtension; + + UNREFERENCED_PARAMETER(context); + + KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); + filterDevExt->irpq = NULL; + KeReleaseSpinLock(&filterDevExt->lock, currentIrql); + if (irp->PendingReturned) { + status = STATUS_PENDING; + IoMarkIrpPending(irp); + } else { + status = STATUS_SUCCESS; + } + + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + if (detourDevExt->isOpen && !detourDevExt->wasCleanupInitiated) { + // if detour is opened, key datum are forwarded to detour + if (irp->IoStatus.Status == STATUS_SUCCESS) { + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); + + KqEnque(&detourDevExt->readQue, + (KEYBOARD_INPUT_DATA *)irp->AssociatedIrp.SystemBuffer, + irp->IoStatus.Information / sizeof(KEYBOARD_INPUT_DATA)); + + irp->IoStatus.Status = STATUS_CANCELLED; + irp->IoStatus.Information = 0; + detourDevExt->filterDevObj = deviceObject; + } + + IoAcquireCancelSpinLock(&cancelIrql); + if (detourDevExt->irpq) { + if (readq(&detourDevExt->readQue, detourDevExt->irpq) == + STATUS_SUCCESS) { + IoSetCancelRoutine(detourDevExt->irpq, NULL); + IoCompleteRequest(detourDevExt->irpq, IO_KEYBOARD_INCREMENT); + detourDevExt->irpq = NULL; + } + } + IoReleaseCancelSpinLock(cancelIrql); + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + + KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); + status = readq(&filterDevExt->readQue, irp); + KeReleaseSpinLock(&filterDevExt->lock, currentIrql); + } else { + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + } + + if (status == STATUS_SUCCESS) + irp->IoStatus.Status = STATUS_SUCCESS; + return irp->IoStatus.Status; } NTSTATUS readq(KeyQue *readQue, PIRP irp) { - if (!KqIsEmpty(readQue)) { - PIO_STACK_LOCATION irpSp; - ULONG len; - - irpSp = IoGetCurrentIrpStackLocation(irp); - len = KqDeque(readQue, - (KEYBOARD_INPUT_DATA *)irp->AssociatedIrp.SystemBuffer, - irpSp->Parameters.Read.Length / sizeof(KEYBOARD_INPUT_DATA)); - irp->IoStatus.Status = STATUS_SUCCESS; - irp->IoStatus.Information = len * sizeof(KEYBOARD_INPUT_DATA); - irpSp->Parameters.Read.Length = irp->IoStatus.Information; - return STATUS_SUCCESS; - } else { - irp->IoStatus.Status = STATUS_PENDING; - irp->IoStatus.Information = 0; - return STATUS_PENDING; - } + if (!KqIsEmpty(readQue)) { + PIO_STACK_LOCATION irpSp; + ULONG len; + + irpSp = IoGetCurrentIrpStackLocation(irp); + len = KqDeque(readQue, + (KEYBOARD_INPUT_DATA *)irp->AssociatedIrp.SystemBuffer, + irpSp->Parameters.Read.Length / sizeof(KEYBOARD_INPUT_DATA)); + irp->IoStatus.Status = STATUS_SUCCESS; + irp->IoStatus.Information = len * sizeof(KEYBOARD_INPUT_DATA); + irpSp->Parameters.Read.Length = irp->IoStatus.Information; + return STATUS_SUCCESS; + } else { + irp->IoStatus.Status = STATUS_PENDING; + irp->IoStatus.Information = 0; + return STATUS_PENDING; + } } /////////////////////////////////////////////////////////////////////////////// @@ -661,317 +645,306 @@ NTSTATUS readq(KeyQue *readQue, PIRP irp) // Generic Dispatcher NTSTATUS mayuGenericDispatch(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); - if (deviceObject->NextDevice) { - FilterDeviceExtension *filterDevExt = - (FilterDeviceExtension *)deviceObject->DeviceExtension; + if (deviceObject->NextDevice) { + FilterDeviceExtension *filterDevExt = + (FilterDeviceExtension *)deviceObject->DeviceExtension; #ifdef USE_TOUCHPAD - if (filterDevExt->isKeyboard == FALSE) - { - DEBUG_LOG(("MajorFunction: %x", irpSp->MajorFunction)); - } + if (filterDevExt->isKeyboard == FALSE) { + DEBUG_LOG(("MajorFunction: %x", irpSp->MajorFunction)); + } #endif - return filterDevExt->MajorFunction[irpSp->MajorFunction](deviceObject, irp); - } else { - DetourDeviceExtension *detourDevExt = - (DetourDeviceExtension *)deviceObject->DeviceExtension; + return filterDevExt->MajorFunction[irpSp->MajorFunction](deviceObject, irp); + } else { + DetourDeviceExtension *detourDevExt = + (DetourDeviceExtension *)deviceObject->DeviceExtension; - return detourDevExt->MajorFunction[irpSp->MajorFunction](deviceObject, irp); - } + return detourDevExt->MajorFunction[irpSp->MajorFunction](deviceObject, irp); + } } // detour IRP_MJ_CREATE NTSTATUS detourCreate(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - DetourDeviceExtension *detourDevExt = - (DetourDeviceExtension*)deviceObject->DeviceExtension; - - if (1 < InterlockedIncrement(&detourDevExt->isOpen)) - // mayu detour device can be opend only once at a time - { - InterlockedDecrement(&detourDevExt->isOpen); - irp->IoStatus.Status = STATUS_INTERNAL_ERROR; - } - else - { - PIRP irpCancel; - KIRQL currentIrql; - PDEVICE_OBJECT filterDevObj; - - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - detourDevExt->wasCleanupInitiated = FALSE; - KqClear(&detourDevExt->readQue); - filterDevObj = detourDevExt->filterDevObj; - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - if (filterDevObj) { - FilterDeviceExtension *filterDevExt = - (FilterDeviceExtension*)filterDevObj->DeviceExtension; - PDEVICE_OBJECT kbdClassDevObj; - - KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); - irpCancel = filterDevExt->kbdClassDevObj->CurrentIrp; - kbdClassDevObj = filterDevExt->kbdClassDevObj; - KeReleaseSpinLock(&filterDevExt->lock, currentIrql); - if (irpCancel) { - CancelKeyboardClassRead(irpCancel, kbdClassDevObj); - } - } - - irp->IoStatus.Status = STATUS_SUCCESS; - } - irp->IoStatus.Information = 0; - IoCompleteRequest(irp, IO_NO_INCREMENT); - return irp->IoStatus.Status; + DetourDeviceExtension *detourDevExt = + (DetourDeviceExtension*)deviceObject->DeviceExtension; + + if (1 < InterlockedIncrement(&detourDevExt->isOpen)) + // mayu detour device can be opend only once at a time + { + InterlockedDecrement(&detourDevExt->isOpen); + irp->IoStatus.Status = STATUS_INTERNAL_ERROR; + } else { + PIRP irpCancel; + KIRQL currentIrql; + PDEVICE_OBJECT filterDevObj; + + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + detourDevExt->wasCleanupInitiated = FALSE; + KqClear(&detourDevExt->readQue); + filterDevObj = detourDevExt->filterDevObj; + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + if (filterDevObj) { + FilterDeviceExtension *filterDevExt = + (FilterDeviceExtension*)filterDevObj->DeviceExtension; + PDEVICE_OBJECT kbdClassDevObj; + + KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); + irpCancel = filterDevExt->kbdClassDevObj->CurrentIrp; + kbdClassDevObj = filterDevExt->kbdClassDevObj; + KeReleaseSpinLock(&filterDevExt->lock, currentIrql); + if (irpCancel) { + CancelKeyboardClassRead(irpCancel, kbdClassDevObj); + } + } + + irp->IoStatus.Status = STATUS_SUCCESS; + } + irp->IoStatus.Information = 0; + IoCompleteRequest(irp, IO_NO_INCREMENT); + return irp->IoStatus.Status; } // detour IRP_MJ_CLOSE NTSTATUS detourClose(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - DetourDeviceExtension *detourDevExt = - (DetourDeviceExtension*)deviceObject->DeviceExtension; - KIRQL currentIrql; - - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - InterlockedDecrement(&detourDevExt->isOpen); - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - irp->IoStatus.Status = STATUS_SUCCESS; - irp->IoStatus.Information = 0; - IoCompleteRequest(irp, IO_NO_INCREMENT); - DEBUG_LOG_TERM(()); - return STATUS_SUCCESS; + DetourDeviceExtension *detourDevExt = + (DetourDeviceExtension*)deviceObject->DeviceExtension; + KIRQL currentIrql; + + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + InterlockedDecrement(&detourDevExt->isOpen); + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + irp->IoStatus.Status = STATUS_SUCCESS; + irp->IoStatus.Information = 0; + IoCompleteRequest(irp, IO_NO_INCREMENT); + DEBUG_LOG_TERM(()); + return STATUS_SUCCESS; } // detour IRP_MJ_READ NTSTATUS detourRead(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - NTSTATUS status; - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); - DetourDeviceExtension *detourDevExt = - (DetourDeviceExtension*)deviceObject->DeviceExtension; - KIRQL currentIrql, cancelIrql; - - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - if (irpSp->Parameters.Read.Length == 0) - status = STATUS_SUCCESS; - else if (irpSp->Parameters.Read.Length % sizeof(KEYBOARD_INPUT_DATA)) - status = STATUS_BUFFER_TOO_SMALL; - else - status = readq(&detourDevExt->readQue, irp); - if (status == STATUS_PENDING) { - IoAcquireCancelSpinLock(&cancelIrql); - IoMarkIrpPending(irp); - detourDevExt->irpq = irp; - IoSetCancelRoutine(irp, mayuDetourReadCancel); - IoReleaseCancelSpinLock(cancelIrql); - } - else { - IoCompleteRequest(irp, IO_KEYBOARD_INCREMENT); - } - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - return status; + NTSTATUS status; + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); + DetourDeviceExtension *detourDevExt = + (DetourDeviceExtension*)deviceObject->DeviceExtension; + KIRQL currentIrql, cancelIrql; + + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + if (irpSp->Parameters.Read.Length == 0) + status = STATUS_SUCCESS; + else if (irpSp->Parameters.Read.Length % sizeof(KEYBOARD_INPUT_DATA)) + status = STATUS_BUFFER_TOO_SMALL; + else + status = readq(&detourDevExt->readQue, irp); + if (status == STATUS_PENDING) { + IoAcquireCancelSpinLock(&cancelIrql); + IoMarkIrpPending(irp); + detourDevExt->irpq = irp; + IoSetCancelRoutine(irp, mayuDetourReadCancel); + IoReleaseCancelSpinLock(cancelIrql); + } else { + IoCompleteRequest(irp, IO_KEYBOARD_INCREMENT); + } + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + return status; } // detour IRP_MJ_WRITE NTSTATUS detourWrite(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - NTSTATUS status; - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); - ULONG len = irpSp->Parameters.Write.Length; - DetourDeviceExtension *detourDevExt = - (DetourDeviceExtension*)deviceObject->DeviceExtension; - - irp->IoStatus.Information = 0; - if (len == 0) - status = STATUS_SUCCESS; - else if (len % sizeof(KEYBOARD_INPUT_DATA)) - status = STATUS_INVALID_PARAMETER; - else { - // write to filter que - KIRQL cancelIrql, currentIrql; - PIRP irpCancel; - PDEVICE_OBJECT filterDevObj; - - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - filterDevObj = detourDevExt->filterDevObj; - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - // enque filter que - if (filterDevObj) { - FilterDeviceExtension *filterDevExt = - (FilterDeviceExtension*)filterDevObj->DeviceExtension; - PDEVICE_OBJECT kbdClassDevObj; - - KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); - - len /= sizeof(KEYBOARD_INPUT_DATA); - len = KqEnque(&filterDevExt->readQue, - (KEYBOARD_INPUT_DATA *)irp->AssociatedIrp.SystemBuffer, - len); - irp->IoStatus.Information = len * sizeof(KEYBOARD_INPUT_DATA); - irpSp->Parameters.Write.Length = irp->IoStatus.Information; - // cancel filter irp - irpCancel = filterDevExt->irpq; - filterDevExt->irpq = NULL; - kbdClassDevObj = filterDevExt->kbdClassDevObj; - KeReleaseSpinLock(&filterDevExt->lock, currentIrql); - if (irpCancel) { - CancelKeyboardClassRead(irpCancel, kbdClassDevObj); - } - status = STATUS_SUCCESS; - } else { - irp->IoStatus.Information = 0; - irpSp->Parameters.Write.Length = irp->IoStatus.Information; - status = STATUS_CANCELLED; - } - } - IoCompleteRequest(irp, IO_NO_INCREMENT); - return status; + NTSTATUS status; + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); + ULONG len = irpSp->Parameters.Write.Length; + DetourDeviceExtension *detourDevExt = + (DetourDeviceExtension*)deviceObject->DeviceExtension; + + irp->IoStatus.Information = 0; + if (len == 0) + status = STATUS_SUCCESS; + else if (len % sizeof(KEYBOARD_INPUT_DATA)) + status = STATUS_INVALID_PARAMETER; + else { + // write to filter que + KIRQL cancelIrql, currentIrql; + PIRP irpCancel; + PDEVICE_OBJECT filterDevObj; + + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + filterDevObj = detourDevExt->filterDevObj; + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + // enque filter que + if (filterDevObj) { + FilterDeviceExtension *filterDevExt = + (FilterDeviceExtension*)filterDevObj->DeviceExtension; + PDEVICE_OBJECT kbdClassDevObj; + + KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); + + len /= sizeof(KEYBOARD_INPUT_DATA); + len = KqEnque(&filterDevExt->readQue, + (KEYBOARD_INPUT_DATA *)irp->AssociatedIrp.SystemBuffer, + len); + irp->IoStatus.Information = len * sizeof(KEYBOARD_INPUT_DATA); + irpSp->Parameters.Write.Length = irp->IoStatus.Information; + // cancel filter irp + irpCancel = filterDevExt->irpq; + filterDevExt->irpq = NULL; + kbdClassDevObj = filterDevExt->kbdClassDevObj; + KeReleaseSpinLock(&filterDevExt->lock, currentIrql); + if (irpCancel) { + CancelKeyboardClassRead(irpCancel, kbdClassDevObj); + } + status = STATUS_SUCCESS; + } else { + irp->IoStatus.Information = 0; + irpSp->Parameters.Write.Length = irp->IoStatus.Information; + status = STATUS_CANCELLED; + } + } + IoCompleteRequest(irp, IO_NO_INCREMENT); + return status; } // detour IRP_MJ_CLEANUP NTSTATUS detourCleanup(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - KIRQL currentIrql, cancelIrql; - PIO_STACK_LOCATION irpSp; - PIRP currentIrp = NULL, irpCancel; - DetourDeviceExtension *detourDevExt = - (DetourDeviceExtension*)deviceObject->DeviceExtension; - - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - IoAcquireCancelSpinLock(&cancelIrql); - irpSp = IoGetCurrentIrpStackLocation(irp); - detourDevExt->wasCleanupInitiated = TRUE; - - // Complete all requests queued by this thread with STATUS_CANCELLED - currentIrp = deviceObject->CurrentIrp; - deviceObject->CurrentIrp = NULL; - detourDevExt->irpq = NULL; - - while (currentIrp != NULL) - { - IoSetCancelRoutine(currentIrp, NULL); - currentIrp->IoStatus.Status = STATUS_CANCELLED; - currentIrp->IoStatus.Information = 0; - - IoReleaseCancelSpinLock(cancelIrql); - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - IoCompleteRequest(currentIrp, IO_NO_INCREMENT); - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - IoAcquireCancelSpinLock(&cancelIrql); - - // Dequeue the next packet (IRP) from the device work queue. - { - PKDEVICE_QUEUE_ENTRY packet = - KeRemoveDeviceQueue(&deviceObject->DeviceQueue); - currentIrp = packet ? - CONTAINING_RECORD(packet, IRP, Tail.Overlay.DeviceQueueEntry) : NULL; - } - } - - IoReleaseCancelSpinLock(cancelIrql); - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - - // Complete the cleanup request with STATUS_SUCCESS. - irp->IoStatus.Status = STATUS_SUCCESS; - irp->IoStatus.Information = 0; - IoCompleteRequest(irp, IO_NO_INCREMENT); - - return STATUS_SUCCESS; + KIRQL currentIrql, cancelIrql; + PIO_STACK_LOCATION irpSp; + PIRP currentIrp = NULL, irpCancel; + DetourDeviceExtension *detourDevExt = + (DetourDeviceExtension*)deviceObject->DeviceExtension; + + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + IoAcquireCancelSpinLock(&cancelIrql); + irpSp = IoGetCurrentIrpStackLocation(irp); + detourDevExt->wasCleanupInitiated = TRUE; + + // Complete all requests queued by this thread with STATUS_CANCELLED + currentIrp = deviceObject->CurrentIrp; + deviceObject->CurrentIrp = NULL; + detourDevExt->irpq = NULL; + + while (currentIrp != NULL) { + IoSetCancelRoutine(currentIrp, NULL); + currentIrp->IoStatus.Status = STATUS_CANCELLED; + currentIrp->IoStatus.Information = 0; + + IoReleaseCancelSpinLock(cancelIrql); + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + IoCompleteRequest(currentIrp, IO_NO_INCREMENT); + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + IoAcquireCancelSpinLock(&cancelIrql); + + // Dequeue the next packet (IRP) from the device work queue. + { + PKDEVICE_QUEUE_ENTRY packet = + KeRemoveDeviceQueue(&deviceObject->DeviceQueue); + currentIrp = packet ? + CONTAINING_RECORD(packet, IRP, Tail.Overlay.DeviceQueueEntry) : NULL; + } + } + + IoReleaseCancelSpinLock(cancelIrql); + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + + // Complete the cleanup request with STATUS_SUCCESS. + irp->IoStatus.Status = STATUS_SUCCESS; + irp->IoStatus.Information = 0; + IoCompleteRequest(irp, IO_NO_INCREMENT); + + return STATUS_SUCCESS; } // detour IRP_MJ_DEVICE_CONTROL NTSTATUS detourDeviceControl(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - NTSTATUS status; - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); - DetourDeviceExtension *detourDevExt = - (DetourDeviceExtension*)deviceObject->DeviceExtension; - - irp->IoStatus.Information = 0; - if (irpSp->Parameters.DeviceIoControl.IoControlCode != IOCTL_MAYU_GET_LOG) DEBUG_LOG(("DeviceIoControl: %x", irpSp->Parameters.DeviceIoControl.IoControlCode)); - status = STATUS_INVALID_DEVICE_REQUEST; - switch (irpSp->Parameters.DeviceIoControl.IoControlCode) - { - case IOCTL_MAYU_DETOUR_CANCEL: - { - KIRQL currentIrql; - PIRP irpCancel = NULL; - - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - if (detourDevExt->isOpen) - irpCancel = detourDevExt->irpq; - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - - if (irpCancel) - IoCancelIrp(irpCancel);// at this point, the irpCancel may be completed - status = STATUS_SUCCESS; - break; - } - case IOCTL_MAYU_GET_VERSION: - { - if (irpSp->Parameters.DeviceIoControl.OutputBufferLength < - MayuDriverVersion.Length) - { - status = STATUS_INVALID_PARAMETER; - break; - } - RtlCopyMemory(irp->AssociatedIrp.SystemBuffer, - MayuDriverVersion.Buffer, MayuDriverVersion.Length); - irp->IoStatus.Information = MayuDriverVersion.Length; - DEBUG_LOG(("Version: %T", &MayuDriverVersion)); - status = STATUS_SUCCESS; - break; - } - case IOCTL_MAYU_GET_LOG: - status = DEBUG_LOG_RETRIEVE((irp)); - break; - case IOCTL_MAYU_FORCE_KEYBOARD_INPUT: - { - KIRQL currentIrql, cancelIrql; - - // if detour is opened, key datum are forwarded to detour - if (irpSp->Parameters.DeviceIoControl.InputBufferLength % - sizeof(KEYBOARD_INPUT_DATA)) - { - status = STATUS_INVALID_PARAMETER; - break; - } - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - KqEnque(&detourDevExt->readQue, - (KEYBOARD_INPUT_DATA *)irp->AssociatedIrp.SystemBuffer, - irpSp->Parameters.DeviceIoControl.InputBufferLength - / sizeof(KEYBOARD_INPUT_DATA)); - - if (detourDevExt->irpq) { - if (readq(&detourDevExt->readQue, detourDevExt->irpq) == - STATUS_SUCCESS) { - IoAcquireCancelSpinLock(&cancelIrql); - IoSetCancelRoutine(detourDevExt->irpq, NULL); - IoReleaseCancelSpinLock(cancelIrql); - IoCompleteRequest(detourDevExt->irpq, IO_KEYBOARD_INCREMENT); - detourDevExt->irpq = NULL; + NTSTATUS status; + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); + DetourDeviceExtension *detourDevExt = + (DetourDeviceExtension*)deviceObject->DeviceExtension; + + irp->IoStatus.Information = 0; + if (irpSp->Parameters.DeviceIoControl.IoControlCode != IOCTL_MAYU_GET_LOG) DEBUG_LOG(("DeviceIoControl: %x", irpSp->Parameters.DeviceIoControl.IoControlCode)); + status = STATUS_INVALID_DEVICE_REQUEST; + switch (irpSp->Parameters.DeviceIoControl.IoControlCode) { + case IOCTL_MAYU_DETOUR_CANCEL: { + KIRQL currentIrql; + PIRP irpCancel = NULL; + + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + if (detourDevExt->isOpen) + irpCancel = detourDevExt->irpq; + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + + if (irpCancel) + IoCancelIrp(irpCancel);// at this point, the irpCancel may be completed + status = STATUS_SUCCESS; + break; + } + case IOCTL_MAYU_GET_VERSION: { + if (irpSp->Parameters.DeviceIoControl.OutputBufferLength < + MayuDriverVersion.Length) { + status = STATUS_INVALID_PARAMETER; + break; + } + RtlCopyMemory(irp->AssociatedIrp.SystemBuffer, + MayuDriverVersion.Buffer, MayuDriverVersion.Length); + irp->IoStatus.Information = MayuDriverVersion.Length; + DEBUG_LOG(("Version: %T", &MayuDriverVersion)); + status = STATUS_SUCCESS; + break; + } + case IOCTL_MAYU_GET_LOG: + status = DEBUG_LOG_RETRIEVE((irp)); + break; + case IOCTL_MAYU_FORCE_KEYBOARD_INPUT: { + KIRQL currentIrql, cancelIrql; + + // if detour is opened, key datum are forwarded to detour + if (irpSp->Parameters.DeviceIoControl.InputBufferLength % + sizeof(KEYBOARD_INPUT_DATA)) { + status = STATUS_INVALID_PARAMETER; + break; + } + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + KqEnque(&detourDevExt->readQue, + (KEYBOARD_INPUT_DATA *)irp->AssociatedIrp.SystemBuffer, + irpSp->Parameters.DeviceIoControl.InputBufferLength + / sizeof(KEYBOARD_INPUT_DATA)); + + if (detourDevExt->irpq) { + if (readq(&detourDevExt->readQue, detourDevExt->irpq) == + STATUS_SUCCESS) { + IoAcquireCancelSpinLock(&cancelIrql); + IoSetCancelRoutine(detourDevExt->irpq, NULL); + IoReleaseCancelSpinLock(cancelIrql); + IoCompleteRequest(detourDevExt->irpq, IO_KEYBOARD_INCREMENT); + detourDevExt->irpq = NULL; + } + } + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + status = STATUS_SUCCESS; + break; } - } - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - status = STATUS_SUCCESS; - break; - } - default: - status = STATUS_INVALID_DEVICE_REQUEST; - break; - } - irp->IoStatus.Status = status; - if (status != STATUS_PENDING) - IoCompleteRequest(irp, IO_NO_INCREMENT); - - return status; + default: + status = STATUS_INVALID_DEVICE_REQUEST; + break; + } + irp->IoStatus.Status = status; + if (status != STATUS_PENDING) + IoCompleteRequest(irp, IO_NO_INCREMENT); + + return status; } @@ -979,13 +952,13 @@ NTSTATUS detourDeviceControl(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) // detour IRP_MJ_POWER NTSTATUS detourPower(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - UNREFERENCED_PARAMETER(deviceObject); - - PoStartNextPowerIrp(irp); - irp->IoStatus.Status = STATUS_SUCCESS; - irp->IoStatus.Information = 0; - IoCompleteRequest(irp, IO_NO_INCREMENT); - return STATUS_SUCCESS; + UNREFERENCED_PARAMETER(deviceObject); + + PoStartNextPowerIrp(irp); + irp->IoStatus.Status = STATUS_SUCCESS; + irp->IoStatus.Information = 0; + IoCompleteRequest(irp, IO_NO_INCREMENT); + return STATUS_SUCCESS; } #endif // !MAYUD_NT4 @@ -993,60 +966,58 @@ NTSTATUS detourPower(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) // filter IRP_MJ_READ NTSTATUS filterRead(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - NTSTATUS status; - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); - FilterDeviceExtension *filterDevExt = - (FilterDeviceExtension*)deviceObject->DeviceExtension; - DetourDeviceExtension *detourDevExt = - (DetourDeviceExtension*)filterDevExt->detourDevObj->DeviceExtension; - KIRQL currentIrql; - - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - if (detourDevExt->isOpen && !detourDevExt->wasCleanupInitiated) - // read from que - { - ULONG len = irpSp->Parameters.Read.Length; - - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - irp->IoStatus.Information = 0; - KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); - if (len == 0) - status = STATUS_SUCCESS; - else if (len % sizeof(KEYBOARD_INPUT_DATA)) - status = STATUS_BUFFER_TOO_SMALL; - else - status = readq(&filterDevExt->readQue, irp); - KeReleaseSpinLock(&filterDevExt->lock, currentIrql); - if (status != STATUS_PENDING) { - irp->IoStatus.Status = status; - IoCompleteRequest(irp, IO_NO_INCREMENT); - return status; - } - } - else - { - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - } - KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); - filterDevExt->irpq = irp; - KeReleaseSpinLock(&filterDevExt->lock, currentIrql); - - *IoGetNextIrpStackLocation(irp) = *irpSp; - IoSetCompletionRoutine(irp, filterReadCompletion, NULL, TRUE, TRUE, TRUE); - return IoCallDriver(filterDevExt->kbdClassDevObj, irp); + NTSTATUS status; + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); + FilterDeviceExtension *filterDevExt = + (FilterDeviceExtension*)deviceObject->DeviceExtension; + DetourDeviceExtension *detourDevExt = + (DetourDeviceExtension*)filterDevExt->detourDevObj->DeviceExtension; + KIRQL currentIrql; + + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + if (detourDevExt->isOpen && !detourDevExt->wasCleanupInitiated) + // read from que + { + ULONG len = irpSp->Parameters.Read.Length; + + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + irp->IoStatus.Information = 0; + KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); + if (len == 0) + status = STATUS_SUCCESS; + else if (len % sizeof(KEYBOARD_INPUT_DATA)) + status = STATUS_BUFFER_TOO_SMALL; + else + status = readq(&filterDevExt->readQue, irp); + KeReleaseSpinLock(&filterDevExt->lock, currentIrql); + if (status != STATUS_PENDING) { + irp->IoStatus.Status = status; + IoCompleteRequest(irp, IO_NO_INCREMENT); + return status; + } + } else { + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + } + KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); + filterDevExt->irpq = irp; + KeReleaseSpinLock(&filterDevExt->lock, currentIrql); + + *IoGetNextIrpStackLocation(irp) = *irpSp; + IoSetCompletionRoutine(irp, filterReadCompletion, NULL, TRUE, TRUE, TRUE); + return IoCallDriver(filterDevExt->kbdClassDevObj, irp); } // pass throught irp to keyboard class driver NTSTATUS filterPassThrough(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - FilterDeviceExtension *filterDevExt = - (FilterDeviceExtension*)deviceObject->DeviceExtension; + FilterDeviceExtension *filterDevExt = + (FilterDeviceExtension*)deviceObject->DeviceExtension; - *IoGetNextIrpStackLocation(irp) = *IoGetCurrentIrpStackLocation(irp); - IoSetCompletionRoutine(irp, filterGenericCompletion, - NULL, TRUE, TRUE, TRUE); - return IoCallDriver(filterDevExt->kbdClassDevObj, irp); + *IoGetNextIrpStackLocation(irp) = *IoGetCurrentIrpStackLocation(irp); + IoSetCompletionRoutine(irp, filterGenericCompletion, + NULL, TRUE, TRUE, TRUE); + return IoCallDriver(filterDevExt->kbdClassDevObj, irp); } @@ -1054,189 +1025,182 @@ NTSTATUS filterPassThrough(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) // filter IRP_MJ_POWER NTSTATUS filterPower(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - FilterDeviceExtension *filterDevExt = - (FilterDeviceExtension*)deviceObject->DeviceExtension; + FilterDeviceExtension *filterDevExt = + (FilterDeviceExtension*)deviceObject->DeviceExtension; - PoStartNextPowerIrp(irp); - IoSkipCurrentIrpStackLocation(irp); - return PoCallDriver(filterDevExt->kbdClassDevObj, irp); + PoStartNextPowerIrp(irp); + IoSkipCurrentIrpStackLocation(irp); + return PoCallDriver(filterDevExt->kbdClassDevObj, irp); } #endif // !MAYUD_NT4 NTSTATUS filterPnP(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); - FilterDeviceExtension *filterDevExt = - (FilterDeviceExtension*)deviceObject->DeviceExtension; - DetourDeviceExtension *detourDevExt = - (DetourDeviceExtension*)filterDevExt->detourDevObj->DeviceExtension; - KIRQL currentIrql; - NTSTATUS status; - ULONG minor; - PIRP cancelIrp; - PDRIVER_OBJECT driverObject = deviceObject->DriverObject; - - minor = irpSp->MinorFunction; - IoSkipCurrentIrpStackLocation(irp); - status = IoCallDriver(filterDevExt->kbdClassDevObj, irp); - DEBUG_LOG(("filterPnP: minor=%d(%x)", minor, minor)); - switch (minor) { - case IRP_MN_SURPRISE_REMOVAL: - case IRP_MN_REMOVE_DEVICE: - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - if (detourDevExt->filterDevObj == deviceObject) { - PDEVICE_OBJECT devObj = deviceObject->DriverObject->DeviceObject; - - DEBUG_LOG(("filterPnP: current filter(%x) was removed", deviceObject)); - detourDevExt->filterDevObj = NULL; - while (devObj->NextDevice) { - if (devObj != deviceObject) { - detourDevExt->filterDevObj = devObj; - break; + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); + FilterDeviceExtension *filterDevExt = + (FilterDeviceExtension*)deviceObject->DeviceExtension; + DetourDeviceExtension *detourDevExt = + (DetourDeviceExtension*)filterDevExt->detourDevObj->DeviceExtension; + KIRQL currentIrql; + NTSTATUS status; + ULONG minor; + PIRP cancelIrp; + PDRIVER_OBJECT driverObject = deviceObject->DriverObject; + + minor = irpSp->MinorFunction; + IoSkipCurrentIrpStackLocation(irp); + status = IoCallDriver(filterDevExt->kbdClassDevObj, irp); + DEBUG_LOG(("filterPnP: minor=%d(%x)", minor, minor)); + switch (minor) { + case IRP_MN_SURPRISE_REMOVAL: + case IRP_MN_REMOVE_DEVICE: + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + if (detourDevExt->filterDevObj == deviceObject) { + PDEVICE_OBJECT devObj = deviceObject->DriverObject->DeviceObject; + + DEBUG_LOG(("filterPnP: current filter(%x) was removed", deviceObject)); + detourDevExt->filterDevObj = NULL; + while (devObj->NextDevice) { + if (devObj != deviceObject) { + detourDevExt->filterDevObj = devObj; + break; + } + devObj = devObj->NextDevice; + } + DEBUG_LOG(("filterPnP: current filter was changed to %x", detourDevExt->filterDevObj)); + } + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + // detach + IoDetachDevice(filterDevExt->kbdClassDevObj); + + KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); + // TODO: at this point, the irp may be completed (but what can I do for it ?) + cancelIrp = filterDevExt->irpq; + KqFinalize(&filterDevExt->readQue); + + KeReleaseSpinLock(&filterDevExt->lock, currentIrql); + if (cancelIrp) { + IoCancelIrp(cancelIrp); + } + IoDeleteDevice(deviceObject); + DEBUG_LOG(("delete filter device: %x", deviceObject)); + DEBUG_LOGChain(driverObject); + break; + default: + break; } - devObj = devObj->NextDevice; - } - DEBUG_LOG(("filterPnP: current filter was changed to %x", detourDevExt->filterDevObj)); - } - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - // detach - IoDetachDevice(filterDevExt->kbdClassDevObj); - - KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); - // TODO: at this point, the irp may be completed (but what can I do for it ?) - cancelIrp = filterDevExt->irpq; - KqFinalize(&filterDevExt->readQue); - - KeReleaseSpinLock(&filterDevExt->lock, currentIrql); - if (cancelIrp) { - IoCancelIrp(cancelIrp); - } - IoDeleteDevice(deviceObject); - DEBUG_LOG(("delete filter device: %x", deviceObject)); - DEBUG_LOGChain(driverObject); - break; - default: - break; - } - return status; + return status; } #ifdef USE_TOUCHPAD -// +// NTSTATUS filterTouchpadCompletion(IN PDEVICE_OBJECT deviceObject, - IN PIRP irp, IN PVOID context) + IN PIRP irp, IN PVOID context) { - KIRQL currentIrql; - FilterDeviceExtension *filterDevExt = - (FilterDeviceExtension*)deviceObject->DeviceExtension; - PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); - //PIO_STACK_LOCATION irpSp = IoGetNextIrpStackLocation(irp); - UCHAR *data = irp->UserBuffer; - UCHAR pressure; - - UNREFERENCED_PARAMETER(context); - - if (irp->PendingReturned) - IoMarkIrpPending(irp); - - if (data) - pressure = data[TOUCHPAD_PRESSURE_OFFSET]; - else - pressure = 0; - - if (data) - { - ULONG *p = (ULONG*)data; - //DEBUG_LOG(("UserBuffer: %2x %2x %2x %2x", data[4], data[5], data[6], data[7])); - //DEBUG_LOG(("UserBuffer: %x %x %x %x %x %x %x %x", p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7])); - } - KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); - if (filterDevExt->isTouched == FALSE && pressure) - { - KIRQL currentIrql, cancelIrql; - PDEVICE_OBJECT detourDevObj = filterDevExt->detourDevObj; - DetourDeviceExtension *detourDevExt = - (DetourDeviceExtension*)detourDevObj->DeviceExtension; - if (detourDevExt->isOpen) - { - KEYBOARD_INPUT_DATA PadKey = {0, TOUCHPAD_SCANCODE, 0, 0, 0}; - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - // if detour is opened, key datum are forwarded to detour - KqEnque(&detourDevExt->readQue, &PadKey, 1); - detourDevExt->filterDevObj = deviceObject; - - if (detourDevExt->irpq) { - if (readq(&detourDevExt->readQue, detourDevExt->irpq) == - STATUS_SUCCESS) { - IoAcquireCancelSpinLock(&cancelIrql); - IoSetCancelRoutine(detourDevExt->irpq, NULL); - IoReleaseCancelSpinLock(cancelIrql); - IoCompleteRequest(detourDevExt->irpq, IO_KEYBOARD_INCREMENT); - detourDevExt->irpq = NULL; + KIRQL currentIrql; + FilterDeviceExtension *filterDevExt = + (FilterDeviceExtension*)deviceObject->DeviceExtension; + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation(irp); + //PIO_STACK_LOCATION irpSp = IoGetNextIrpStackLocation(irp); + UCHAR *data = irp->UserBuffer; + UCHAR pressure; + + UNREFERENCED_PARAMETER(context); + + if (irp->PendingReturned) + IoMarkIrpPending(irp); + + if (data) + pressure = data[TOUCHPAD_PRESSURE_OFFSET]; + else + pressure = 0; + + if (data) { + ULONG *p = (ULONG*)data; + //DEBUG_LOG(("UserBuffer: %2x %2x %2x %2x", data[4], data[5], data[6], data[7])); + //DEBUG_LOG(("UserBuffer: %x %x %x %x %x %x %x %x", p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7])); } - } - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - } - filterDevExt->isTouched = TRUE; - } - else - { - if (filterDevExt->isTouched == TRUE && pressure == 0) - { - KIRQL currentIrql, cancelIrql; - PDEVICE_OBJECT detourDevObj = filterDevExt->detourDevObj; - DetourDeviceExtension *detourDevExt = - (DetourDeviceExtension*)detourDevObj->DeviceExtension; - if (detourDevExt->isOpen) - { - KEYBOARD_INPUT_DATA PadKey = {0, TOUCHPAD_SCANCODE, 1, 0, 0}; - KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); - // if detour is opened, key datum are forwarded to detour - KqEnque(&detourDevExt->readQue, &PadKey, 1); - detourDevExt->filterDevObj = deviceObject; - - if (detourDevExt->irpq) { - if (readq(&detourDevExt->readQue, detourDevExt->irpq) == - STATUS_SUCCESS) { - IoAcquireCancelSpinLock(&cancelIrql); - IoSetCancelRoutine(detourDevExt->irpq, NULL); - IoReleaseCancelSpinLock(cancelIrql); - IoCompleteRequest(detourDevExt->irpq, IO_KEYBOARD_INCREMENT); - detourDevExt->irpq = NULL; - } + KeAcquireSpinLock(&filterDevExt->lock, ¤tIrql); + if (filterDevExt->isTouched == FALSE && pressure) { + KIRQL currentIrql, cancelIrql; + PDEVICE_OBJECT detourDevObj = filterDevExt->detourDevObj; + DetourDeviceExtension *detourDevExt = + (DetourDeviceExtension*)detourDevObj->DeviceExtension; + if (detourDevExt->isOpen) { + KEYBOARD_INPUT_DATA PadKey = {0, TOUCHPAD_SCANCODE, 0, 0, 0}; + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + // if detour is opened, key datum are forwarded to detour + KqEnque(&detourDevExt->readQue, &PadKey, 1); + detourDevExt->filterDevObj = deviceObject; + + if (detourDevExt->irpq) { + if (readq(&detourDevExt->readQue, detourDevExt->irpq) == + STATUS_SUCCESS) { + IoAcquireCancelSpinLock(&cancelIrql); + IoSetCancelRoutine(detourDevExt->irpq, NULL); + IoReleaseCancelSpinLock(cancelIrql); + IoCompleteRequest(detourDevExt->irpq, IO_KEYBOARD_INCREMENT); + detourDevExt->irpq = NULL; + } + } + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + } + filterDevExt->isTouched = TRUE; + } else { + if (filterDevExt->isTouched == TRUE && pressure == 0) { + KIRQL currentIrql, cancelIrql; + PDEVICE_OBJECT detourDevObj = filterDevExt->detourDevObj; + DetourDeviceExtension *detourDevExt = + (DetourDeviceExtension*)detourDevObj->DeviceExtension; + if (detourDevExt->isOpen) { + KEYBOARD_INPUT_DATA PadKey = {0, TOUCHPAD_SCANCODE, 1, 0, 0}; + KeAcquireSpinLock(&detourDevExt->lock, ¤tIrql); + // if detour is opened, key datum are forwarded to detour + KqEnque(&detourDevExt->readQue, &PadKey, 1); + detourDevExt->filterDevObj = deviceObject; + + if (detourDevExt->irpq) { + if (readq(&detourDevExt->readQue, detourDevExt->irpq) == + STATUS_SUCCESS) { + IoAcquireCancelSpinLock(&cancelIrql); + IoSetCancelRoutine(detourDevExt->irpq, NULL); + IoReleaseCancelSpinLock(cancelIrql); + IoCompleteRequest(detourDevExt->irpq, IO_KEYBOARD_INCREMENT); + detourDevExt->irpq = NULL; + } + } + KeReleaseSpinLock(&detourDevExt->lock, currentIrql); + } + filterDevExt->isTouched = FALSE; + } } - KeReleaseSpinLock(&detourDevExt->lock, currentIrql); - } - filterDevExt->isTouched = FALSE; - } - } - //DEBUG_LOG(("touchpad pressed: out=%u in=%u code=%u status=%x SystemBuffer=%x UserBuffer=%x", irpSp->Parameters.DeviceIoControl.OutputBufferLength, irpSp->Parameters.DeviceIoControl.InputBufferLength, irpSp->Parameters.DeviceIoControl.IoControlCode, irp->IoStatus.Status, irp->AssociatedIrp.SystemBuffer, irp->UserBuffer)); - KeReleaseSpinLock(&filterDevExt->lock, currentIrql); - return STATUS_SUCCESS; + //DEBUG_LOG(("touchpad pressed: out=%u in=%u code=%u status=%x SystemBuffer=%x UserBuffer=%x", irpSp->Parameters.DeviceIoControl.OutputBufferLength, irpSp->Parameters.DeviceIoControl.InputBufferLength, irpSp->Parameters.DeviceIoControl.IoControlCode, irp->IoStatus.Status, irp->AssociatedIrp.SystemBuffer, irp->UserBuffer)); + KeReleaseSpinLock(&filterDevExt->lock, currentIrql); + return STATUS_SUCCESS; } // filter touchpad input NTSTATUS filterTouchpad(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - FilterDeviceExtension *filterDevExt = - (FilterDeviceExtension*)deviceObject->DeviceExtension; + FilterDeviceExtension *filterDevExt = + (FilterDeviceExtension*)deviceObject->DeviceExtension; - *IoGetNextIrpStackLocation(irp) = *IoGetCurrentIrpStackLocation(irp); - IoSetCompletionRoutine(irp, filterTouchpadCompletion, - NULL, TRUE, TRUE, TRUE); - return IoCallDriver(filterDevExt->kbdClassDevObj, irp); + *IoGetNextIrpStackLocation(irp) = *IoGetCurrentIrpStackLocation(irp); + IoSetCompletionRoutine(irp, filterTouchpadCompletion, + NULL, TRUE, TRUE, TRUE); + return IoCallDriver(filterDevExt->kbdClassDevObj, irp); } #endif NTSTATUS detourPnP(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - UNREFERENCED_PARAMETER(deviceObject); + UNREFERENCED_PARAMETER(deviceObject); - IoSkipCurrentIrpStackLocation(irp); - irp->IoStatus.Status = STATUS_SUCCESS; - irp->IoStatus.Information = 0; - IoCompleteRequest(irp, IO_NO_INCREMENT); - return STATUS_SUCCESS; + IoSkipCurrentIrpStackLocation(irp); + irp->IoStatus.Status = STATUS_SUCCESS; + irp->IoStatus.Information = 0; + IoCompleteRequest(irp, IO_NO_INCREMENT); + return STATUS_SUCCESS; } diff --git a/d/rescue/mayudrsc.c b/d/rescue/mayudrsc.c old mode 100755 new mode 100644 index cab37ed..99cf319 --- a/d/rescue/mayudrsc.c +++ b/d/rescue/mayudrsc.c @@ -25,32 +25,32 @@ NTSTATUS mayuGenericDispatch (IN PDEVICE_OBJECT, IN PIRP); // initialize driver NTSTATUS DriverEntry(IN PDRIVER_OBJECT driverObject, - IN PUNICODE_STRING registryPath) + IN PUNICODE_STRING registryPath) { - ULONG i; - UNREFERENCED_PARAMETER(registryPath); - - // set major functions - driverObject->DriverUnload = mayuUnloadDriver; - driverObject->DriverExtension->AddDevice = mayuAddDevice; - for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++) - driverObject->MajorFunction[i] = mayuGenericDispatch; - driverObject->MajorFunction[IRP_MJ_PNP] = mayuGenericDispatch; - return STATUS_SUCCESS; + ULONG i; + UNREFERENCED_PARAMETER(registryPath); + + // set major functions + driverObject->DriverUnload = mayuUnloadDriver; + driverObject->DriverExtension->AddDevice = mayuAddDevice; + for (i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++) + driverObject->MajorFunction[i] = mayuGenericDispatch; + driverObject->MajorFunction[IRP_MJ_PNP] = mayuGenericDispatch; + return STATUS_SUCCESS; } NTSTATUS mayuAddDevice(IN PDRIVER_OBJECT driverObject, - IN PDEVICE_OBJECT kbdClassDevObj) + IN PDEVICE_OBJECT kbdClassDevObj) { - UNREFERENCED_PARAMETER(driverObject); - UNREFERENCED_PARAMETER(kbdClassDevObj); - return STATUS_SUCCESS; + UNREFERENCED_PARAMETER(driverObject); + UNREFERENCED_PARAMETER(kbdClassDevObj); + return STATUS_SUCCESS; } // unload driver VOID mayuUnloadDriver(IN PDRIVER_OBJECT driverObject) { - UNREFERENCED_PARAMETER(driverObject); + UNREFERENCED_PARAMETER(driverObject); } @@ -61,7 +61,7 @@ VOID mayuUnloadDriver(IN PDRIVER_OBJECT driverObject) // Generic Dispatcher NTSTATUS mayuGenericDispatch(IN PDEVICE_OBJECT deviceObject, IN PIRP irp) { - UNREFERENCED_PARAMETER(deviceObject); - UNREFERENCED_PARAMETER(irp); - return STATUS_SUCCESS; + UNREFERENCED_PARAMETER(deviceObject); + UNREFERENCED_PARAMETER(irp); + return STATUS_SUCCESS; } diff --git a/dlgeditsetting.cpp b/dlgeditsetting.cpp index 892d11e..cecb0ff 100644 --- a/dlgeditsetting.cpp +++ b/dlgeditsetting.cpp @@ -13,140 +13,132 @@ /// class DlgEditSetting : public LayoutManager { - HWND m_hwndMayuPathName; /// - HWND m_hwndMayuPath; /// - HWND m_hwndSymbols; /// + HWND m_hwndMayuPathName; /// + HWND m_hwndMayuPath; /// + HWND m_hwndSymbols; /// - DlgEditSettingData *m_data; /// + DlgEditSettingData *m_data; /// public: - /// - DlgEditSetting(HWND i_hwnd) - : LayoutManager(i_hwnd), - m_hwndMayuPathName(NULL), - m_hwndMayuPath(NULL), - m_hwndSymbols(NULL), - m_data(NULL) - { - } - - /// WM_INITDIALOG - BOOL wmInitDialog(HWND /* focus */, LPARAM i_lParam) - { - m_data = reinterpret_cast(i_lParam); - - setSmallIcon(m_hwnd, IDI_ICON_mayu); - setBigIcon(m_hwnd, IDI_ICON_mayu); - - CHECK_TRUE( m_hwndMayuPathName - = GetDlgItem(m_hwnd, IDC_EDIT_mayuPathName) ); - CHECK_TRUE( m_hwndMayuPath = GetDlgItem(m_hwnd, IDC_EDIT_mayuPath) ); - CHECK_TRUE( m_hwndSymbols = GetDlgItem(m_hwnd, IDC_EDIT_symbols) ); - - SetWindowText(m_hwndMayuPathName, m_data->m_name.c_str()); - SetWindowText(m_hwndMayuPath, m_data->m_filename.c_str()); - SetWindowText(m_hwndSymbols, m_data->m_symbols.c_str()); - - restrictSmallestSize(); - - // set layout manager - typedef LayoutManager LM; - - addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuPathName)); - addItem(GetDlgItem(m_hwnd, IDC_EDIT_mayuPathName), - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuPathNameComment), - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE); - - addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuPath)); - addItem(GetDlgItem(m_hwnd, IDC_EDIT_mayuPath), - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_BUTTON_browse), - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE); - - addItem(GetDlgItem(m_hwnd, IDC_STATIC_symbols)); - addItem(GetDlgItem(m_hwnd, IDC_EDIT_symbols), - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_STATIC_symbolsComment), - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE); - - addItem(GetDlgItem(m_hwnd, IDOK), - LM::ORIGIN_CENTER, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_CENTER, LM::ORIGIN_TOP_EDGE); - addItem(GetDlgItem(m_hwnd, IDCANCEL), - LM::ORIGIN_CENTER, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_CENTER, LM::ORIGIN_TOP_EDGE); - - restrictSmallestSize(LM::RESTRICT_BOTH); - restrictLargestSize(LM::RESTRICT_VERTICALLY); - - return TRUE; - } - - /// WM_CLOSE - BOOL wmClose() - { - CHECK_TRUE( EndDialog(m_hwnd, 0) ); - return TRUE; - } - - /// WM_COMMAND - BOOL wmCommand(int /* i_notify_code */, int i_id, HWND /* i_hwnd_control */) - { - _TCHAR buf[GANA_MAX_PATH]; - switch (i_id) - { - case IDC_BUTTON_browse: - { - tstring title = loadString(IDS_openMayu); - tstring filter = loadString(IDS_openMayuFilter); - for (size_t i = 0; i < filter.size(); ++ i) - if (filter[i] == _T('|')) - filter[i] = _T('\0'); - - _tcscpy(buf, _T(".mayu")); - OPENFILENAME of; - memset(&of, 0, sizeof(of)); - of.lStructSize = sizeof(of); - of.hwndOwner = m_hwnd; - of.lpstrFilter = filter.c_str(); - of.nFilterIndex = 1; - of.lpstrFile = buf; - of.nMaxFile = NUMBER_OF(buf); - of.lpstrTitle = title.c_str(); - of.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | - OFN_HIDEREADONLY | OFN_PATHMUSTEXIST; - if (GetOpenFileName(&of)) - SetWindowText(m_hwndMayuPath, buf); - return TRUE; - } - - case IDOK: - { - GetWindowText(m_hwndMayuPathName, buf, NUMBER_OF(buf)); - m_data->m_name = buf; - GetWindowText(m_hwndMayuPath, buf, NUMBER_OF(buf)); - m_data->m_filename = buf; - GetWindowText(m_hwndSymbols, buf, NUMBER_OF(buf)); - m_data->m_symbols = buf; - CHECK_TRUE( EndDialog(m_hwnd, 1) ); - return TRUE; - } - - case IDCANCEL: - { - CHECK_TRUE( EndDialog(m_hwnd, 0) ); - return TRUE; - } - } - return FALSE; - } + /// + DlgEditSetting(HWND i_hwnd) + : LayoutManager(i_hwnd), + m_hwndMayuPathName(NULL), + m_hwndMayuPath(NULL), + m_hwndSymbols(NULL), + m_data(NULL) { + } + + /// WM_INITDIALOG + BOOL wmInitDialog(HWND /* focus */, LPARAM i_lParam) { + m_data = reinterpret_cast(i_lParam); + + setSmallIcon(m_hwnd, IDI_ICON_mayu); + setBigIcon(m_hwnd, IDI_ICON_mayu); + + CHECK_TRUE( m_hwndMayuPathName + = GetDlgItem(m_hwnd, IDC_EDIT_mayuPathName) ); + CHECK_TRUE( m_hwndMayuPath = GetDlgItem(m_hwnd, IDC_EDIT_mayuPath) ); + CHECK_TRUE( m_hwndSymbols = GetDlgItem(m_hwnd, IDC_EDIT_symbols) ); + + SetWindowText(m_hwndMayuPathName, m_data->m_name.c_str()); + SetWindowText(m_hwndMayuPath, m_data->m_filename.c_str()); + SetWindowText(m_hwndSymbols, m_data->m_symbols.c_str()); + + restrictSmallestSize(); + + // set layout manager + typedef LayoutManager LM; + + addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuPathName)); + addItem(GetDlgItem(m_hwnd, IDC_EDIT_mayuPathName), + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuPathNameComment), + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE); + + addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuPath)); + addItem(GetDlgItem(m_hwnd, IDC_EDIT_mayuPath), + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_BUTTON_browse), + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE); + + addItem(GetDlgItem(m_hwnd, IDC_STATIC_symbols)); + addItem(GetDlgItem(m_hwnd, IDC_EDIT_symbols), + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_STATIC_symbolsComment), + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_TOP_EDGE); + + addItem(GetDlgItem(m_hwnd, IDOK), + LM::ORIGIN_CENTER, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_CENTER, LM::ORIGIN_TOP_EDGE); + addItem(GetDlgItem(m_hwnd, IDCANCEL), + LM::ORIGIN_CENTER, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_CENTER, LM::ORIGIN_TOP_EDGE); + + restrictSmallestSize(LM::RESTRICT_BOTH); + restrictLargestSize(LM::RESTRICT_VERTICALLY); + + return TRUE; + } + + /// WM_CLOSE + BOOL wmClose() { + CHECK_TRUE( EndDialog(m_hwnd, 0) ); + return TRUE; + } + + /// WM_COMMAND + BOOL wmCommand(int /* i_notify_code */, int i_id, HWND /* i_hwnd_control */) { + _TCHAR buf[GANA_MAX_PATH]; + switch (i_id) { + case IDC_BUTTON_browse: { + tstring title = loadString(IDS_openMayu); + tstring filter = loadString(IDS_openMayuFilter); + for (size_t i = 0; i < filter.size(); ++ i) + if (filter[i] == _T('|')) + filter[i] = _T('\0'); + + _tcscpy(buf, _T(".mayu")); + OPENFILENAME of; + memset(&of, 0, sizeof(of)); + of.lStructSize = sizeof(of); + of.hwndOwner = m_hwnd; + of.lpstrFilter = filter.c_str(); + of.nFilterIndex = 1; + of.lpstrFile = buf; + of.nMaxFile = NUMBER_OF(buf); + of.lpstrTitle = title.c_str(); + of.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | + OFN_HIDEREADONLY | OFN_PATHMUSTEXIST; + if (GetOpenFileName(&of)) + SetWindowText(m_hwndMayuPath, buf); + return TRUE; + } + + case IDOK: { + GetWindowText(m_hwndMayuPathName, buf, NUMBER_OF(buf)); + m_data->m_name = buf; + GetWindowText(m_hwndMayuPath, buf, NUMBER_OF(buf)); + m_data->m_filename = buf; + GetWindowText(m_hwndSymbols, buf, NUMBER_OF(buf)); + m_data->m_symbols = buf; + CHECK_TRUE( EndDialog(m_hwnd, 1) ); + return TRUE; + } + + case IDCANCEL: { + CHECK_TRUE( EndDialog(m_hwnd, 0) ); + return TRUE; + } + } + return FALSE; + } }; @@ -156,31 +148,29 @@ INT_PTR CALLBACK dlgEditSetting_dlgProc(HWND i_hwnd, UINT i_message, #else BOOL CALLBACK dlgEditSetting_dlgProc(HWND i_hwnd, UINT i_message, #endif - WPARAM i_wParam, LPARAM i_lParam) + WPARAM i_wParam, LPARAM i_lParam) { - DlgEditSetting *wc; - getUserData(i_hwnd, &wc); - if (!wc) - switch (i_message) - { - case WM_INITDIALOG: - wc = setUserData(i_hwnd, new DlgEditSetting(i_hwnd)); - return wc->wmInitDialog( - reinterpret_cast(i_wParam), i_lParam); - } - else - switch (i_message) - { - case WM_COMMAND: - return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam), - reinterpret_cast(i_lParam)); - case WM_CLOSE: - return wc->wmClose(); - case WM_NCDESTROY: - delete wc; - return TRUE; - default: - return wc->defaultWMHandler(i_message, i_wParam, i_lParam); - } - return FALSE; + DlgEditSetting *wc; + getUserData(i_hwnd, &wc); + if (!wc) + switch (i_message) { + case WM_INITDIALOG: + wc = setUserData(i_hwnd, new DlgEditSetting(i_hwnd)); + return wc->wmInitDialog( + reinterpret_cast(i_wParam), i_lParam); + } + else + switch (i_message) { + case WM_COMMAND: + return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam), + reinterpret_cast(i_lParam)); + case WM_CLOSE: + return wc->wmClose(); + case WM_NCDESTROY: + delete wc; + return TRUE; + default: + return wc->defaultWMHandler(i_message, i_wParam, i_lParam); + } + return FALSE; } diff --git a/dlgeditsetting.h b/dlgeditsetting.h index 382e93c..381d182 100644 --- a/dlgeditsetting.h +++ b/dlgeditsetting.h @@ -14,15 +14,14 @@ INT_PTR CALLBACK dlgEditSetting_dlgProc( #else BOOL CALLBACK dlgEditSetting_dlgProc( #endif - HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam); + HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam); /// parameters for "Edit Setting" dialog box -class DlgEditSettingData -{ +class DlgEditSettingData { public: - tstringi m_name; /// setting name - tstringi m_filename; /// filename of setting - tstringi m_symbols; /// symbol list (-Dsymbol1;-Dsymbol2;-D...) + tstringi m_name; /// setting name + tstringi m_filename; /// filename of setting + tstringi m_symbols; /// symbol list (-Dsymbol1;-Dsymbol2;-D...) }; diff --git a/dlginvestigate.cpp b/dlginvestigate.cpp index 4098426..c665684 100644 --- a/dlginvestigate.cpp +++ b/dlginvestigate.cpp @@ -18,136 +18,121 @@ /// class DlgInvestigate { - HWND m_hwnd; /// - UINT m_WM_MAYU_MESSAGE; /// - DlgInvestigateData m_data; /// - + HWND m_hwnd; /// + UINT m_WM_MAYU_MESSAGE; /// + DlgInvestigateData m_data; /// + public: - /// - DlgInvestigate(HWND i_hwnd) - : m_hwnd(i_hwnd), - m_WM_MAYU_MESSAGE(RegisterWindowMessage( - addSessionId(WM_MAYU_MESSAGE_NAME).c_str())) - { - m_data.m_engine = NULL; - m_data.m_hwndLog = NULL; - } - - /// WM_INITDIALOG - BOOL wmInitDialog(HWND /* i_focus */, LPARAM i_lParam) - { - m_data = *reinterpret_cast(i_lParam); - setSmallIcon(m_hwnd, IDI_ICON_mayu); - setBigIcon(m_hwnd, IDI_ICON_mayu); - return TRUE; - } - - /// WM_DESTROY - BOOL wmDestroy() - { - unsetSmallIcon(m_hwnd); - unsetBigIcon(m_hwnd); - return TRUE; - } - - /// WM_CLOSE - BOOL wmClose() - { - ShowWindow(m_hwnd, SW_HIDE); - return TRUE; - } - - /// WM_COMMAND - BOOL wmCommand(int /* i_notifyCode */, int i_id, HWND /* i_hwndControl */) - { - switch (i_id) - { - case IDOK: - { - ShowWindow(m_hwnd, SW_HIDE); - return TRUE; - } - } - return FALSE; - } - - /// WM_focusNotify - BOOL wmFocusNotify(bool i_isFocused, HWND i_hwndFocus) - { - if (m_data.m_engine && - i_hwndFocus == GetDlgItem(m_hwnd, IDC_CUSTOM_scancode)) - m_data.m_engine->enableLogMode(i_isFocused); - return TRUE; - } - - /// WM_targetNotify - BOOL wmTargetNotify(HWND i_hwndTarget) - { - _TCHAR className[GANA_MAX_ATOM_LENGTH]; - bool ok = false; - if (GetClassName(i_hwndTarget, className, NUMBER_OF(className))) - { - if (_tcsicmp(className, _T("ConsoleWindowClass")) == 0) - { - _TCHAR titleName[1024]; - if (GetWindowText(i_hwndTarget, titleName, NUMBER_OF(titleName)) == 0) - titleName[0] = _T('\0'); - { - Acquire a(&m_data.m_engine->m_log, 1); - m_data.m_engine->m_log << _T("HWND:\t") << std::hex - << reinterpret_cast(i_hwndTarget) - << std::dec << std::endl; + /// + DlgInvestigate(HWND i_hwnd) + : m_hwnd(i_hwnd), + m_WM_MAYU_MESSAGE(RegisterWindowMessage( + addSessionId(WM_MAYU_MESSAGE_NAME).c_str())) { + m_data.m_engine = NULL; + m_data.m_hwndLog = NULL; + } + + /// WM_INITDIALOG + BOOL wmInitDialog(HWND /* i_focus */, LPARAM i_lParam) { + m_data = *reinterpret_cast(i_lParam); + setSmallIcon(m_hwnd, IDI_ICON_mayu); + setBigIcon(m_hwnd, IDI_ICON_mayu); + return TRUE; + } + + /// WM_DESTROY + BOOL wmDestroy() { + unsetSmallIcon(m_hwnd); + unsetBigIcon(m_hwnd); + return TRUE; + } + + /// WM_CLOSE + BOOL wmClose() { + ShowWindow(m_hwnd, SW_HIDE); + return TRUE; + } + + /// WM_COMMAND + BOOL wmCommand(int /* i_notifyCode */, int i_id, HWND /* i_hwndControl */) { + switch (i_id) { + case IDOK: { + ShowWindow(m_hwnd, SW_HIDE); + return TRUE; + } + } + return FALSE; + } + + /// WM_focusNotify + BOOL wmFocusNotify(bool i_isFocused, HWND i_hwndFocus) { + if (m_data.m_engine && + i_hwndFocus == GetDlgItem(m_hwnd, IDC_CUSTOM_scancode)) + m_data.m_engine->enableLogMode(i_isFocused); + return TRUE; + } + + /// WM_targetNotify + BOOL wmTargetNotify(HWND i_hwndTarget) { + _TCHAR className[GANA_MAX_ATOM_LENGTH]; + bool ok = false; + if (GetClassName(i_hwndTarget, className, NUMBER_OF(className))) { + if (_tcsicmp(className, _T("ConsoleWindowClass")) == 0) { + _TCHAR titleName[1024]; + if (GetWindowText(i_hwndTarget, titleName, NUMBER_OF(titleName)) == 0) + titleName[0] = _T('\0'); + { + Acquire a(&m_data.m_engine->m_log, 1); + m_data.m_engine->m_log << _T("HWND:\t") << std::hex + << reinterpret_cast(i_hwndTarget) + << std::dec << std::endl; + } + Acquire a(&m_data.m_engine->m_log, 0); + m_data.m_engine->m_log << _T("CLASS:\t") << className << std::endl; + m_data.m_engine->m_log << _T("TITLE:\t") << titleName << std::endl; + ok = true; + } + } + if (!ok) + CHECK_TRUE( PostMessage(i_hwndTarget, m_WM_MAYU_MESSAGE, + MayuMessage_notifyName, 0) ); + return TRUE; + } + + /// WM_vkeyNotify + BOOL wmVkeyNotify(int i_nVirtKey, int /* i_repeatCount */, + BYTE /* i_scanCode */, bool i_isExtended, + bool /* i_isAltDown */, bool i_isKeyup) { + Acquire a(&m_data.m_engine->m_log, 0); + m_data.m_engine->m_log + << (i_isExtended ? _T(" E-") : _T(" ")) + << _T("0x") << std::hex << std::setw(2) << std::setfill(_T('0')) + << i_nVirtKey << std::dec << _T(" &VK( ") + << (i_isExtended ? _T("E-") : _T(" ")) + << (i_isKeyup ? _T("U-") : _T("D-")); + + for (const VKeyTable *vkt = g_vkeyTable; vkt->m_name; ++ vkt) { + if (vkt->m_code == i_nVirtKey) { + m_data.m_engine->m_log << vkt->m_name << _T(" )") << std::endl; + return TRUE; + } + } + m_data.m_engine->m_log << _T("0x") << std::hex << std::setw(2) + << std::setfill(_T('0')) << i_nVirtKey << std::dec + << _T(" )") << std::endl; + return TRUE; + } + + BOOL wmMove(int /* i_x */, int /* i_y */) { + RECT rc1, rc2; + GetWindowRect(m_hwnd, &rc1); + GetWindowRect(m_data.m_hwndLog, &rc2); + + MoveWindow(m_data.m_hwndLog, rc1.left, rc1.bottom, + rcWidth(&rc2), rcHeight(&rc2), TRUE); + + return TRUE; } - Acquire a(&m_data.m_engine->m_log, 0); - m_data.m_engine->m_log << _T("CLASS:\t") << className << std::endl; - m_data.m_engine->m_log << _T("TITLE:\t") << titleName << std::endl; - ok = true; - } - } - if (!ok) - CHECK_TRUE( PostMessage(i_hwndTarget, m_WM_MAYU_MESSAGE, - MayuMessage_notifyName, 0) ); - return TRUE; - } - - /// WM_vkeyNotify - BOOL wmVkeyNotify(int i_nVirtKey, int /* i_repeatCount */, - BYTE /* i_scanCode */, bool i_isExtended, - bool /* i_isAltDown */, bool i_isKeyup) - { - Acquire a(&m_data.m_engine->m_log, 0); - m_data.m_engine->m_log - << (i_isExtended ? _T(" E-") : _T(" ")) - << _T("0x") << std::hex << std::setw(2) << std::setfill(_T('0')) - << i_nVirtKey << std::dec << _T(" &VK( ") - << (i_isExtended ? _T("E-") : _T(" ")) - << (i_isKeyup ? _T("U-") : _T("D-")); - - for (const VKeyTable *vkt = g_vkeyTable; vkt->m_name; ++ vkt) - { - if (vkt->m_code == i_nVirtKey) - { - m_data.m_engine->m_log << vkt->m_name << _T(" )") << std::endl; - return TRUE; - } - } - m_data.m_engine->m_log << _T("0x") << std::hex << std::setw(2) - << std::setfill(_T('0')) << i_nVirtKey << std::dec - << _T(" )") << std::endl; - return TRUE; - } - - BOOL wmMove(int /* i_x */, int /* i_y */) - { - RECT rc1, rc2; - GetWindowRect(m_hwnd, &rc1); - GetWindowRect(m_data.m_hwndLog, &rc2); - - MoveWindow(m_data.m_hwndLog, rc1.left, rc1.bottom, - rcWidth(&rc2), rcHeight(&rc2), TRUE); - - return TRUE; - } }; @@ -157,45 +142,43 @@ INT_PTR CALLBACK dlgInvestigate_dlgProc(HWND i_hwnd, UINT i_message, #else BOOL CALLBACK dlgInvestigate_dlgProc(HWND i_hwnd, UINT i_message, #endif - WPARAM i_wParam, LPARAM i_lParam) + WPARAM i_wParam, LPARAM i_lParam) { - DlgInvestigate *wc; - getUserData(i_hwnd, &wc); - if (!wc) - switch (i_message) - { - case WM_INITDIALOG: - wc = setUserData(i_hwnd, new DlgInvestigate(i_hwnd)); - return wc->wmInitDialog(reinterpret_cast(i_wParam), i_lParam); - } - else - switch (i_message) - { - case WM_MOVE: - return wc->wmMove(static_cast(LOWORD(i_lParam)), - static_cast(HIWORD(i_lParam))); - case WM_COMMAND: - return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam), - reinterpret_cast(i_lParam)); - case WM_CLOSE: - return wc->wmClose(); - case WM_DESTROY: - return wc->wmDestroy(); - case WM_APP_notifyFocus: - return wc->wmFocusNotify(!!i_wParam, - reinterpret_cast(i_lParam)); - case WM_APP_targetNotify: - return wc->wmTargetNotify(reinterpret_cast(i_lParam)); - case WM_APP_notifyVKey: - return wc->wmVkeyNotify( - static_cast(i_wParam), static_cast(i_lParam & 0xffff), - static_cast((i_lParam >> 16) & 0xff), - !!(i_lParam & (1 << 24)), - !!(i_lParam & (1 << 29)), - !!(i_lParam & (1 << 31))); - case WM_NCDESTROY: - delete wc; - return TRUE; - } - return FALSE; + DlgInvestigate *wc; + getUserData(i_hwnd, &wc); + if (!wc) + switch (i_message) { + case WM_INITDIALOG: + wc = setUserData(i_hwnd, new DlgInvestigate(i_hwnd)); + return wc->wmInitDialog(reinterpret_cast(i_wParam), i_lParam); + } + else + switch (i_message) { + case WM_MOVE: + return wc->wmMove(static_cast(LOWORD(i_lParam)), + static_cast(HIWORD(i_lParam))); + case WM_COMMAND: + return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam), + reinterpret_cast(i_lParam)); + case WM_CLOSE: + return wc->wmClose(); + case WM_DESTROY: + return wc->wmDestroy(); + case WM_APP_notifyFocus: + return wc->wmFocusNotify(!!i_wParam, + reinterpret_cast(i_lParam)); + case WM_APP_targetNotify: + return wc->wmTargetNotify(reinterpret_cast(i_lParam)); + case WM_APP_notifyVKey: + return wc->wmVkeyNotify( + static_cast(i_wParam), static_cast(i_lParam & 0xffff), + static_cast((i_lParam >> 16) & 0xff), + !!(i_lParam & (1 << 24)), + !!(i_lParam & (1 << 29)), + !!(i_lParam & (1 << 31))); + case WM_NCDESTROY: + delete wc; + return TRUE; + } + return FALSE; } diff --git a/dlginvestigate.h b/dlginvestigate.h index b02f2de..1b33137 100644 --- a/dlginvestigate.h +++ b/dlginvestigate.h @@ -14,16 +14,15 @@ INT_PTR CALLBACK dlgInvestigate_dlgProc( #else BOOL CALLBACK dlgInvestigate_dlgProc( #endif - HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam); + HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam); class Engine; /// parameters for "Investigate" dialog box -class DlgInvestigateData -{ +class DlgInvestigateData { public: - Engine *m_engine; /// engine - HWND m_hwndLog; /// log + Engine *m_engine; /// engine + HWND m_hwndLog; /// log }; diff --git a/dlglog.cpp b/dlglog.cpp index f9e5a9d..df79d5a 100644 --- a/dlglog.cpp +++ b/dlglog.cpp @@ -16,147 +16,136 @@ /// class DlgLog : public LayoutManager { - HWND m_hwndEdit; /// - HWND m_hwndTaskTray; /// tasktray window - LOGFONT m_lf; /// - HFONT m_hfontOriginal; /// - HFONT m_hfont; /// - tomsgstream *m_log; /// - + HWND m_hwndEdit; /// + HWND m_hwndTaskTray; /// tasktray window + LOGFONT m_lf; /// + HFONT m_hfontOriginal; /// + HFONT m_hfont; /// + tomsgstream *m_log; /// + public: - /// - DlgLog(HWND i_hwnd) - : LayoutManager(i_hwnd), - m_hwndEdit(GetDlgItem(m_hwnd, IDC_EDIT_log)), - m_hwndTaskTray(NULL), - m_hfontOriginal(GetWindowFont(m_hwnd)), - m_hfont(NULL) - { - } - - /// WM_INITDIALOG - BOOL wmInitDialog(HWND /* i_focus */, LPARAM i_lParam) - { - DlgLogData *dld = reinterpret_cast(i_lParam); - m_log = dld->m_log; - m_hwndTaskTray = dld->m_hwndTaskTray; - - // set icons - setSmallIcon(m_hwnd, IDI_ICON_mayu); - setBigIcon(m_hwnd, IDI_ICON_mayu); - - // set font - Registry::read(MAYU_REGISTRY_ROOT, _T("logFont"), &m_lf, - loadString(IDS_logFont)); - m_hfont = CreateFontIndirect(&m_lf); - SetWindowFont(m_hwndEdit, m_hfont, false); - - // resize - RECT rc; - CHECK_TRUE( GetClientRect(m_hwnd, &rc) ); - wmSize(0, (short)rc.right, (short)rc.bottom); - - // debug level - bool isChecked = - (IsDlgButtonChecked(m_hwnd, IDC_CHECK_detail) == BST_CHECKED); - m_log->setDebugLevel(isChecked ? 1 : 0); - - // set layout manager - typedef LayoutManager LM; - addItem(GetDlgItem(m_hwnd, IDOK), - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE, - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_EDIT_log), - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_BOTTOM_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_BUTTON_clearLog), - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE, - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_BUTTON_changeFont), - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE, - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_CHECK_detail), - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE, - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE); - restrictSmallestSize(); - - // enlarge window - GetWindowRect(m_hwnd, &rc); - rc.bottom += (rc.bottom - rc.top) * 3; - MoveWindow(m_hwnd, rc.left, rc.top, - rc.right - rc.left, rc.bottom - rc.top, true); - return TRUE; - } - - /// WM_DESTROY - BOOL wmDestroy() - { - // unset font - SetWindowFont(m_hwndEdit, m_hfontOriginal, false); - DeleteObject(m_hfont); - - // unset icons - unsetBigIcon(m_hwnd); - unsetSmallIcon(m_hwnd); - return TRUE; - } - - /// WM_CLOSE - BOOL wmClose() - { - ShowWindow(m_hwnd, SW_HIDE); - return TRUE; - } - - /// WM_COMMAND - BOOL wmCommand(int /* i_notifyCode */, int i_id, HWND /* i_hwndControl */) - { - switch (i_id) - { - case IDOK: - { - ShowWindow(m_hwnd, SW_HIDE); - return TRUE; - } - - case IDC_BUTTON_clearLog: - { - Edit_SetSel(m_hwndEdit, 0, Edit_GetTextLength(m_hwndEdit)); - Edit_ReplaceSel(m_hwndEdit, _T("")); - SendMessage(m_hwndTaskTray, WM_APP_dlglogNotify, - DlgLogNotify_logCleared, 0); - return TRUE; - } - - case IDC_BUTTON_changeFont: - { - CHOOSEFONT cf; - memset(&cf, 0, sizeof(cf)); - cf.lStructSize = sizeof(cf); - cf.hwndOwner = m_hwnd; - cf.lpLogFont = &m_lf; - cf.Flags = CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS; - if (ChooseFont(&cf)) - { - HFONT hfontNew = CreateFontIndirect(&m_lf); - SetWindowFont(m_hwnd, hfontNew, true); - DeleteObject(m_hfont); - m_hfont = hfontNew; - Registry::write(MAYU_REGISTRY_ROOT, _T("logFont"), m_lf); + /// + DlgLog(HWND i_hwnd) + : LayoutManager(i_hwnd), + m_hwndEdit(GetDlgItem(m_hwnd, IDC_EDIT_log)), + m_hwndTaskTray(NULL), + m_hfontOriginal(GetWindowFont(m_hwnd)), + m_hfont(NULL) { + } + + /// WM_INITDIALOG + BOOL wmInitDialog(HWND /* i_focus */, LPARAM i_lParam) { + DlgLogData *dld = reinterpret_cast(i_lParam); + m_log = dld->m_log; + m_hwndTaskTray = dld->m_hwndTaskTray; + + // set icons + setSmallIcon(m_hwnd, IDI_ICON_mayu); + setBigIcon(m_hwnd, IDI_ICON_mayu); + + // set font + Registry::read(MAYU_REGISTRY_ROOT, _T("logFont"), &m_lf, + loadString(IDS_logFont)); + m_hfont = CreateFontIndirect(&m_lf); + SetWindowFont(m_hwndEdit, m_hfont, false); + + // resize + RECT rc; + CHECK_TRUE( GetClientRect(m_hwnd, &rc) ); + wmSize(0, (short)rc.right, (short)rc.bottom); + + // debug level + bool isChecked = + (IsDlgButtonChecked(m_hwnd, IDC_CHECK_detail) == BST_CHECKED); + m_log->setDebugLevel(isChecked ? 1 : 0); + + // set layout manager + typedef LayoutManager LM; + addItem(GetDlgItem(m_hwnd, IDOK), + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE, + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_EDIT_log), + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_BOTTOM_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_BUTTON_clearLog), + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE, + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_BUTTON_changeFont), + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE, + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_CHECK_detail), + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE, + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_BOTTOM_EDGE); + restrictSmallestSize(); + + // enlarge window + GetWindowRect(m_hwnd, &rc); + rc.bottom += (rc.bottom - rc.top) * 3; + MoveWindow(m_hwnd, rc.left, rc.top, + rc.right - rc.left, rc.bottom - rc.top, true); + return TRUE; + } + + /// WM_DESTROY + BOOL wmDestroy() { + // unset font + SetWindowFont(m_hwndEdit, m_hfontOriginal, false); + DeleteObject(m_hfont); + + // unset icons + unsetBigIcon(m_hwnd); + unsetSmallIcon(m_hwnd); + return TRUE; + } + + /// WM_CLOSE + BOOL wmClose() { + ShowWindow(m_hwnd, SW_HIDE); + return TRUE; + } + + /// WM_COMMAND + BOOL wmCommand(int /* i_notifyCode */, int i_id, HWND /* i_hwndControl */) { + switch (i_id) { + case IDOK: { + ShowWindow(m_hwnd, SW_HIDE); + return TRUE; + } + + case IDC_BUTTON_clearLog: { + Edit_SetSel(m_hwndEdit, 0, Edit_GetTextLength(m_hwndEdit)); + Edit_ReplaceSel(m_hwndEdit, _T("")); + SendMessage(m_hwndTaskTray, WM_APP_dlglogNotify, + DlgLogNotify_logCleared, 0); + return TRUE; + } + + case IDC_BUTTON_changeFont: { + CHOOSEFONT cf; + memset(&cf, 0, sizeof(cf)); + cf.lStructSize = sizeof(cf); + cf.hwndOwner = m_hwnd; + cf.lpLogFont = &m_lf; + cf.Flags = CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS; + if (ChooseFont(&cf)) { + HFONT hfontNew = CreateFontIndirect(&m_lf); + SetWindowFont(m_hwnd, hfontNew, true); + DeleteObject(m_hfont); + m_hfont = hfontNew; + Registry::write(MAYU_REGISTRY_ROOT, _T("logFont"), m_lf); + } + return TRUE; + } + + case IDC_CHECK_detail: { + bool isChecked = + (IsDlgButtonChecked(m_hwnd, IDC_CHECK_detail) == BST_CHECKED); + m_log->setDebugLevel(isChecked ? 1 : 0); + return TRUE; + } + } + return FALSE; } - return TRUE; - } - - case IDC_CHECK_detail: - { - bool isChecked = - (IsDlgButtonChecked(m_hwnd, IDC_CHECK_detail) == BST_CHECKED); - m_log->setDebugLevel(isChecked ? 1 : 0); - return TRUE; - } - } - return FALSE; - } }; @@ -166,32 +155,30 @@ INT_PTR CALLBACK dlgLog_dlgProc(HWND i_hwnd, UINT i_message, #else BOOL CALLBACK dlgLog_dlgProc(HWND i_hwnd, UINT i_message, #endif - WPARAM i_wParam, LPARAM i_lParam) + WPARAM i_wParam, LPARAM i_lParam) { - DlgLog *wc; - getUserData(i_hwnd, &wc); - if (!wc) - switch (i_message) - { - case WM_INITDIALOG: - wc = setUserData(i_hwnd, new DlgLog(i_hwnd)); - return wc->wmInitDialog(reinterpret_cast(i_wParam), i_lParam); - } - else - switch (i_message) - { - case WM_COMMAND: - return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam), - reinterpret_cast(i_lParam)); - case WM_CLOSE: - return wc->wmClose(); - case WM_DESTROY: - return wc->wmDestroy(); - case WM_NCDESTROY: - delete wc; - return TRUE; - default: - return wc->defaultWMHandler(i_message, i_wParam, i_lParam); - } - return FALSE; + DlgLog *wc; + getUserData(i_hwnd, &wc); + if (!wc) + switch (i_message) { + case WM_INITDIALOG: + wc = setUserData(i_hwnd, new DlgLog(i_hwnd)); + return wc->wmInitDialog(reinterpret_cast(i_wParam), i_lParam); + } + else + switch (i_message) { + case WM_COMMAND: + return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam), + reinterpret_cast(i_lParam)); + case WM_CLOSE: + return wc->wmClose(); + case WM_DESTROY: + return wc->wmDestroy(); + case WM_NCDESTROY: + delete wc; + return TRUE; + default: + return wc->defaultWMHandler(i_message, i_wParam, i_lParam); + } + return FALSE; } diff --git a/dlglog.h b/dlglog.h index 54d8cd9..3fe8b02 100644 --- a/dlglog.h +++ b/dlglog.h @@ -15,25 +15,22 @@ INT_PTR CALLBACK dlgLog_dlgProc( #else BOOL CALLBACK dlgLog_dlgProc( #endif - HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam); + HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam); -enum -{ - /// - WM_APP_dlglogNotify = WM_APP + 115, +enum { + /// + WM_APP_dlglogNotify = WM_APP + 115, }; -enum DlgLogNotify -{ - DlgLogNotify_logCleared, /// +enum DlgLogNotify { + DlgLogNotify_logCleared, /// }; /// parameters for "Investigate" dialog box -class DlgLogData -{ +class DlgLogData { public: - tomsgstream *m_log; /// log stream - HWND m_hwndTaskTray; /// tasktray window + tomsgstream *m_log; /// log stream + HWND m_hwndTaskTray; /// tasktray window }; #endif // !_DLGLOG_H diff --git a/dlgsetting.cpp b/dlgsetting.cpp index cd99da6..e07ab91 100644 --- a/dlgsetting.cpp +++ b/dlgsetting.cpp @@ -20,323 +20,297 @@ /// class DlgSetting : public LayoutManager { - HWND m_hwndMayuPaths; /// - - /// - Registry m_reg; - - typedef DlgEditSettingData Data; /// - - /// - void insertItem(int i_index, const Data &i_data) - { - LVITEM item; - item.mask = LVIF_TEXT; - item.iItem = i_index; - - item.iSubItem = 0; - item.pszText = const_cast<_TCHAR *>(i_data.m_name.c_str()); - CHECK_TRUE( ListView_InsertItem(m_hwndMayuPaths, &item) != -1 ); - - ListView_SetItemText(m_hwndMayuPaths, i_index, 1, - const_cast<_TCHAR *>(i_data.m_filename.c_str())); - ListView_SetItemText(m_hwndMayuPaths, i_index, 2, - const_cast<_TCHAR *>(i_data.m_symbols.c_str())); - } - - /// - void setItem(int i_index, const Data &i_data) - { - ListView_SetItemText(m_hwndMayuPaths, i_index, 0, - const_cast<_TCHAR *>(i_data.m_name.c_str())); - ListView_SetItemText(m_hwndMayuPaths, i_index, 1, - const_cast<_TCHAR *>(i_data.m_filename.c_str())); - ListView_SetItemText(m_hwndMayuPaths, i_index, 2, - const_cast<_TCHAR *>(i_data.m_symbols.c_str())); - } - - /// - void getItem(int i_index, Data *o_data) - { - _TCHAR buf[GANA_MAX_PATH]; - LVITEM item; - item.mask = LVIF_TEXT; - item.iItem = i_index; - item.pszText = buf; - item.cchTextMax = NUMBER_OF(buf); - - item.iSubItem = 0; - CHECK_TRUE( ListView_GetItem(m_hwndMayuPaths, &item) ); - o_data->m_name = item.pszText; - - item.iSubItem = 1; - CHECK_TRUE( ListView_GetItem(m_hwndMayuPaths, &item) ); - o_data->m_filename = item.pszText; - - item.iSubItem = 2; - CHECK_TRUE( ListView_GetItem(m_hwndMayuPaths, &item) ); - o_data->m_symbols = item.pszText; - } - - /// - void setSelectedItem(int i_index) - { - ListView_SetItemState(m_hwndMayuPaths, i_index, - LVIS_SELECTED, LVIS_SELECTED); - } - - /// - int getSelectedItem() - { - if (ListView_GetSelectedCount(m_hwndMayuPaths) == 0) - return -1; - for (int i = 0; ; ++ i) - { - if (ListView_GetItemState(m_hwndMayuPaths, i, LVIS_SELECTED)) - return i; - } - } + HWND m_hwndMayuPaths; /// + + /// + Registry m_reg; + + typedef DlgEditSettingData Data; /// + + /// + void insertItem(int i_index, const Data &i_data) { + LVITEM item; + item.mask = LVIF_TEXT; + item.iItem = i_index; + + item.iSubItem = 0; + item.pszText = const_cast<_TCHAR *>(i_data.m_name.c_str()); + CHECK_TRUE( ListView_InsertItem(m_hwndMayuPaths, &item) != -1 ); + + ListView_SetItemText(m_hwndMayuPaths, i_index, 1, + const_cast<_TCHAR *>(i_data.m_filename.c_str())); + ListView_SetItemText(m_hwndMayuPaths, i_index, 2, + const_cast<_TCHAR *>(i_data.m_symbols.c_str())); + } + + /// + void setItem(int i_index, const Data &i_data) { + ListView_SetItemText(m_hwndMayuPaths, i_index, 0, + const_cast<_TCHAR *>(i_data.m_name.c_str())); + ListView_SetItemText(m_hwndMayuPaths, i_index, 1, + const_cast<_TCHAR *>(i_data.m_filename.c_str())); + ListView_SetItemText(m_hwndMayuPaths, i_index, 2, + const_cast<_TCHAR *>(i_data.m_symbols.c_str())); + } + + /// + void getItem(int i_index, Data *o_data) { + _TCHAR buf[GANA_MAX_PATH]; + LVITEM item; + item.mask = LVIF_TEXT; + item.iItem = i_index; + item.pszText = buf; + item.cchTextMax = NUMBER_OF(buf); + + item.iSubItem = 0; + CHECK_TRUE( ListView_GetItem(m_hwndMayuPaths, &item) ); + o_data->m_name = item.pszText; + + item.iSubItem = 1; + CHECK_TRUE( ListView_GetItem(m_hwndMayuPaths, &item) ); + o_data->m_filename = item.pszText; + + item.iSubItem = 2; + CHECK_TRUE( ListView_GetItem(m_hwndMayuPaths, &item) ); + o_data->m_symbols = item.pszText; + } + + /// + void setSelectedItem(int i_index) { + ListView_SetItemState(m_hwndMayuPaths, i_index, + LVIS_SELECTED, LVIS_SELECTED); + } + + /// + int getSelectedItem() { + if (ListView_GetSelectedCount(m_hwndMayuPaths) == 0) + return -1; + for (int i = 0; ; ++ i) { + if (ListView_GetItemState(m_hwndMayuPaths, i, LVIS_SELECTED)) + return i; + } + } public: - /// - DlgSetting(HWND i_hwnd) - : LayoutManager(i_hwnd), - m_hwndMayuPaths(NULL), - m_reg(MAYU_REGISTRY_ROOT) - { - } - - /// WM_INITDIALOG - BOOL wmInitDialog(HWND /* i_focus */, LPARAM /* i_lParam */) - { - setSmallIcon(m_hwnd, IDI_ICON_mayu); - setBigIcon(m_hwnd, IDI_ICON_mayu); - - CHECK_TRUE( m_hwndMayuPaths = GetDlgItem(m_hwnd, IDC_LIST_mayuPaths) ); - - // create list view colmn - RECT rc; - GetClientRect(m_hwndMayuPaths, &rc); - - LVCOLUMN lvc; - lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT; - lvc.fmt = LVCFMT_LEFT; - lvc.cx = (rc.right - rc.left) / 3; - - tstringi str = loadString(IDS_mayuPathName); - lvc.pszText = const_cast<_TCHAR *>(str.c_str()); - CHECK( 0 ==, ListView_InsertColumn(m_hwndMayuPaths, 0, &lvc) ); - str = loadString(IDS_mayuPath); - lvc.pszText = const_cast<_TCHAR *>(str.c_str()); - CHECK( 1 ==, ListView_InsertColumn(m_hwndMayuPaths, 1, &lvc) ); - str = loadString(IDS_mayuSymbols); - lvc.pszText = const_cast<_TCHAR *>(str.c_str()); - CHECK( 2 ==, ListView_InsertColumn(m_hwndMayuPaths, 2, &lvc) ); - - Data data; - insertItem(0, data); // TODO: why ? - - // set list view - tregex split(_T("^([^;]*);([^;]*);(.*)$")); - tstringi dot_mayu; - int i; - for (i = 0; i < MAX_MAYU_REGISTRY_ENTRIES; ++ i) - { - _TCHAR buf[100]; - _sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), i); - if (!m_reg.read(buf, &dot_mayu)) - break; - - tsmatch what; - if (boost::regex_match(dot_mayu, what, split)) - { - data.m_name = what.str(1); - data.m_filename = what.str(2); - data.m_symbols = what.str(3); - insertItem(i, data); - } - } - - CHECK_TRUE( ListView_DeleteItem(m_hwndMayuPaths, i) ); // TODO: why ? - - // arrange list view size - ListView_SetColumnWidth(m_hwndMayuPaths, 0, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(m_hwndMayuPaths, 1, LVSCW_AUTOSIZE); - ListView_SetColumnWidth(m_hwndMayuPaths, 2, LVSCW_AUTOSIZE); - - ListView_SetExtendedListViewStyle(m_hwndMayuPaths, LVS_EX_FULLROWSELECT); - - // set selection - int index; - m_reg.read(_T(".mayuIndex"), &index, 0); - setSelectedItem(index); - - // set layout manager - typedef LayoutManager LM; - addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuPaths), - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_BOTTOM_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_LIST_mayuPaths), - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_BOTTOM_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_BUTTON_up), - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_CENTER, - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_CENTER); - addItem(GetDlgItem(m_hwnd, IDC_BUTTON_down), - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_CENTER, - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_CENTER); - addItem(GetDlgItem(m_hwnd, IDC_BUTTON_add), - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_BUTTON_edit), - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_BUTTON_delete), - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); - addItem(GetDlgItem(m_hwnd, IDCANCEL), - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); - addItem(GetDlgItem(m_hwnd, IDOK), - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); - restrictSmallestSize(); - return TRUE; - } - - /// WM_CLOSE - BOOL wmClose() - { - EndDialog(m_hwnd, 0); - return TRUE; - } - - /// WM_NOTIFY - BOOL wmNotify(int i_id, NMHDR *i_nmh) - { - switch (i_id) - { - case IDC_LIST_mayuPaths: - if (i_nmh->code == NM_DBLCLK) - FORWARD_WM_COMMAND(m_hwnd, IDC_BUTTON_edit, NULL, 0, SendMessage); - return TRUE; - } - return TRUE; - } - - /// WM_COMMAND - BOOL wmCommand(int /* i_notifyCode */, int i_id, HWND /* i_hwndControl */) - { - _TCHAR buf[GANA_MAX_PATH]; - switch (i_id) - { - case IDC_BUTTON_up: - case IDC_BUTTON_down: - { - int count = ListView_GetItemCount(m_hwndMayuPaths); - if (count < 2) - return TRUE; - int index = getSelectedItem(); - if (index < 0 || - (i_id == IDC_BUTTON_up && index == 0) || - (i_id == IDC_BUTTON_down && index == count - 1)) - return TRUE; - - int target = (i_id == IDC_BUTTON_up) ? index - 1 : index + 1; - - Data dataIndex, dataTarget; - getItem(index, &dataIndex); - getItem(target, &dataTarget); - setItem(index, dataTarget); - setItem(target, dataIndex); - - setSelectedItem(target); - return TRUE; - } - - case IDC_BUTTON_add: - { - Data data; - int index = getSelectedItem(); - if (0 <= index) - getItem(index, &data); - if (DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_editSetting), - m_hwnd, dlgEditSetting_dlgProc, (LPARAM)&data)) - if (!data.m_name.empty()) - { - insertItem(0, data); - setSelectedItem(0); - } - return TRUE; - } - - case IDC_BUTTON_delete: - { - int index = getSelectedItem(); - if (0 <= index) - { - CHECK_TRUE( ListView_DeleteItem(m_hwndMayuPaths, index) ); - int count = ListView_GetItemCount(m_hwndMayuPaths); - if (count == 0) - ; - else if (count == index) - setSelectedItem(index - 1); - else - setSelectedItem(index); + /// + DlgSetting(HWND i_hwnd) + : LayoutManager(i_hwnd), + m_hwndMayuPaths(NULL), + m_reg(MAYU_REGISTRY_ROOT) { + } + + /// WM_INITDIALOG + BOOL wmInitDialog(HWND /* i_focus */, LPARAM /* i_lParam */) { + setSmallIcon(m_hwnd, IDI_ICON_mayu); + setBigIcon(m_hwnd, IDI_ICON_mayu); + + CHECK_TRUE( m_hwndMayuPaths = GetDlgItem(m_hwnd, IDC_LIST_mayuPaths) ); + + // create list view colmn + RECT rc; + GetClientRect(m_hwndMayuPaths, &rc); + + LVCOLUMN lvc; + lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT; + lvc.fmt = LVCFMT_LEFT; + lvc.cx = (rc.right - rc.left) / 3; + + tstringi str = loadString(IDS_mayuPathName); + lvc.pszText = const_cast<_TCHAR *>(str.c_str()); + CHECK( 0 ==, ListView_InsertColumn(m_hwndMayuPaths, 0, &lvc) ); + str = loadString(IDS_mayuPath); + lvc.pszText = const_cast<_TCHAR *>(str.c_str()); + CHECK( 1 ==, ListView_InsertColumn(m_hwndMayuPaths, 1, &lvc) ); + str = loadString(IDS_mayuSymbols); + lvc.pszText = const_cast<_TCHAR *>(str.c_str()); + CHECK( 2 ==, ListView_InsertColumn(m_hwndMayuPaths, 2, &lvc) ); + + Data data; + insertItem(0, data); // TODO: why ? + + // set list view + tregex split(_T("^([^;]*);([^;]*);(.*)$")); + tstringi dot_mayu; + int i; + for (i = 0; i < MAX_MAYU_REGISTRY_ENTRIES; ++ i) { + _TCHAR buf[100]; + _sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), i); + if (!m_reg.read(buf, &dot_mayu)) + break; + + tsmatch what; + if (boost::regex_match(dot_mayu, what, split)) { + data.m_name = what.str(1); + data.m_filename = what.str(2); + data.m_symbols = what.str(3); + insertItem(i, data); + } + } + + CHECK_TRUE( ListView_DeleteItem(m_hwndMayuPaths, i) ); // TODO: why ? + + // arrange list view size + ListView_SetColumnWidth(m_hwndMayuPaths, 0, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(m_hwndMayuPaths, 1, LVSCW_AUTOSIZE); + ListView_SetColumnWidth(m_hwndMayuPaths, 2, LVSCW_AUTOSIZE); + + ListView_SetExtendedListViewStyle(m_hwndMayuPaths, LVS_EX_FULLROWSELECT); + + // set selection + int index; + m_reg.read(_T(".mayuIndex"), &index, 0); + setSelectedItem(index); + + // set layout manager + typedef LayoutManager LM; + addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuPaths), + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_BOTTOM_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_LIST_mayuPaths), + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_BOTTOM_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_BUTTON_up), + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_CENTER, + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_CENTER); + addItem(GetDlgItem(m_hwnd, IDC_BUTTON_down), + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_CENTER, + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_CENTER); + addItem(GetDlgItem(m_hwnd, IDC_BUTTON_add), + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_BUTTON_edit), + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_BUTTON_delete), + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); + addItem(GetDlgItem(m_hwnd, IDCANCEL), + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); + addItem(GetDlgItem(m_hwnd, IDOK), + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); + restrictSmallestSize(); + return TRUE; } - return TRUE; - } - - case IDC_BUTTON_edit: - { - Data data; - int index = getSelectedItem(); - if (index < 0) - return TRUE; - getItem(index, &data); - if (DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_editSetting), - m_hwnd, dlgEditSetting_dlgProc, (LPARAM)&data)) - { - setItem(index, data); - setSelectedItem(index); + + /// WM_CLOSE + BOOL wmClose() { + EndDialog(m_hwnd, 0); + return TRUE; } - return TRUE; - } - - case IDOK: - { - int count = ListView_GetItemCount(m_hwndMayuPaths); - int index; - for (index = 0; index < count; ++ index) - { - _sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index); - Data data; - getItem(index, &data); - m_reg.write(buf, data.m_name + _T(";") + - data.m_filename + _T(";") + data.m_symbols); + + /// WM_NOTIFY + BOOL wmNotify(int i_id, NMHDR *i_nmh) { + switch (i_id) { + case IDC_LIST_mayuPaths: + if (i_nmh->code == NM_DBLCLK) + FORWARD_WM_COMMAND(m_hwnd, IDC_BUTTON_edit, NULL, 0, SendMessage); + return TRUE; + } + return TRUE; } - for (; ; ++ index) - { - _sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index); - if (!m_reg.remove(buf)) - break; + + /// WM_COMMAND + BOOL wmCommand(int /* i_notifyCode */, int i_id, HWND /* i_hwndControl */) { + _TCHAR buf[GANA_MAX_PATH]; + switch (i_id) { + case IDC_BUTTON_up: + case IDC_BUTTON_down: { + int count = ListView_GetItemCount(m_hwndMayuPaths); + if (count < 2) + return TRUE; + int index = getSelectedItem(); + if (index < 0 || + (i_id == IDC_BUTTON_up && index == 0) || + (i_id == IDC_BUTTON_down && index == count - 1)) + return TRUE; + + int target = (i_id == IDC_BUTTON_up) ? index - 1 : index + 1; + + Data dataIndex, dataTarget; + getItem(index, &dataIndex); + getItem(target, &dataTarget); + setItem(index, dataTarget); + setItem(target, dataIndex); + + setSelectedItem(target); + return TRUE; + } + + case IDC_BUTTON_add: { + Data data; + int index = getSelectedItem(); + if (0 <= index) + getItem(index, &data); + if (DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_editSetting), + m_hwnd, dlgEditSetting_dlgProc, (LPARAM)&data)) + if (!data.m_name.empty()) { + insertItem(0, data); + setSelectedItem(0); + } + return TRUE; + } + + case IDC_BUTTON_delete: { + int index = getSelectedItem(); + if (0 <= index) { + CHECK_TRUE( ListView_DeleteItem(m_hwndMayuPaths, index) ); + int count = ListView_GetItemCount(m_hwndMayuPaths); + if (count == 0) + ; + else if (count == index) + setSelectedItem(index - 1); + else + setSelectedItem(index); + } + return TRUE; + } + + case IDC_BUTTON_edit: { + Data data; + int index = getSelectedItem(); + if (index < 0) + return TRUE; + getItem(index, &data); + if (DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_editSetting), + m_hwnd, dlgEditSetting_dlgProc, (LPARAM)&data)) { + setItem(index, data); + setSelectedItem(index); + } + return TRUE; + } + + case IDOK: { + int count = ListView_GetItemCount(m_hwndMayuPaths); + int index; + for (index = 0; index < count; ++ index) { + _sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index); + Data data; + getItem(index, &data); + m_reg.write(buf, data.m_name + _T(";") + + data.m_filename + _T(";") + data.m_symbols); + } + for (; ; ++ index) { + _sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index); + if (!m_reg.remove(buf)) + break; + } + index = getSelectedItem(); + if (index < 0) + index = 0; + m_reg.write(_T(".mayuIndex"), index); + EndDialog(m_hwnd, 1); + return TRUE; + } + + case IDCANCEL: { + CHECK_TRUE( EndDialog(m_hwnd, 0) ); + return TRUE; + } + } + return FALSE; } - index = getSelectedItem(); - if (index < 0) - index = 0; - m_reg.write(_T(".mayuIndex"), index); - EndDialog(m_hwnd, 1); - return TRUE; - } - - case IDCANCEL: - { - CHECK_TRUE( EndDialog(m_hwnd, 0) ); - return TRUE; - } - } - return FALSE; - } }; @@ -346,33 +320,31 @@ INT_PTR CALLBACK dlgSetting_dlgProc( #else BOOL CALLBACK dlgSetting_dlgProc( #endif - HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam) + HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam) { - DlgSetting *wc; - getUserData(i_hwnd, &wc); - if (!wc) - switch (i_message) - { - case WM_INITDIALOG: - wc = setUserData(i_hwnd, new DlgSetting(i_hwnd)); - return wc->wmInitDialog(reinterpret_cast(i_wParam), i_lParam); - } - else - switch (i_message) - { - case WM_COMMAND: - return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam), - reinterpret_cast(i_lParam)); - case WM_CLOSE: - return wc->wmClose(); - case WM_NCDESTROY: - delete wc; - return TRUE; - case WM_NOTIFY: - return wc->wmNotify(static_cast(i_wParam), - reinterpret_cast(i_lParam)); - default: - return wc->defaultWMHandler(i_message, i_wParam, i_lParam); - } - return FALSE; + DlgSetting *wc; + getUserData(i_hwnd, &wc); + if (!wc) + switch (i_message) { + case WM_INITDIALOG: + wc = setUserData(i_hwnd, new DlgSetting(i_hwnd)); + return wc->wmInitDialog(reinterpret_cast(i_wParam), i_lParam); + } + else + switch (i_message) { + case WM_COMMAND: + return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam), + reinterpret_cast(i_lParam)); + case WM_CLOSE: + return wc->wmClose(); + case WM_NCDESTROY: + delete wc; + return TRUE; + case WM_NOTIFY: + return wc->wmNotify(static_cast(i_wParam), + reinterpret_cast(i_lParam)); + default: + return wc->defaultWMHandler(i_message, i_wParam, i_lParam); + } + return FALSE; } diff --git a/dlgsetting.h b/dlgsetting.h index 7f742ba..2d6967d 100644 --- a/dlgsetting.h +++ b/dlgsetting.h @@ -14,7 +14,7 @@ INT_PTR CALLBACK dlgSetting_dlgProc( #else BOOL CALLBACK dlgSetting_dlgProc( #endif - HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam); + HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam); #endif // !_DLGSETTING_H diff --git a/dlgversion.cpp b/dlgversion.cpp old mode 100755 new mode 100644 index aa27918..d2097bb --- a/dlgversion.cpp +++ b/dlgversion.cpp @@ -17,93 +17,86 @@ /// class DlgVersion : public LayoutManager { - HWND m_hwnd; /// - + HWND m_hwnd; /// + public: - /// - DlgVersion(HWND i_hwnd) - : LayoutManager(i_hwnd), - m_hwnd(i_hwnd) - { - } - - /// WM_INITDIALOG - BOOL wmInitDialog(HWND /* i_focus */, LPARAM i_lParam) - { - TCHAR *mayudVersion = (TCHAR*)i_lParam; - setSmallIcon(m_hwnd, IDI_ICON_mayu); - setBigIcon(m_hwnd, IDI_ICON_mayu); - - _TCHAR modulebuf[1024]; - CHECK_TRUE( GetModuleFileName(g_hInst, modulebuf, - NUMBER_OF(modulebuf)) ); - - _TCHAR buf[1024]; - _sntprintf(buf, NUMBER_OF(buf), loadString(IDS_version).c_str(), - _T(VERSION) + /// + DlgVersion(HWND i_hwnd) + : LayoutManager(i_hwnd), + m_hwnd(i_hwnd) { + } + + /// WM_INITDIALOG + BOOL wmInitDialog(HWND /* i_focus */, LPARAM i_lParam) { + TCHAR *mayudVersion = (TCHAR*)i_lParam; + setSmallIcon(m_hwnd, IDI_ICON_mayu); + setBigIcon(m_hwnd, IDI_ICON_mayu); + + _TCHAR modulebuf[1024]; + CHECK_TRUE( GetModuleFileName(g_hInst, modulebuf, + NUMBER_OF(modulebuf)) ); + + _TCHAR buf[1024]; + _sntprintf(buf, NUMBER_OF(buf), loadString(IDS_version).c_str(), + _T(VERSION) #ifndef NDEBUG - _T(" (DEBUG)") + _T(" (DEBUG)") #endif // !NDEBUG #ifdef _UNICODE - _T(" (UNICODE)") + _T(" (UNICODE)") #endif // !_UNICODE - , - loadString(IDS_homepage).c_str(), - (_T(LOGNAME) _T("@") + toLower(_T(COMPUTERNAME))).c_str(), - _T(__DATE__) _T(" ") _T(__TIME__), - getCompilerVersionString().c_str(), - modulebuf); - - - Edit_SetText(GetDlgItem(m_hwnd, IDC_EDIT_builtBy), buf); - - // set layout manager - typedef LayoutManager LM; - - addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuIcon), - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_EDIT_builtBy), - LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, - LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_BOTTOM_EDGE); - addItem(GetDlgItem(m_hwnd, IDC_BUTTON_download), - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); - addItem(GetDlgItem(m_hwnd, IDOK), - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, - LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); - restrictSmallestSize(); - - return TRUE; - } - - /// WM_CLOSE - BOOL wmClose() - { - CHECK_TRUE( EndDialog(m_hwnd, 0) ); - return TRUE; - } - - /// WM_COMMAND - BOOL wmCommand(int /* i_notifyCode */, int i_id, HWND /* i_hwndControl */) - { - switch (i_id) - { - case IDOK: - { - CHECK_TRUE( EndDialog(m_hwnd, 0) ); - return TRUE; - } - case IDC_BUTTON_download: - { - ShellExecute(NULL, NULL, loadString(IDS_homepage).c_str(), - NULL, NULL, SW_SHOWNORMAL); - CHECK_TRUE( EndDialog(m_hwnd, 0) ); - return TRUE; - } - } - return FALSE; - } + , + loadString(IDS_homepage).c_str(), + (_T(LOGNAME) _T("@") + toLower(_T(COMPUTERNAME))).c_str(), + _T(__DATE__) _T(" ") _T(__TIME__), + getCompilerVersionString().c_str(), + modulebuf); + + + Edit_SetText(GetDlgItem(m_hwnd, IDC_EDIT_builtBy), buf); + + // set layout manager + typedef LayoutManager LM; + + addItem(GetDlgItem(m_hwnd, IDC_STATIC_mayuIcon), + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_EDIT_builtBy), + LM::ORIGIN_LEFT_EDGE, LM::ORIGIN_TOP_EDGE, + LM::ORIGIN_RIGHT_EDGE, LM::ORIGIN_BOTTOM_EDGE); + addItem(GetDlgItem(m_hwnd, IDC_BUTTON_download), + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); + addItem(GetDlgItem(m_hwnd, IDOK), + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE, + LM::ORIGIN_CENTER, LM::ORIGIN_BOTTOM_EDGE); + restrictSmallestSize(); + + return TRUE; + } + + /// WM_CLOSE + BOOL wmClose() { + CHECK_TRUE( EndDialog(m_hwnd, 0) ); + return TRUE; + } + + /// WM_COMMAND + BOOL wmCommand(int /* i_notifyCode */, int i_id, HWND /* i_hwndControl */) { + switch (i_id) { + case IDOK: { + CHECK_TRUE( EndDialog(m_hwnd, 0) ); + return TRUE; + } + case IDC_BUTTON_download: { + ShellExecute(NULL, NULL, loadString(IDS_homepage).c_str(), + NULL, NULL, SW_SHOWNORMAL); + CHECK_TRUE( EndDialog(m_hwnd, 0) ); + return TRUE; + } + } + return FALSE; + } }; @@ -113,30 +106,28 @@ INT_PTR CALLBACK dlgVersion_dlgProc( #else BOOL CALLBACK dlgVersion_dlgProc( #endif - HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam) + HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam) { - DlgVersion *wc; - getUserData(i_hwnd, &wc); - if (!wc) - switch (i_message) - { - case WM_INITDIALOG: - wc = setUserData(i_hwnd, new DlgVersion(i_hwnd)); - return wc->wmInitDialog(reinterpret_cast(i_wParam), i_lParam); - } - else - switch (i_message) - { - case WM_COMMAND: - return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam), - reinterpret_cast(i_lParam)); - case WM_CLOSE: - return wc->wmClose(); - case WM_NCDESTROY: - delete wc; - return TRUE; - default: - return wc->defaultWMHandler(i_message, i_wParam, i_lParam); - } - return FALSE; + DlgVersion *wc; + getUserData(i_hwnd, &wc); + if (!wc) + switch (i_message) { + case WM_INITDIALOG: + wc = setUserData(i_hwnd, new DlgVersion(i_hwnd)); + return wc->wmInitDialog(reinterpret_cast(i_wParam), i_lParam); + } + else + switch (i_message) { + case WM_COMMAND: + return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam), + reinterpret_cast(i_lParam)); + case WM_CLOSE: + return wc->wmClose(); + case WM_NCDESTROY: + delete wc; + return TRUE; + default: + return wc->defaultWMHandler(i_message, i_wParam, i_lParam); + } + return FALSE; } diff --git a/dlgversion.h b/dlgversion.h index 3e2f480..ff1021c 100644 --- a/dlgversion.h +++ b/dlgversion.h @@ -14,7 +14,7 @@ INT_PTR CALLBACK dlgVersion_dlgProc( #else BOOL CALLBACK dlgVersion_dlgProc( #endif - HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam); + HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam); #endif // !_DLGVERSION_H diff --git a/driver.h b/driver.h index abcf94d..73898f9 100644 --- a/driver.h +++ b/driver.h @@ -21,40 +21,39 @@ class KEYBOARD_INPUT_DATA { public: - /// - enum - { - /// key release flag - BREAK = 1, - /// extended key flag - E0 = 2, - /// extended key flag - E1 = 4, - /// extended key flag (E0 | E1) - E0E1 = 6, - /// - TERMSRV_SET_LED = 8, - /// Define the keyboard overrun MakeCode. - KEYBOARD_OVERRUN_MAKE_CODE_ = 0xFF, - }; + /// + enum { + /// key release flag + BREAK = 1, + /// extended key flag + E0 = 2, + /// extended key flag + E1 = 4, + /// extended key flag (E0 | E1) + E0E1 = 6, + /// + TERMSRV_SET_LED = 8, + /// Define the keyboard overrun MakeCode. + KEYBOARD_OVERRUN_MAKE_CODE_ = 0xFF, + }; public: - /** Unit number. E.g., for \Device\KeyboardPort0 the unit is '0', for - \Device\KeyboardPort1 the unit is '1', and so on. */ - USHORT UnitId; - - /** The "make" scan code (key depression). */ - USHORT MakeCode; - - /** The flags field indicates a "break" (key release) and other miscellaneous - scan code information defined above. */ - USHORT Flags; - - /// - USHORT Reserved; - - /** Device-specific additional information for the event. */ - ULONG ExtraInformation; + /** Unit number. E.g., for \Device\KeyboardPort0 the unit is '0', for + \Device\KeyboardPort1 the unit is '1', and so on. */ + USHORT UnitId; + + /** The "make" scan code (key depression). */ + USHORT MakeCode; + + /** The flags field indicates a "break" (key release) and other miscellaneous + scan code information defined above. */ + USHORT Flags; + + /// + USHORT Reserved; + + /** Device-specific additional information for the event. */ + ULONG ExtraInformation; }; diff --git a/engine.cpp b/engine.cpp index fe7f959..4c74873 100644 --- a/engine.cpp +++ b/engine.cpp @@ -18,119 +18,107 @@ // check focus window void Engine::checkFocusWindow() { - int count = 0; - - restart: - count ++; - - HWND hwndFore = GetForegroundWindow(); - DWORD threadId = GetWindowThreadProcessId(hwndFore, NULL); - - if (hwndFore) - { - { - Acquire a(&m_cs); - if (m_currentFocusOfThread && - m_currentFocusOfThread->m_threadId == threadId && - m_currentFocusOfThread->m_hwndFocus == m_hwndFocus) - return; - - m_emacsEditKillLine.reset(); - - // erase dead thread - if (!m_detachedThreadIds.empty()) - { - for (DetachedThreadIds::iterator i = m_detachedThreadIds.begin(); - i != m_detachedThreadIds.end(); i ++) - { - FocusOfThreads::iterator j = m_focusOfThreads.find((*i)); - if (j != m_focusOfThreads.end()) - { - FocusOfThread *fot = &((*j).second); - Acquire a(&m_log, 1); - m_log << _T("RemoveThread") << std::endl; - m_log << _T("\tHWND:\t") << std::hex << (int)fot->m_hwndFocus - << std::dec << std::endl; - m_log << _T("\tTHREADID:") << fot->m_threadId << std::endl; - m_log << _T("\tCLASS:\t") << fot->m_className << std::endl; - m_log << _T("\tTITLE:\t") << fot->m_titleName << std::endl; - m_log << std::endl; - m_focusOfThreads.erase(j); - } + int count = 0; + +restart: + count ++; + + HWND hwndFore = GetForegroundWindow(); + DWORD threadId = GetWindowThreadProcessId(hwndFore, NULL); + + if (hwndFore) { + { + Acquire a(&m_cs); + if (m_currentFocusOfThread && + m_currentFocusOfThread->m_threadId == threadId && + m_currentFocusOfThread->m_hwndFocus == m_hwndFocus) + return; + + m_emacsEditKillLine.reset(); + + // erase dead thread + if (!m_detachedThreadIds.empty()) { + for (DetachedThreadIds::iterator i = m_detachedThreadIds.begin(); + i != m_detachedThreadIds.end(); i ++) { + FocusOfThreads::iterator j = m_focusOfThreads.find((*i)); + if (j != m_focusOfThreads.end()) { + FocusOfThread *fot = &((*j).second); + Acquire a(&m_log, 1); + m_log << _T("RemoveThread") << std::endl; + m_log << _T("\tHWND:\t") << std::hex << (int)fot->m_hwndFocus + << std::dec << std::endl; + m_log << _T("\tTHREADID:") << fot->m_threadId << std::endl; + m_log << _T("\tCLASS:\t") << fot->m_className << std::endl; + m_log << _T("\tTITLE:\t") << fot->m_titleName << std::endl; + m_log << std::endl; + m_focusOfThreads.erase(j); + } + } + m_detachedThreadIds.erase + (m_detachedThreadIds.begin(), m_detachedThreadIds.end()); + } + + FocusOfThreads::iterator i = m_focusOfThreads.find(threadId); + if (i != m_focusOfThreads.end()) { + m_currentFocusOfThread = &((*i).second); + if (!m_currentFocusOfThread->m_isConsole || 2 <= count) { + if (m_currentFocusOfThread->m_keymaps.empty()) + setCurrentKeymap(NULL); + else + setCurrentKeymap(*m_currentFocusOfThread->m_keymaps.begin()); + m_hwndFocus = m_currentFocusOfThread->m_hwndFocus; + checkShow(m_hwndFocus); + + Acquire a(&m_log, 1); + m_log << _T("FocusChanged") << std::endl; + m_log << _T("\tHWND:\t") + << std::hex << (int)m_currentFocusOfThread->m_hwndFocus + << std::dec << std::endl; + m_log << _T("\tTHREADID:") + << m_currentFocusOfThread->m_threadId << std::endl; + m_log << _T("\tCLASS:\t") + << m_currentFocusOfThread->m_className << std::endl; + m_log << _T("\tTITLE:\t") + << m_currentFocusOfThread->m_titleName << std::endl; + m_log << std::endl; + return; + } + } + } + + _TCHAR className[GANA_MAX_ATOM_LENGTH]; + if (GetClassName(hwndFore, className, NUMBER_OF(className))) { + if (_tcsicmp(className, _T("ConsoleWindowClass")) == 0) { + _TCHAR titleName[1024]; + if (GetWindowText(hwndFore, titleName, NUMBER_OF(titleName)) == 0) + titleName[0] = _T('\0'); + setFocus(hwndFore, threadId, className, titleName, true); + Acquire a(&m_log, 1); + m_log << _T("HWND:\t") << std::hex << reinterpret_cast(hwndFore) + << std::dec << std::endl; + m_log << _T("THREADID:") << threadId << std::endl; + m_log << _T("CLASS:\t") << className << std::endl; + m_log << _T("TITLE:\t") << titleName << std::endl << std::endl; + goto restart; + } + } } - m_detachedThreadIds.erase - (m_detachedThreadIds.begin(), m_detachedThreadIds.end()); - } - - FocusOfThreads::iterator i = m_focusOfThreads.find(threadId); - if (i != m_focusOfThreads.end()) - { - m_currentFocusOfThread = &((*i).second); - if (!m_currentFocusOfThread->m_isConsole || 2 <= count) - { - if (m_currentFocusOfThread->m_keymaps.empty()) - setCurrentKeymap(NULL); - else - setCurrentKeymap(*m_currentFocusOfThread->m_keymaps.begin()); - m_hwndFocus = m_currentFocusOfThread->m_hwndFocus; - checkShow(m_hwndFocus); - - Acquire a(&m_log, 1); - m_log << _T("FocusChanged") << std::endl; - m_log << _T("\tHWND:\t") - << std::hex << (int)m_currentFocusOfThread->m_hwndFocus - << std::dec << std::endl; - m_log << _T("\tTHREADID:") - << m_currentFocusOfThread->m_threadId << std::endl; - m_log << _T("\tCLASS:\t") - << m_currentFocusOfThread->m_className << std::endl; - m_log << _T("\tTITLE:\t") - << m_currentFocusOfThread->m_titleName << std::endl; - m_log << std::endl; - return; + + Acquire a(&m_cs); + if (m_globalFocus.m_keymaps.empty()) { + Acquire a(&m_log, 1); + m_log << _T("NO GLOBAL FOCUS") << std::endl; + m_currentFocusOfThread = NULL; + setCurrentKeymap(NULL); + } else { + if (m_currentFocusOfThread != &m_globalFocus) { + Acquire a(&m_log, 1); + m_log << _T("GLOBAL FOCUS") << std::endl; + m_currentFocusOfThread = &m_globalFocus; + setCurrentKeymap(m_globalFocus.m_keymaps.front()); + } } - } - } - - _TCHAR className[GANA_MAX_ATOM_LENGTH]; - if (GetClassName(hwndFore, className, NUMBER_OF(className))) - { - if (_tcsicmp(className, _T("ConsoleWindowClass")) == 0) - { - _TCHAR titleName[1024]; - if (GetWindowText(hwndFore, titleName, NUMBER_OF(titleName)) == 0) - titleName[0] = _T('\0'); - setFocus(hwndFore, threadId, className, titleName, true); - Acquire a(&m_log, 1); - m_log << _T("HWND:\t") << std::hex << reinterpret_cast(hwndFore) - << std::dec << std::endl; - m_log << _T("THREADID:") << threadId << std::endl; - m_log << _T("CLASS:\t") << className << std::endl; - m_log << _T("TITLE:\t") << titleName << std::endl << std::endl; - goto restart; - } - } - } - - Acquire a(&m_cs); - if (m_globalFocus.m_keymaps.empty()) - { - Acquire a(&m_log, 1); - m_log << _T("NO GLOBAL FOCUS") << std::endl; - m_currentFocusOfThread = NULL; - setCurrentKeymap(NULL); - } - else - { - if (m_currentFocusOfThread != &m_globalFocus) - { - Acquire a(&m_log, 1); - m_log << _T("GLOBAL FOCUS") << std::endl; - m_currentFocusOfThread = &m_globalFocus; - setCurrentKeymap(m_globalFocus.m_keymaps.front()); - } - } - m_hwndFocus = NULL; + m_hwndFocus = NULL; } @@ -138,543 +126,504 @@ void Engine::checkFocusWindow() // is modifier pressed ? bool Engine::isPressed(Modifier::Type i_mt) { - const Keymap::ModAssignments &ma = m_currentKeymap->getModAssignments(i_mt); - for (Keymap::ModAssignments::const_iterator i = ma.begin(); - i != ma.end(); ++ i) - if ((*i).m_key->m_isPressed) - return true; - return false; + const Keymap::ModAssignments &ma = m_currentKeymap->getModAssignments(i_mt); + for (Keymap::ModAssignments::const_iterator i = ma.begin(); + i != ma.end(); ++ i) + if ((*i).m_key->m_isPressed) + return true; + return false; } // fix modifier key (if fixed, return true) bool Engine::fixModifierKey(ModifiedKey *io_mkey, Keymap::AssignMode *o_am) { - // for all modifier ... - for (int i = Modifier::Type_begin; i != Modifier::Type_end; ++ i) - { - // get modifier assignments (list of modifier keys) - const Keymap::ModAssignments &ma = - m_currentKeymap->getModAssignments(static_cast(i)); - - for (Keymap::ModAssignments::const_iterator - j = ma.begin(); j != ma.end(); ++ j) - if (io_mkey->m_key == (*j).m_key) // is io_mkey a modifier ? - { - { - Acquire a(&m_log, 1); - m_log << _T("* Modifier Key") << std::endl; + // for all modifier ... + for (int i = Modifier::Type_begin; i != Modifier::Type_end; ++ i) { + // get modifier assignments (list of modifier keys) + const Keymap::ModAssignments &ma = + m_currentKeymap->getModAssignments(static_cast(i)); + + for (Keymap::ModAssignments::const_iterator + j = ma.begin(); j != ma.end(); ++ j) + if (io_mkey->m_key == (*j).m_key) { // is io_mkey a modifier ? + { + Acquire a(&m_log, 1); + m_log << _T("* Modifier Key") << std::endl; + } + // set dontcare for this modifier + io_mkey->m_modifier.dontcare(static_cast(i)); + *o_am = (*j).m_assignMode; + return true; + } } - // set dontcare for this modifier - io_mkey->m_modifier.dontcare(static_cast(i)); - *o_am = (*j).m_assignMode; - return true; - } - } - *o_am = Keymap::AM_notModifier; - return false; + *o_am = Keymap::AM_notModifier; + return false; } // output to m_log void Engine::outputToLog(const Key *i_key, const ModifiedKey &i_mkey, - int i_debugLevel) + int i_debugLevel) { - size_t i; - Acquire a(&m_log, i_debugLevel); - - // output scan codes - for (i = 0; i < i_key->getScanCodesSize(); ++ i) - { - if (i_key->getScanCodes()[i].m_flags & ScanCode::E0) m_log << _T("E0-"); - if (i_key->getScanCodes()[i].m_flags & ScanCode::E1) m_log << _T("E1-"); - if (!(i_key->getScanCodes()[i].m_flags & ScanCode::E0E1)) - m_log << _T(" "); - m_log << _T("0x") << std::hex << std::setw(2) << std::setfill(_T('0')) - << static_cast(i_key->getScanCodes()[i].m_scan) - << std::dec << _T(" "); - } - - if (!i_mkey.m_key) // key corresponds to no phisical key - { - m_log << std::endl; - return; - } - - m_log << _T(" ") << i_mkey << std::endl; + size_t i; + Acquire a(&m_log, i_debugLevel); + + // output scan codes + for (i = 0; i < i_key->getScanCodesSize(); ++ i) { + if (i_key->getScanCodes()[i].m_flags & ScanCode::E0) m_log << _T("E0-"); + if (i_key->getScanCodes()[i].m_flags & ScanCode::E1) m_log << _T("E1-"); + if (!(i_key->getScanCodes()[i].m_flags & ScanCode::E0E1)) + m_log << _T(" "); + m_log << _T("0x") << std::hex << std::setw(2) << std::setfill(_T('0')) + << static_cast(i_key->getScanCodes()[i].m_scan) + << std::dec << _T(" "); + } + + if (!i_mkey.m_key) { // key corresponds to no phisical key + m_log << std::endl; + return; + } + + m_log << _T(" ") << i_mkey << std::endl; } // describe bindings void Engine::describeBindings() { - Acquire a(&m_log, 0); + Acquire a(&m_log, 0); - Keymap::DescribeParam dp; - for (KeymapPtrList::iterator i = m_currentFocusOfThread->m_keymaps.begin(); - i != m_currentFocusOfThread->m_keymaps.end(); ++ i) - (*i)->describe(m_log, &dp); - m_log << std::endl; + Keymap::DescribeParam dp; + for (KeymapPtrList::iterator i = m_currentFocusOfThread->m_keymaps.begin(); + i != m_currentFocusOfThread->m_keymaps.end(); ++ i) + (*i)->describe(m_log, &dp); + m_log << std::endl; } // update m_lastPressedKey void Engine::updateLastPressedKey(Key *i_key) { - m_lastPressedKey[1] = m_lastPressedKey[0]; - m_lastPressedKey[0] = i_key; + m_lastPressedKey[1] = m_lastPressedKey[0]; + m_lastPressedKey[0] = i_key; } // set current keymap void Engine::setCurrentKeymap(const Keymap *i_keymap, bool i_doesAddToHistory) { - if (i_doesAddToHistory) - { - m_keymapPrefixHistory.push_back(const_cast(m_currentKeymap)); - if (MAX_KEYMAP_PREFIX_HISTORY < m_keymapPrefixHistory.size()) - m_keymapPrefixHistory.pop_front(); - } - else - m_keymapPrefixHistory.clear(); - m_currentKeymap = i_keymap; + if (i_doesAddToHistory) { + m_keymapPrefixHistory.push_back(const_cast(m_currentKeymap)); + if (MAX_KEYMAP_PREFIX_HISTORY < m_keymapPrefixHistory.size()) + m_keymapPrefixHistory.pop_front(); + } else + m_keymapPrefixHistory.clear(); + m_currentKeymap = i_keymap; } // get current modifiers Modifier Engine::getCurrentModifiers(Key *i_key, bool i_isPressed) { - Modifier cmods; - cmods.add(m_currentLock); - - cmods.press(Modifier::Type_Shift , isPressed(Modifier::Type_Shift )); - cmods.press(Modifier::Type_Alt , isPressed(Modifier::Type_Alt )); - cmods.press(Modifier::Type_Control, isPressed(Modifier::Type_Control)); - cmods.press(Modifier::Type_Windows, isPressed(Modifier::Type_Windows)); - cmods.press(Modifier::Type_Up , !i_isPressed); - cmods.press(Modifier::Type_Down , i_isPressed); - - cmods.press(Modifier::Type_Repeat , false); - if (m_lastPressedKey[0] == i_key) - { - if (i_isPressed) - cmods.press(Modifier::Type_Repeat, true); - else - if (m_lastPressedKey[1] == i_key) - cmods.press(Modifier::Type_Repeat, true); - } - - for (int i = Modifier::Type_Mod0; i <= Modifier::Type_Mod9; ++ i) - cmods.press(static_cast(i), - isPressed(static_cast(i))); - - return cmods; + Modifier cmods; + cmods.add(m_currentLock); + + cmods.press(Modifier::Type_Shift , isPressed(Modifier::Type_Shift )); + cmods.press(Modifier::Type_Alt , isPressed(Modifier::Type_Alt )); + cmods.press(Modifier::Type_Control, isPressed(Modifier::Type_Control)); + cmods.press(Modifier::Type_Windows, isPressed(Modifier::Type_Windows)); + cmods.press(Modifier::Type_Up , !i_isPressed); + cmods.press(Modifier::Type_Down , i_isPressed); + + cmods.press(Modifier::Type_Repeat , false); + if (m_lastPressedKey[0] == i_key) { + if (i_isPressed) + cmods.press(Modifier::Type_Repeat, true); + else + if (m_lastPressedKey[1] == i_key) + cmods.press(Modifier::Type_Repeat, true); + } + + for (int i = Modifier::Type_Mod0; i <= Modifier::Type_Mod9; ++ i) + cmods.press(static_cast(i), + isPressed(static_cast(i))); + + return cmods; } // generate keyboard event for a key void Engine::generateKeyEvent(Key *i_key, bool i_doPress, bool i_isByAssign) { - // check if key is event - bool isEvent = false; - for (Key **e = Event::events; *e; ++ e) - if (*e == i_key) - { - isEvent = true; - break; - } - - bool isAlreadyReleased = false; - - if (!isEvent) - { - if (i_doPress && !i_key->m_isPressedOnWin32) - ++ m_currentKeyPressCountOnWin32; - else if (!i_doPress) - { - if (i_key->m_isPressedOnWin32) - -- m_currentKeyPressCountOnWin32; - else - isAlreadyReleased = true; - } - i_key->m_isPressedOnWin32 = i_doPress; - - if (i_isByAssign) - i_key->m_isPressedByAssign = i_doPress; - - Key *sync = m_setting->m_keyboard.getSyncKey(); - - if (!isAlreadyReleased || i_key == sync) - { - KEYBOARD_INPUT_DATA kid = { 0, 0, 0, 0, 0 }; - const ScanCode *sc = i_key->getScanCodes(); - for (size_t i = 0; i < i_key->getScanCodesSize(); ++ i) - { - kid.MakeCode = sc[i].m_scan; - kid.Flags = sc[i].m_flags; - if (!i_doPress) - kid.Flags |= KEYBOARD_INPUT_DATA::BREAK; + // check if key is event + bool isEvent = false; + for (Key **e = Event::events; *e; ++ e) + if (*e == i_key) { + isEvent = true; + break; + } + + bool isAlreadyReleased = false; + + if (!isEvent) { + if (i_doPress && !i_key->m_isPressedOnWin32) + ++ m_currentKeyPressCountOnWin32; + else if (!i_doPress) { + if (i_key->m_isPressedOnWin32) + -- m_currentKeyPressCountOnWin32; + else + isAlreadyReleased = true; + } + i_key->m_isPressedOnWin32 = i_doPress; + + if (i_isByAssign) + i_key->m_isPressedByAssign = i_doPress; + + Key *sync = m_setting->m_keyboard.getSyncKey(); + + if (!isAlreadyReleased || i_key == sync) { + KEYBOARD_INPUT_DATA kid = { 0, 0, 0, 0, 0 }; + const ScanCode *sc = i_key->getScanCodes(); + for (size_t i = 0; i < i_key->getScanCodesSize(); ++ i) { + kid.MakeCode = sc[i].m_scan; + kid.Flags = sc[i].m_flags; + if (!i_doPress) + kid.Flags |= KEYBOARD_INPUT_DATA::BREAK; #ifdef NO_DRIVER - injectInput(&kid, NULL); + injectInput(&kid, NULL); #else // !NO_DRIVER - DWORD len; - WriteFile(m_device, &kid, sizeof(kid), &len, &m_ol); - CHECK_TRUE( GetOverlappedResult(m_device, &m_ol, &len, TRUE) ); + DWORD len; + WriteFile(m_device, &kid, sizeof(kid), &len, &m_ol); + CHECK_TRUE( GetOverlappedResult(m_device, &m_ol, &len, TRUE) ); #endif // !NO_DRIVER - } - - m_lastGeneratedKey = i_doPress ? i_key : NULL; - } - } - - { - Acquire a(&m_log, 1); - m_log << _T("\t\t =>\t"); - if (isAlreadyReleased) - m_log << _T("(already released) "); - } - ModifiedKey mkey(i_key); - mkey.m_modifier.on(Modifier::Type_Up, !i_doPress); - mkey.m_modifier.on(Modifier::Type_Down, i_doPress); - outputToLog(i_key, mkey, 1); + } + + m_lastGeneratedKey = i_doPress ? i_key : NULL; + } + } + + { + Acquire a(&m_log, 1); + m_log << _T("\t\t =>\t"); + if (isAlreadyReleased) + m_log << _T("(already released) "); + } + ModifiedKey mkey(i_key); + mkey.m_modifier.on(Modifier::Type_Up, !i_doPress); + mkey.m_modifier.on(Modifier::Type_Down, i_doPress); + outputToLog(i_key, mkey, 1); } // genete event void Engine::generateEvents(Current i_c, const Keymap *i_keymap, Key *i_event) { - // generate - i_c.m_keymap = i_keymap; - i_c.m_mkey.m_key = i_event; - if (const Keymap::KeyAssignment *keyAssign = - i_c.m_keymap->searchAssignment(i_c.m_mkey)) - { - { - Acquire a(&m_log, 1); - m_log << std::endl << _T(" ") - << i_event->getName() << std::endl; - } - generateKeySeqEvents(i_c, keyAssign->m_keySeq, Part_all); - } + // generate + i_c.m_keymap = i_keymap; + i_c.m_mkey.m_key = i_event; + if (const Keymap::KeyAssignment *keyAssign = + i_c.m_keymap->searchAssignment(i_c.m_mkey)) { + { + Acquire a(&m_log, 1); + m_log << std::endl << _T(" ") + << i_event->getName() << std::endl; + } + generateKeySeqEvents(i_c, keyAssign->m_keySeq, Part_all); + } } // genete modifier events void Engine::generateModifierEvents(const Modifier &i_mod) { - { - Acquire a(&m_log, 1); - m_log << _T("* Gen Modifiers\t{") << std::endl; - } - - for (int i = Modifier::Type_begin; i < Modifier::Type_BASIC; ++ i) - { - Keyboard::Mods &mods = - m_setting->m_keyboard.getModifiers(static_cast(i)); - - if (i_mod.isDontcare(static_cast(i))) - // no need to process - ; - else if (i_mod.isPressed(static_cast(i))) - // we have to press this modifier - { - bool noneIsPressed = true; - bool noneIsPressedByAssign = true; - for (Keyboard::Mods::iterator i = mods.begin(); i != mods.end(); ++ i) - { - if ((*i)->m_isPressedOnWin32) - noneIsPressed = false; - if ((*i)->m_isPressedByAssign) - noneIsPressedByAssign = false; - } - if (noneIsPressed) - { - if (noneIsPressedByAssign) - generateKeyEvent(mods.front(), true, false); - else - for (Keyboard::Mods::iterator - i = mods.begin(); i != mods.end(); ++ i) - if ((*i)->m_isPressedByAssign) - generateKeyEvent((*i), true, false); - } - } - - else - // we have to release this modifier - { - // avoid such sequences as "Alt U-ALt" or "Windows U-Windows" - if (i == Modifier::Type_Alt || i == Modifier::Type_Windows) - { - for (Keyboard::Mods::iterator j = mods.begin(); j != mods.end(); ++ j) - if ((*j) == m_lastGeneratedKey) - { - Keyboard::Mods *mods = - &m_setting->m_keyboard.getModifiers(Modifier::Type_Shift); - if (mods->size() == 0) - mods = &m_setting->m_keyboard.getModifiers( - Modifier::Type_Control); - if (0 < mods->size()) - { - generateKeyEvent(mods->front(), true, false); - generateKeyEvent(mods->front(), false, false); - } - break; - } - } - - for (Keyboard::Mods::iterator j = mods.begin(); j != mods.end(); ++ j) - { - if ((*j)->m_isPressedOnWin32) - generateKeyEvent((*j), false, false); - } - } - } - - { - Acquire a(&m_log, 1); - m_log << _T("\t\t}") << std::endl; - } + { + Acquire a(&m_log, 1); + m_log << _T("* Gen Modifiers\t{") << std::endl; + } + + for (int i = Modifier::Type_begin; i < Modifier::Type_BASIC; ++ i) { + Keyboard::Mods &mods = + m_setting->m_keyboard.getModifiers(static_cast(i)); + + if (i_mod.isDontcare(static_cast(i))) + // no need to process + ; + else if (i_mod.isPressed(static_cast(i))) + // we have to press this modifier + { + bool noneIsPressed = true; + bool noneIsPressedByAssign = true; + for (Keyboard::Mods::iterator i = mods.begin(); i != mods.end(); ++ i) { + if ((*i)->m_isPressedOnWin32) + noneIsPressed = false; + if ((*i)->m_isPressedByAssign) + noneIsPressedByAssign = false; + } + if (noneIsPressed) { + if (noneIsPressedByAssign) + generateKeyEvent(mods.front(), true, false); + else + for (Keyboard::Mods::iterator + i = mods.begin(); i != mods.end(); ++ i) + if ((*i)->m_isPressedByAssign) + generateKeyEvent((*i), true, false); + } + } + + else + // we have to release this modifier + { + // avoid such sequences as "Alt U-ALt" or "Windows U-Windows" + if (i == Modifier::Type_Alt || i == Modifier::Type_Windows) { + for (Keyboard::Mods::iterator j = mods.begin(); j != mods.end(); ++ j) + if ((*j) == m_lastGeneratedKey) { + Keyboard::Mods *mods = + &m_setting->m_keyboard.getModifiers(Modifier::Type_Shift); + if (mods->size() == 0) + mods = &m_setting->m_keyboard.getModifiers( + Modifier::Type_Control); + if (0 < mods->size()) { + generateKeyEvent(mods->front(), true, false); + generateKeyEvent(mods->front(), false, false); + } + break; + } + } + + for (Keyboard::Mods::iterator j = mods.begin(); j != mods.end(); ++ j) { + if ((*j)->m_isPressedOnWin32) + generateKeyEvent((*j), false, false); + } + } + } + + { + Acquire a(&m_log, 1); + m_log << _T("\t\t}") << std::endl; + } } // generate keyboard events for action void Engine::generateActionEvents(const Current &i_c, const Action *i_a, - bool i_doPress) + bool i_doPress) { - switch (i_a->getType()) - { - // key - case Action::Type_key: - { - const ModifiedKey &mkey - = reinterpret_cast( - const_cast(i_a))->m_modifiedKey; - - // release - if (!i_doPress && - (mkey.m_modifier.isOn(Modifier::Type_Up) || - mkey.m_modifier.isDontcare(Modifier::Type_Up))) - generateKeyEvent(mkey.m_key, false, true); - - // press - else if (i_doPress && - (mkey.m_modifier.isOn(Modifier::Type_Down) || - mkey.m_modifier.isDontcare(Modifier::Type_Down))) - { - Modifier modifier = mkey.m_modifier; - modifier.add(i_c.m_mkey.m_modifier); - generateModifierEvents(modifier); - generateKeyEvent(mkey.m_key, true, true); - } - break; - } - - // keyseq - case Action::Type_keySeq: - { - const ActionKeySeq *aks = reinterpret_cast(i_a); - generateKeySeqEvents(i_c, aks->m_keySeq, - i_doPress ? Part_down : Part_up); - break; - } - - // function - case Action::Type_function: - { - const ActionFunction *af = reinterpret_cast(i_a); - bool is_up = (!i_doPress && - (af->m_modifier.isOn(Modifier::Type_Up) || - af->m_modifier.isDontcare(Modifier::Type_Up))); - bool is_down = (i_doPress && - (af->m_modifier.isOn(Modifier::Type_Down) || - af->m_modifier.isDontcare(Modifier::Type_Down))); - - if (!is_down && !is_up) - break; - - { - Acquire a(&m_log, 1); - m_log << _T("\t\t >\t") << af->m_functionData; - } - - FunctionParam param; - param.m_isPressed = i_doPress; - param.m_hwnd = m_currentFocusOfThread->m_hwndFocus; - param.m_c = i_c; - param.m_doesNeedEndl = true; - param.m_af = af; - - param.m_c.m_mkey.m_modifier.on(Modifier::Type_Up, !i_doPress); - param.m_c.m_mkey.m_modifier.on(Modifier::Type_Down, i_doPress); - - af->m_functionData->exec(this, ¶m); - - if (param.m_doesNeedEndl) - { - Acquire a(&m_log, 1); - m_log << std::endl; - } - break; - } - } + switch (i_a->getType()) { + // key + case Action::Type_key: { + const ModifiedKey &mkey + = reinterpret_cast( + const_cast(i_a))->m_modifiedKey; + + // release + if (!i_doPress && + (mkey.m_modifier.isOn(Modifier::Type_Up) || + mkey.m_modifier.isDontcare(Modifier::Type_Up))) + generateKeyEvent(mkey.m_key, false, true); + + // press + else if (i_doPress && + (mkey.m_modifier.isOn(Modifier::Type_Down) || + mkey.m_modifier.isDontcare(Modifier::Type_Down))) { + Modifier modifier = mkey.m_modifier; + modifier.add(i_c.m_mkey.m_modifier); + generateModifierEvents(modifier); + generateKeyEvent(mkey.m_key, true, true); + } + break; + } + + // keyseq + case Action::Type_keySeq: { + const ActionKeySeq *aks = reinterpret_cast(i_a); + generateKeySeqEvents(i_c, aks->m_keySeq, + i_doPress ? Part_down : Part_up); + break; + } + + // function + case Action::Type_function: { + const ActionFunction *af = reinterpret_cast(i_a); + bool is_up = (!i_doPress && + (af->m_modifier.isOn(Modifier::Type_Up) || + af->m_modifier.isDontcare(Modifier::Type_Up))); + bool is_down = (i_doPress && + (af->m_modifier.isOn(Modifier::Type_Down) || + af->m_modifier.isDontcare(Modifier::Type_Down))); + + if (!is_down && !is_up) + break; + + { + Acquire a(&m_log, 1); + m_log << _T("\t\t >\t") << af->m_functionData; + } + + FunctionParam param; + param.m_isPressed = i_doPress; + param.m_hwnd = m_currentFocusOfThread->m_hwndFocus; + param.m_c = i_c; + param.m_doesNeedEndl = true; + param.m_af = af; + + param.m_c.m_mkey.m_modifier.on(Modifier::Type_Up, !i_doPress); + param.m_c.m_mkey.m_modifier.on(Modifier::Type_Down, i_doPress); + + af->m_functionData->exec(this, ¶m); + + if (param.m_doesNeedEndl) { + Acquire a(&m_log, 1); + m_log << std::endl; + } + break; + } + } } // generate keyboard events for keySeq void Engine::generateKeySeqEvents(const Current &i_c, const KeySeq *i_keySeq, - Part i_part) + Part i_part) { - const KeySeq::Actions &actions = i_keySeq->getActions(); - if (actions.empty()) - return; - if (i_part == Part_up) - generateActionEvents(i_c, actions[actions.size() - 1], false); - else - { - size_t i; - for (i = 0 ; i < actions.size() - 1; ++ i) - { - generateActionEvents(i_c, actions[i], true); - generateActionEvents(i_c, actions[i], false); - } - generateActionEvents(i_c, actions[i], true); - if (i_part == Part_all) - generateActionEvents(i_c, actions[i], false); - } + const KeySeq::Actions &actions = i_keySeq->getActions(); + if (actions.empty()) + return; + if (i_part == Part_up) + generateActionEvents(i_c, actions[actions.size() - 1], false); + else { + size_t i; + for (i = 0 ; i < actions.size() - 1; ++ i) { + generateActionEvents(i_c, actions[i], true); + generateActionEvents(i_c, actions[i], false); + } + generateActionEvents(i_c, actions[i], true); + if (i_part == Part_all) + generateActionEvents(i_c, actions[i], false); + } } // generate keyboard events for current key void Engine::generateKeyboardEvents(const Current &i_c) { - if (++ m_generateKeyboardEventsRecursionGuard == - MAX_GENERATE_KEYBOARD_EVENTS_RECURSION_COUNT) - { - Acquire a(&m_log); - m_log << _T("error: too deep keymap recursion. there may be a loop.") - << std::endl; - return; - } - - const Keymap::KeyAssignment *keyAssign - = i_c.m_keymap->searchAssignment(i_c.m_mkey); - if (!keyAssign) - { - const KeySeq *keySeq = i_c.m_keymap->getDefaultKeySeq(); - ASSERT( keySeq ); - generateKeySeqEvents(i_c, keySeq, i_c.isPressed() ? Part_down : Part_up); - } - else - { - if (keyAssign->m_modifiedKey.m_modifier.isOn(Modifier::Type_Up) || - keyAssign->m_modifiedKey.m_modifier.isOn(Modifier::Type_Down)) - generateKeySeqEvents(i_c, keyAssign->m_keySeq, Part_all); - else - generateKeySeqEvents(i_c, keyAssign->m_keySeq, - i_c.isPressed() ? Part_down : Part_up); - } - m_generateKeyboardEventsRecursionGuard --; + if (++ m_generateKeyboardEventsRecursionGuard == + MAX_GENERATE_KEYBOARD_EVENTS_RECURSION_COUNT) { + Acquire a(&m_log); + m_log << _T("error: too deep keymap recursion. there may be a loop.") + << std::endl; + return; + } + + const Keymap::KeyAssignment *keyAssign + = i_c.m_keymap->searchAssignment(i_c.m_mkey); + if (!keyAssign) { + const KeySeq *keySeq = i_c.m_keymap->getDefaultKeySeq(); + ASSERT( keySeq ); + generateKeySeqEvents(i_c, keySeq, i_c.isPressed() ? Part_down : Part_up); + } else { + if (keyAssign->m_modifiedKey.m_modifier.isOn(Modifier::Type_Up) || + keyAssign->m_modifiedKey.m_modifier.isOn(Modifier::Type_Down)) + generateKeySeqEvents(i_c, keyAssign->m_keySeq, Part_all); + else + generateKeySeqEvents(i_c, keyAssign->m_keySeq, + i_c.isPressed() ? Part_down : Part_up); + } + m_generateKeyboardEventsRecursionGuard --; } // generate keyboard events for current key void Engine::beginGeneratingKeyboardEvents( - const Current &i_c, bool i_isModifier) + const Current &i_c, bool i_isModifier) { - // (1) (2) (3) (4) (1) - // up/down: D- U- D- U- D- - // keymap: m_currentKeymap m_currentKeymap X X m_currentKeymap - // memo: &Prefix(X) ... ... ... ... - // m_isPrefix: false true true false false - - Current cnew(i_c); - - bool isPhysicallyPressed - = cnew.m_mkey.m_modifier.isPressed(Modifier::Type_Down); - - // substitute - ModifiedKey mkey = m_setting->m_keyboard.searchSubstitute(cnew.m_mkey); - if (mkey.m_key) - { - cnew.m_mkey = mkey; - if (isPhysicallyPressed) - { - cnew.m_mkey.m_modifier.off(Modifier::Type_Up); - cnew.m_mkey.m_modifier.on(Modifier::Type_Down); - } - else - { - cnew.m_mkey.m_modifier.on(Modifier::Type_Up); - cnew.m_mkey.m_modifier.off(Modifier::Type_Down); - } - for (int i = Modifier::Type_begin; i != Modifier::Type_end; ++ i) - { - Modifier::Type type = static_cast(i); - if (cnew.m_mkey.m_modifier.isDontcare(type) && - !i_c.m_mkey.m_modifier.isDontcare(type)) - cnew.m_mkey.m_modifier.press( - type, i_c.m_mkey.m_modifier.isPressed(type)); - } - - { - Acquire a(&m_log, 1); - m_log << _T("* substitute") << std::endl; - } - outputToLog(mkey.m_key, cnew.m_mkey, 1); - } - - // for prefix key - const Keymap *tmpKeymap = m_currentKeymap; - if (i_isModifier || !m_isPrefix) ; - else if (isPhysicallyPressed) // when (3) - m_isPrefix = false; - else if (!isPhysicallyPressed) // when (2) - m_currentKeymap = m_currentFocusOfThread->m_keymaps.front(); - - // for m_emacsEditKillLine function - m_emacsEditKillLine.m_doForceReset = !i_isModifier; - - // generate key event ! - m_generateKeyboardEventsRecursionGuard = 0; - if (isPhysicallyPressed) - generateEvents(cnew, cnew.m_keymap, &Event::before_key_down); - generateKeyboardEvents(cnew); - if (!isPhysicallyPressed) - generateEvents(cnew, cnew.m_keymap, &Event::after_key_up); - - // for m_emacsEditKillLine function - if (m_emacsEditKillLine.m_doForceReset) - m_emacsEditKillLine.reset(); - - // for prefix key - if (i_isModifier) - ; - else if (!m_isPrefix) // when (1), (4) - m_currentKeymap = m_currentFocusOfThread->m_keymaps.front(); - else if (!isPhysicallyPressed) // when (2) - m_currentKeymap = tmpKeymap; + // (1) (2) (3) (4) (1) + // up/down: D- U- D- U- D- + // keymap: m_currentKeymap m_currentKeymap X X m_currentKeymap + // memo: &Prefix(X) ... ... ... ... + // m_isPrefix: false true true false false + + Current cnew(i_c); + + bool isPhysicallyPressed + = cnew.m_mkey.m_modifier.isPressed(Modifier::Type_Down); + + // substitute + ModifiedKey mkey = m_setting->m_keyboard.searchSubstitute(cnew.m_mkey); + if (mkey.m_key) { + cnew.m_mkey = mkey; + if (isPhysicallyPressed) { + cnew.m_mkey.m_modifier.off(Modifier::Type_Up); + cnew.m_mkey.m_modifier.on(Modifier::Type_Down); + } else { + cnew.m_mkey.m_modifier.on(Modifier::Type_Up); + cnew.m_mkey.m_modifier.off(Modifier::Type_Down); + } + for (int i = Modifier::Type_begin; i != Modifier::Type_end; ++ i) { + Modifier::Type type = static_cast(i); + if (cnew.m_mkey.m_modifier.isDontcare(type) && + !i_c.m_mkey.m_modifier.isDontcare(type)) + cnew.m_mkey.m_modifier.press( + type, i_c.m_mkey.m_modifier.isPressed(type)); + } + + { + Acquire a(&m_log, 1); + m_log << _T("* substitute") << std::endl; + } + outputToLog(mkey.m_key, cnew.m_mkey, 1); + } + + // for prefix key + const Keymap *tmpKeymap = m_currentKeymap; + if (i_isModifier || !m_isPrefix) ; + else if (isPhysicallyPressed) // when (3) + m_isPrefix = false; + else if (!isPhysicallyPressed) // when (2) + m_currentKeymap = m_currentFocusOfThread->m_keymaps.front(); + + // for m_emacsEditKillLine function + m_emacsEditKillLine.m_doForceReset = !i_isModifier; + + // generate key event ! + m_generateKeyboardEventsRecursionGuard = 0; + if (isPhysicallyPressed) + generateEvents(cnew, cnew.m_keymap, &Event::before_key_down); + generateKeyboardEvents(cnew); + if (!isPhysicallyPressed) + generateEvents(cnew, cnew.m_keymap, &Event::after_key_up); + + // for m_emacsEditKillLine function + if (m_emacsEditKillLine.m_doForceReset) + m_emacsEditKillLine.reset(); + + // for prefix key + if (i_isModifier) + ; + else if (!m_isPrefix) // when (1), (4) + m_currentKeymap = m_currentFocusOfThread->m_keymaps.front(); + else if (!isPhysicallyPressed) // when (2) + m_currentKeymap = tmpKeymap; } #ifdef NO_DRIVER unsigned int Engine::injectInput(const KEYBOARD_INPUT_DATA *i_kid, const KBDLLHOOKSTRUCT *i_kidRaw) { - INPUT kid; - kid.type = INPUT_KEYBOARD; - kid.ki.wVk = 0; - kid.ki.wScan = i_kid->MakeCode; - kid.ki.dwFlags = KEYEVENTF_SCANCODE; - kid.ki.time = i_kidRaw ? i_kidRaw->time : 0; - kid.ki.dwExtraInfo = i_kidRaw ? i_kidRaw->dwExtraInfo : 0; - if (i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) - { - kid.ki.dwFlags |= KEYEVENTF_KEYUP; - } - if (i_kid->Flags & KEYBOARD_INPUT_DATA::E0) - { - kid.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY; - } - SendInput(1, &kid, sizeof(kid)); - return 1; + INPUT kid; + kid.type = INPUT_KEYBOARD; + kid.ki.wVk = 0; + kid.ki.wScan = i_kid->MakeCode; + kid.ki.dwFlags = KEYEVENTF_SCANCODE; + kid.ki.time = i_kidRaw ? i_kidRaw->time : 0; + kid.ki.dwExtraInfo = i_kidRaw ? i_kidRaw->dwExtraInfo : 0; + if (i_kid->Flags & KEYBOARD_INPUT_DATA::BREAK) { + kid.ki.dwFlags |= KEYEVENTF_KEYUP; + } + if (i_kid->Flags & KEYBOARD_INPUT_DATA::E0) { + kid.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY; + } + SendInput(1, &kid, sizeof(kid)); + return 1; } #endif // NO_DRIVER @@ -682,1035 +631,929 @@ unsigned int Engine::injectInput(const KEYBOARD_INPUT_DATA *i_kid, const KBDLLHO // pop all pressed key on win32 void Engine::keyboardResetOnWin32() { - for (Keyboard::KeyIterator - i = m_setting->m_keyboard.getKeyIterator(); *i; ++ i) - { - if ((*i)->m_isPressedOnWin32) - generateKeyEvent((*i), false, true); - } + for (Keyboard::KeyIterator + i = m_setting->m_keyboard.getKeyIterator(); *i; ++ i) { + if ((*i)->m_isPressedOnWin32) + generateKeyEvent((*i), false, true); + } } #ifdef NO_DRIVER unsigned int WINAPI Engine::keyboardDetour(Engine *i_this, KBDLLHOOKSTRUCT *i_kid) { - return i_this->keyboardDetour(i_kid); + return i_this->keyboardDetour(i_kid); } unsigned int Engine::keyboardDetour(KBDLLHOOKSTRUCT *i_kid) { #if 0 - Acquire a(&m_log, 1); - m_log << std::hex + Acquire a(&m_log, 1); + m_log << std::hex << _T("keyboardDetour: vkCode=") << i_kid->vkCode << _T(" scanCode=") << i_kid->scanCode << _T(" flags=") << i_kid->flags << std::endl; #endif - if (i_kid->flags & LLKHF_INJECTED) - { - return 0; - } - else - { - Key key; - KEYBOARD_INPUT_DATA kid; - - kid.UnitId = 0; - kid.MakeCode = i_kid->scanCode; - kid.Flags = 0; - if (i_kid->flags & LLKHF_UP) - { - kid.Flags |= KEYBOARD_INPUT_DATA::BREAK; - } - if (i_kid->flags & LLKHF_EXTENDED) - { - kid.Flags |= KEYBOARD_INPUT_DATA::E0; - } - kid.Reserved = 0; - kid.ExtraInformation = 0; - - Acquire a(&m_cskidq); - m_kidq.push_back(kid); - SetEvent(m_readEvent); - return 1; - } + if (i_kid->flags & LLKHF_INJECTED) { + return 0; + } else { + Key key; + KEYBOARD_INPUT_DATA kid; + + kid.UnitId = 0; + kid.MakeCode = i_kid->scanCode; + kid.Flags = 0; + if (i_kid->flags & LLKHF_UP) { + kid.Flags |= KEYBOARD_INPUT_DATA::BREAK; + } + if (i_kid->flags & LLKHF_EXTENDED) { + kid.Flags |= KEYBOARD_INPUT_DATA::E0; + } + kid.Reserved = 0; + kid.ExtraInformation = 0; + + Acquire a(&m_cskidq); + m_kidq.push_back(kid); + SetEvent(m_readEvent); + return 1; + } } #endif // NO_DRIVER // keyboard handler thread unsigned int WINAPI Engine::keyboardHandler(void *i_this) { - reinterpret_cast(i_this)->keyboardHandler(); - _endthreadex(0); - return 0; + reinterpret_cast(i_this)->keyboardHandler(); + _endthreadex(0); + return 0; } void Engine::keyboardHandler() { - // initialize ok - CHECK_TRUE( SetEvent(m_threadEvent) ); - - // loop - Key key; - while (!m_doForceTerminate) - { - KEYBOARD_INPUT_DATA kid; - + // initialize ok + CHECK_TRUE( SetEvent(m_threadEvent) ); + + // loop + Key key; + while (!m_doForceTerminate) { + KEYBOARD_INPUT_DATA kid; + #ifndef NO_DRIVER - DWORD len; + DWORD len; #endif // !NO_DRIVER - { - Acquire a(&m_log, 1); - m_log << _T("begin ReadFile();") << std::endl; - } + { + Acquire a(&m_log, 1); + m_log << _T("begin ReadFile();") << std::endl; + } #ifdef NO_DRIVER - if (1) - { + if (1) { #else // !NO_DRIVER - if (!ReadFile(m_device, &kid, sizeof(kid), &len, &m_ol)) - { - if (GetLastError() != ERROR_IO_PENDING) - continue; + if (!ReadFile(m_device, &kid, sizeof(kid), &len, &m_ol)) { + if (GetLastError() != ERROR_IO_PENDING) + continue; #endif // !NO_DRIVER - - HANDLE handles[] = { m_readEvent, m_interruptThreadEvent }; - rewait: - switch (MsgWaitForMultipleObjects(NUMBER_OF(handles), &handles[0], - FALSE, INFINITE, QS_POSTMESSAGE)) - { - case WAIT_OBJECT_0: // m_readEvent + + HANDLE handles[] = { m_readEvent, m_interruptThreadEvent }; +rewait: + switch (MsgWaitForMultipleObjects(NUMBER_OF(handles), &handles[0], + FALSE, INFINITE, QS_POSTMESSAGE)) { + case WAIT_OBJECT_0: // m_readEvent #ifdef NO_DRIVER - { - Acquire a(&m_cskidq); - if (m_kidq.empty()) - { - goto rewait; - } - kid = m_kidq.front(); - m_kidq.pop_front(); - if (!m_kidq.empty()) - { - SetEvent(m_readEvent); - } - } + { + Acquire a(&m_cskidq); + if (m_kidq.empty()) { + goto rewait; + } + kid = m_kidq.front(); + m_kidq.pop_front(); + if (!m_kidq.empty()) { + SetEvent(m_readEvent); + } + } #else // !NO_DRIVER - if (!GetOverlappedResult(m_device, &m_ol, &len, FALSE)) - continue; + if (!GetOverlappedResult(m_device, &m_ol, &len, FALSE)) + continue; #endif // !NO_DRIVER - break; - - case WAIT_OBJECT_0 + 1: // m_interruptThreadEvent - CancelIo(m_device); - switch (m_interruptThreadReason) { - default: { - ASSERT( false ); - Acquire a(&m_log, 0); - m_log << _T("internal error: m_interruptThreadReason == ") - << m_interruptThreadReason << std::endl; - break; - } - - case InterruptThreadReason_Terminate: - goto break_while; - - case InterruptThreadReason_Pause: { - CHECK_TRUE( SetEvent(m_threadEvent) ); - while (WaitForMultipleObjects(1, &m_interruptThreadEvent, - FALSE, INFINITE) != WAIT_OBJECT_0) - ; - switch (m_interruptThreadReason) { - case InterruptThreadReason_Terminate: - goto break_while; - - case InterruptThreadReason_Resume: - break; - - default: - ASSERT( false ); - break; - } - CHECK_TRUE( SetEvent(m_threadEvent) ); - break; - } - } - break; - - case WAIT_OBJECT_0 + NUMBER_OF(handles): - { - MSG message; - - while (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) - { - switch (message.message) - { - case WM_APP + 201: - { - if (message.wParam) + break; + + case WAIT_OBJECT_0 + 1: // m_interruptThreadEvent + CancelIo(m_device); + switch (m_interruptThreadReason) { + default: { + ASSERT( false ); + Acquire a(&m_log, 0); + m_log << _T("internal error: m_interruptThreadReason == ") + << m_interruptThreadReason << std::endl; + break; + } + + case InterruptThreadReason_Terminate: + goto break_while; + + case InterruptThreadReason_Pause: { + CHECK_TRUE( SetEvent(m_threadEvent) ); + while (WaitForMultipleObjects(1, &m_interruptThreadEvent, + FALSE, INFINITE) != WAIT_OBJECT_0) + ; + switch (m_interruptThreadReason) { + case InterruptThreadReason_Terminate: + goto break_while; + + case InterruptThreadReason_Resume: + break; + + default: + ASSERT( false ); + break; + } + CHECK_TRUE( SetEvent(m_threadEvent) ); + break; + } + } + break; + + case WAIT_OBJECT_0 + NUMBER_OF(handles): { + MSG message; + + while (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) { + switch (message.message) { + case WM_APP + 201: { + if (message.wParam) { + m_currentLock.on(Modifier::Type_Touchpad); + m_currentLock.on(Modifier::Type_TouchpadSticky); + } else + m_currentLock.off(Modifier::Type_Touchpad); + Acquire a(&m_log, 1); + m_log << _T("touchpad: ") << message.wParam + << _T(".") << (message.lParam & 0xffff) + << _T(".") << (message.lParam >> 16 & 0xffff) + << std::endl; + break; + } + default: + break; + } + } + goto rewait; + } + + default: + ASSERT( false ); + continue; + } + } { - m_currentLock.on(Modifier::Type_Touchpad); - m_currentLock.on(Modifier::Type_TouchpadSticky); + Acquire a(&m_log, 1); + m_log << _T("end ReadFile();") << std::endl; } - else - m_currentLock.off(Modifier::Type_Touchpad); - Acquire a(&m_log, 1); - m_log << _T("touchpad: ") << message.wParam - << _T(".") << (message.lParam & 0xffff) - << _T(".") << (message.lParam >> 16 & 0xffff) - << std::endl; - break; - } - default: - break; - } - } - goto rewait; - } - default: - ASSERT( false ); - continue; - } - } - { - Acquire a(&m_log, 1); - m_log << _T("end ReadFile();") << std::endl; - } - - checkFocusWindow(); - - if (!m_setting || // m_setting has not been loaded - !m_isEnabled) // disabled - { - if (m_isLogMode) - { - Key key; - key.addScanCode(ScanCode(kid.MakeCode, kid.Flags)); - outputToLog(&key, ModifiedKey(), 0); - } - else - { + checkFocusWindow(); + + if (!m_setting || // m_setting has not been loaded + !m_isEnabled) { // disabled + if (m_isLogMode) { + Key key; + key.addScanCode(ScanCode(kid.MakeCode, kid.Flags)); + outputToLog(&key, ModifiedKey(), 0); + } else { #ifdef NO_DRIVER - injectInput(&kid, NULL); + injectInput(&kid, NULL); #else // !NO_DRIVER - WriteFile(m_device, &kid, sizeof(kid), &len, &m_ol); - GetOverlappedResult(m_device, &m_ol, &len, TRUE); + WriteFile(m_device, &kid, sizeof(kid), &len, &m_ol); + GetOverlappedResult(m_device, &m_ol, &len, TRUE); #endif // !NO_DRIVER - } - updateLastPressedKey(NULL); - continue; - } - - Acquire a(&m_cs); - - if (!m_currentFocusOfThread || - !m_currentKeymap) - { + } + updateLastPressedKey(NULL); + continue; + } + + Acquire a(&m_cs); + + if (!m_currentFocusOfThread || + !m_currentKeymap) { #ifndef NO_DRIVER - WriteFile(m_device, &kid, sizeof(kid), &len, &m_ol); - GetOverlappedResult(m_device, &m_ol, &len, TRUE); + WriteFile(m_device, &kid, sizeof(kid), &len, &m_ol); + GetOverlappedResult(m_device, &m_ol, &len, TRUE); #endif // !NO_DRIVER - Acquire a(&m_log, 0); - if (!m_currentFocusOfThread) - m_log << _T("internal error: m_currentFocusOfThread == NULL") - << std::endl; - if (!m_currentKeymap) - m_log << _T("internal error: m_currentKeymap == NULL") - << std::endl; - updateLastPressedKey(NULL); - continue; - } - - Current c; - c.m_keymap = m_currentKeymap; - c.m_i = m_currentFocusOfThread->m_keymaps.begin(); - - // search key - key.addScanCode(ScanCode(kid.MakeCode, kid.Flags)); - c.m_mkey = m_setting->m_keyboard.searchKey(key); - if (!c.m_mkey.m_key) - { - c.m_mkey.m_key = m_setting->m_keyboard.searchPrefixKey(key); - if (c.m_mkey.m_key) - continue; - } - - // press the key and update counter - bool isPhysicallyPressed - = !(key.getScanCodes()[0].m_flags & ScanCode::BREAK); - if (c.m_mkey.m_key) - { - if (!c.m_mkey.m_key->m_isPressed && isPhysicallyPressed) - ++ m_currentKeyPressCount; - else if (c.m_mkey.m_key->m_isPressed && !isPhysicallyPressed) - -- m_currentKeyPressCount; - c.m_mkey.m_key->m_isPressed = isPhysicallyPressed; - } - - // create modifiers - c.m_mkey.m_modifier = getCurrentModifiers(c.m_mkey.m_key, - isPhysicallyPressed); - Keymap::AssignMode am; - bool isModifier = fixModifierKey(&c.m_mkey, &am); - if (m_isPrefix) - { - if (isModifier && m_doesIgnoreModifierForPrefix) - am = Keymap::AM_true; - if (m_doesEditNextModifier) - { - Modifier modifier = m_modifierForNextKey; - modifier.add(c.m_mkey.m_modifier); - c.m_mkey.m_modifier = modifier; - } - } - - if (m_isLogMode) - outputToLog(&key, c.m_mkey, 0); - else if (am == Keymap::AM_true) - { - { - Acquire a(&m_log, 1); - m_log << _T("* true modifier") << std::endl; - } - // true modifier doesn't generate scan code - outputToLog(&key, c.m_mkey, 1); - } - else if (am == Keymap::AM_oneShot || am == Keymap::AM_oneShotRepeatable) - { - { - Acquire a(&m_log, 1); - if (am == Keymap::AM_oneShot) - m_log << _T("* one shot modifier") << std::endl; - else - m_log << _T("* one shot repeatable modifier") << std::endl; - } - // oneShot modifier doesn't generate scan code - outputToLog(&key, c.m_mkey, 1); - if (isPhysicallyPressed) - { - if (am == Keymap::AM_oneShotRepeatable // the key is repeating - && m_oneShotKey.m_key == c.m_mkey.m_key) - { - if (m_oneShotRepeatableRepeatCount < - m_setting->m_oneShotRepeatableDelay) { - ; // delay - } else { - Current cnew = c; - beginGeneratingKeyboardEvents(cnew, false); - } - ++ m_oneShotRepeatableRepeatCount; - } else { - m_oneShotKey = c.m_mkey; - m_oneShotRepeatableRepeatCount = 0; - } - } - else - { - if (m_oneShotKey.m_key) - { - Current cnew = c; - cnew.m_mkey.m_modifier = m_oneShotKey.m_modifier; - cnew.m_mkey.m_modifier.off(Modifier::Type_Up); - cnew.m_mkey.m_modifier.on(Modifier::Type_Down); - beginGeneratingKeyboardEvents(cnew, false); - - cnew = c; - cnew.m_mkey.m_modifier = m_oneShotKey.m_modifier; - cnew.m_mkey.m_modifier.on(Modifier::Type_Up); - cnew.m_mkey.m_modifier.off(Modifier::Type_Down); - beginGeneratingKeyboardEvents(cnew, false); + Acquire a(&m_log, 0); + if (!m_currentFocusOfThread) + m_log << _T("internal error: m_currentFocusOfThread == NULL") + << std::endl; + if (!m_currentKeymap) + m_log << _T("internal error: m_currentKeymap == NULL") + << std::endl; + updateLastPressedKey(NULL); + continue; + } + + Current c; + c.m_keymap = m_currentKeymap; + c.m_i = m_currentFocusOfThread->m_keymaps.begin(); + + // search key + key.addScanCode(ScanCode(kid.MakeCode, kid.Flags)); + c.m_mkey = m_setting->m_keyboard.searchKey(key); + if (!c.m_mkey.m_key) { + c.m_mkey.m_key = m_setting->m_keyboard.searchPrefixKey(key); + if (c.m_mkey.m_key) + continue; + } + + // press the key and update counter + bool isPhysicallyPressed + = !(key.getScanCodes()[0].m_flags & ScanCode::BREAK); + if (c.m_mkey.m_key) { + if (!c.m_mkey.m_key->m_isPressed && isPhysicallyPressed) + ++ m_currentKeyPressCount; + else if (c.m_mkey.m_key->m_isPressed && !isPhysicallyPressed) + -- m_currentKeyPressCount; + c.m_mkey.m_key->m_isPressed = isPhysicallyPressed; + } + + // create modifiers + c.m_mkey.m_modifier = getCurrentModifiers(c.m_mkey.m_key, + isPhysicallyPressed); + Keymap::AssignMode am; + bool isModifier = fixModifierKey(&c.m_mkey, &am); + if (m_isPrefix) { + if (isModifier && m_doesIgnoreModifierForPrefix) + am = Keymap::AM_true; + if (m_doesEditNextModifier) { + Modifier modifier = m_modifierForNextKey; + modifier.add(c.m_mkey.m_modifier); + c.m_mkey.m_modifier = modifier; + } + } + + if (m_isLogMode) + outputToLog(&key, c.m_mkey, 0); + else if (am == Keymap::AM_true) { + { + Acquire a(&m_log, 1); + m_log << _T("* true modifier") << std::endl; + } + // true modifier doesn't generate scan code + outputToLog(&key, c.m_mkey, 1); + } else if (am == Keymap::AM_oneShot || am == Keymap::AM_oneShotRepeatable) { + { + Acquire a(&m_log, 1); + if (am == Keymap::AM_oneShot) + m_log << _T("* one shot modifier") << std::endl; + else + m_log << _T("* one shot repeatable modifier") << std::endl; + } + // oneShot modifier doesn't generate scan code + outputToLog(&key, c.m_mkey, 1); + if (isPhysicallyPressed) { + if (am == Keymap::AM_oneShotRepeatable // the key is repeating + && m_oneShotKey.m_key == c.m_mkey.m_key) { + if (m_oneShotRepeatableRepeatCount < + m_setting->m_oneShotRepeatableDelay) { + ; // delay + } else { + Current cnew = c; + beginGeneratingKeyboardEvents(cnew, false); + } + ++ m_oneShotRepeatableRepeatCount; + } else { + m_oneShotKey = c.m_mkey; + m_oneShotRepeatableRepeatCount = 0; + } + } else { + if (m_oneShotKey.m_key) { + Current cnew = c; + cnew.m_mkey.m_modifier = m_oneShotKey.m_modifier; + cnew.m_mkey.m_modifier.off(Modifier::Type_Up); + cnew.m_mkey.m_modifier.on(Modifier::Type_Down); + beginGeneratingKeyboardEvents(cnew, false); + + cnew = c; + cnew.m_mkey.m_modifier = m_oneShotKey.m_modifier; + cnew.m_mkey.m_modifier.on(Modifier::Type_Up); + cnew.m_mkey.m_modifier.off(Modifier::Type_Down); + beginGeneratingKeyboardEvents(cnew, false); + } + m_oneShotKey.m_key = NULL; + m_oneShotRepeatableRepeatCount = 0; + } + } else if (c.m_mkey.m_key) + // normal key + { + outputToLog(&key, c.m_mkey, 1); + if (isPhysicallyPressed) + m_oneShotKey.m_key = NULL; + beginGeneratingKeyboardEvents(c, isModifier); + } + + // if counter is zero, reset modifiers and keys on win32 + if (m_currentKeyPressCount <= 0) { + { + Acquire a(&m_log, 1); + m_log << _T("* No key is pressed") << std::endl; + } + generateModifierEvents(Modifier()); + if (0 < m_currentKeyPressCountOnWin32) + keyboardResetOnWin32(); + m_currentKeyPressCount = 0; + m_currentKeyPressCountOnWin32 = 0; + m_oneShotKey.m_key = NULL; + if (m_currentLock.isOn(Modifier::Type_Touchpad) == false) + m_currentLock.off(Modifier::Type_TouchpadSticky); + } + + key.initialize(); + updateLastPressedKey(isPhysicallyPressed ? c.m_mkey.m_key : NULL); } - m_oneShotKey.m_key = NULL; - m_oneShotRepeatableRepeatCount = 0; - } - } - else if (c.m_mkey.m_key) - // normal key - { - outputToLog(&key, c.m_mkey, 1); - if (isPhysicallyPressed) - m_oneShotKey.m_key = NULL; - beginGeneratingKeyboardEvents(c, isModifier); - } - - // if counter is zero, reset modifiers and keys on win32 - if (m_currentKeyPressCount <= 0) - { - { - Acquire a(&m_log, 1); - m_log << _T("* No key is pressed") << std::endl; - } - generateModifierEvents(Modifier()); - if (0 < m_currentKeyPressCountOnWin32) - keyboardResetOnWin32(); - m_currentKeyPressCount = 0; - m_currentKeyPressCountOnWin32 = 0; - m_oneShotKey.m_key = NULL; - if (m_currentLock.isOn(Modifier::Type_Touchpad) == false) - m_currentLock.off(Modifier::Type_TouchpadSticky); - } - - key.initialize(); - updateLastPressedKey(isPhysicallyPressed ? c.m_mkey.m_key : NULL); - } - break_while: - CHECK_TRUE( SetEvent(m_threadEvent) ); +break_while: + CHECK_TRUE( SetEvent(m_threadEvent) ); } - + Engine::Engine(tomsgstream &i_log) - : m_hwndAssocWindow(NULL), - m_setting(NULL), - m_device(INVALID_HANDLE_VALUE), - m_didMayuStartDevice(false), - m_threadEvent(NULL), - m_mayudVersion(_T("unknown")), - m_readEvent(NULL), - m_interruptThreadEvent(NULL), - m_sts4mayu(NULL), - m_cts4mayu(NULL), - m_doForceTerminate(false), - m_isLogMode(false), - m_isEnabled(true), - m_isSynchronizing(false), - m_eSync(NULL), - m_generateKeyboardEventsRecursionGuard(0), - m_currentKeyPressCount(0), - m_currentKeyPressCountOnWin32(0), - m_lastGeneratedKey(NULL), - m_oneShotRepeatableRepeatCount(0), - m_isPrefix(false), - m_currentKeymap(NULL), - m_currentFocusOfThread(NULL), - m_hwndFocus(NULL), - m_afShellExecute(NULL), - m_variable(0), - m_log(i_log) -{ - for (size_t i = 0; i < NUMBER_OF(m_lastPressedKey); ++ i) - m_lastPressedKey[i] = NULL; - - // set default lock state - for (int i = 0; i < Modifier::Type_end; ++ i) - m_currentLock.dontcare(static_cast(i)); - for (int i = Modifier::Type_Lock0; i <= Modifier::Type_Lock9; ++ i) - m_currentLock.release(static_cast(i)); + : m_hwndAssocWindow(NULL), + m_setting(NULL), + m_device(INVALID_HANDLE_VALUE), + m_didMayuStartDevice(false), + m_threadEvent(NULL), + m_mayudVersion(_T("unknown")), + m_readEvent(NULL), + m_interruptThreadEvent(NULL), + m_sts4mayu(NULL), + m_cts4mayu(NULL), + m_doForceTerminate(false), + m_isLogMode(false), + m_isEnabled(true), + m_isSynchronizing(false), + m_eSync(NULL), + m_generateKeyboardEventsRecursionGuard(0), + m_currentKeyPressCount(0), + m_currentKeyPressCountOnWin32(0), + m_lastGeneratedKey(NULL), + m_oneShotRepeatableRepeatCount(0), + m_isPrefix(false), + m_currentKeymap(NULL), + m_currentFocusOfThread(NULL), + m_hwndFocus(NULL), + m_afShellExecute(NULL), + m_variable(0), + m_log(i_log) { + for (size_t i = 0; i < NUMBER_OF(m_lastPressedKey); ++ i) + m_lastPressedKey[i] = NULL; + + // set default lock state + for (int i = 0; i < Modifier::Type_end; ++ i) + m_currentLock.dontcare(static_cast(i)); + for (int i = Modifier::Type_Lock0; i <= Modifier::Type_Lock9; ++ i) + m_currentLock.release(static_cast(i)); #ifndef NO_DRIVER - if (!open()) { - throw ErrorMessage() << loadString(IDS_driverNotInstalled); - } + if (!open()) { + throw ErrorMessage() << loadString(IDS_driverNotInstalled); + } #endif // !NO_DRIVER - + #ifndef NO_DRIVER - { - TCHAR versionBuf[256]; - DWORD length = 0; - - if (DeviceIoControl(m_device, IOCTL_MAYU_GET_VERSION, NULL, 0, - versionBuf, sizeof(versionBuf), &length, NULL) - && length - && length < sizeof(versionBuf)) // fail safe - m_mayudVersion = tstring(versionBuf, length / 2); - } + { + TCHAR versionBuf[256]; + DWORD length = 0; + + if (DeviceIoControl(m_device, IOCTL_MAYU_GET_VERSION, NULL, 0, + versionBuf, sizeof(versionBuf), &length, NULL) + && length + && length < sizeof(versionBuf)) // fail safe + m_mayudVersion = tstring(versionBuf, length / 2); + } #endif // !NO_DRIVER - // create event for sync - CHECK_TRUE( m_eSync = CreateEvent(NULL, FALSE, FALSE, NULL) ); - // create named pipe for &SetImeString - m_hookPipe = CreateNamedPipe(addSessionId(HOOK_PIPE_NAME).c_str(), - PIPE_ACCESS_OUTBOUND, - PIPE_TYPE_BYTE, 1, - 0, 0, 0, NULL); - StrExprArg::setEngine(this); + // create event for sync + CHECK_TRUE( m_eSync = CreateEvent(NULL, FALSE, FALSE, NULL) ); + // create named pipe for &SetImeString + m_hookPipe = CreateNamedPipe(addSessionId(HOOK_PIPE_NAME).c_str(), + PIPE_ACCESS_OUTBOUND, + PIPE_TYPE_BYTE, 1, + 0, 0, 0, NULL); + StrExprArg::setEngine(this); } // open mayu device -bool Engine::open() -{ - // open mayu m_device +bool Engine::open() { + // open mayu m_device #ifndef NO_DRIVER - m_device = CreateFile(MAYU_DEVICE_FILE_NAME, GENERIC_READ | GENERIC_WRITE, - 0, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); + m_device = CreateFile(MAYU_DEVICE_FILE_NAME, GENERIC_READ | GENERIC_WRITE, + 0, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); #endif // !NO_DRIVER - if (m_device != INVALID_HANDLE_VALUE) { - return true; - } + if (m_device != INVALID_HANDLE_VALUE) { + return true; + } #ifndef NO_DRIVER - // start mayud - SC_HANDLE hscm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); - if (hscm) - { - SC_HANDLE hs = OpenService(hscm, MAYU_DRIVER_NAME, SERVICE_START); - if (hs) - { - StartService(hs, 0, NULL); - CloseServiceHandle(hs); - m_didMayuStartDevice = true; - } - CloseServiceHandle(hscm); - } - - // open mayu m_device - m_device = CreateFile(MAYU_DEVICE_FILE_NAME, GENERIC_READ | GENERIC_WRITE, - 0, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); + // start mayud + SC_HANDLE hscm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); + if (hscm) { + SC_HANDLE hs = OpenService(hscm, MAYU_DRIVER_NAME, SERVICE_START); + if (hs) { + StartService(hs, 0, NULL); + CloseServiceHandle(hs); + m_didMayuStartDevice = true; + } + CloseServiceHandle(hscm); + } + + // open mayu m_device + m_device = CreateFile(MAYU_DEVICE_FILE_NAME, GENERIC_READ | GENERIC_WRITE, + 0, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); #endif // !NO_DRIVER - return (m_device != INVALID_HANDLE_VALUE); + return (m_device != INVALID_HANDLE_VALUE); } // close mayu device -void Engine::close() -{ - if (m_device != INVALID_HANDLE_VALUE) { +void Engine::close() { + if (m_device != INVALID_HANDLE_VALUE) { #ifndef NO_DRIVER - CHECK_TRUE( CloseHandle(m_device) ); + CHECK_TRUE( CloseHandle(m_device) ); #endif // !NO_DRIVER - } - m_device = INVALID_HANDLE_VALUE; + } + m_device = INVALID_HANDLE_VALUE; } // start keyboard handler thread -void Engine::start() -{ - CHECK_TRUE( m_threadEvent = CreateEvent(NULL, FALSE, FALSE, NULL) ); - - CHECK_TRUE( m_readEvent = CreateEvent(NULL, FALSE, FALSE, NULL) ); - CHECK_TRUE( m_interruptThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL) ); - m_ol.Offset = 0; - m_ol.OffsetHigh = 0; - m_ol.hEvent = m_readEvent; - - CHECK_TRUE( m_threadHandle = (HANDLE)_beginthreadex(NULL, 0, keyboardHandler, this, 0, &m_threadId) ); - CHECK( WAIT_OBJECT_0 ==, WaitForSingleObject(m_threadEvent, INFINITE) ); +void Engine::start() { + CHECK_TRUE( m_threadEvent = CreateEvent(NULL, FALSE, FALSE, NULL) ); + + CHECK_TRUE( m_readEvent = CreateEvent(NULL, FALSE, FALSE, NULL) ); + CHECK_TRUE( m_interruptThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL) ); + m_ol.Offset = 0; + m_ol.OffsetHigh = 0; + m_ol.hEvent = m_readEvent; + + CHECK_TRUE( m_threadHandle = (HANDLE)_beginthreadex(NULL, 0, keyboardHandler, this, 0, &m_threadId) ); + CHECK( WAIT_OBJECT_0 ==, WaitForSingleObject(m_threadEvent, INFINITE) ); } // stop keyboard handler thread -void Engine::stop() -{ - if (m_threadEvent) - { - m_doForceTerminate = true; - do - { - m_interruptThreadReason = InterruptThreadReason_Terminate; - SetEvent(m_interruptThreadEvent); - //DWORD buf; - //M_DeviceIoControl(m_device, IOCTL_MAYU_DETOUR_CANCEL, - // &buf, sizeof(buf), &buf, sizeof(buf), &buf, NULL); - - // wait for message handler thread terminate - } while (WaitForSingleObject(m_threadEvent, 100) != WAIT_OBJECT_0); - CHECK_TRUE( CloseHandle(m_threadEvent) ); - m_threadEvent = NULL; - WaitForSingleObject(m_threadHandle, 100); - CHECK_TRUE( CloseHandle(m_threadHandle) ); - m_threadHandle = NULL; - - // stop mayud - if (m_didMayuStartDevice) - { - SC_HANDLE hscm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); - if (hscm) - { - SC_HANDLE hs = OpenService(hscm, MAYU_DRIVER_NAME, SERVICE_STOP); - if (hs) - { - SERVICE_STATUS ss; - ControlService(hs, SERVICE_CONTROL_STOP, &ss); - CloseServiceHandle(hs); +void Engine::stop() { + if (m_threadEvent) { + m_doForceTerminate = true; + do { + m_interruptThreadReason = InterruptThreadReason_Terminate; + SetEvent(m_interruptThreadEvent); + //DWORD buf; + //M_DeviceIoControl(m_device, IOCTL_MAYU_DETOUR_CANCEL, + // &buf, sizeof(buf), &buf, sizeof(buf), &buf, NULL); + + // wait for message handler thread terminate + } while (WaitForSingleObject(m_threadEvent, 100) != WAIT_OBJECT_0); + CHECK_TRUE( CloseHandle(m_threadEvent) ); + m_threadEvent = NULL; + WaitForSingleObject(m_threadHandle, 100); + CHECK_TRUE( CloseHandle(m_threadHandle) ); + m_threadHandle = NULL; + + // stop mayud + if (m_didMayuStartDevice) { + SC_HANDLE hscm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); + if (hscm) { + SC_HANDLE hs = OpenService(hscm, MAYU_DRIVER_NAME, SERVICE_STOP); + if (hs) { + SERVICE_STATUS ss; + ControlService(hs, SERVICE_CONTROL_STOP, &ss); + CloseServiceHandle(hs); + } + CloseServiceHandle(hscm); + } + } + + CHECK_TRUE( CloseHandle(m_readEvent) ); + m_readEvent = NULL; + CHECK_TRUE( CloseHandle(m_interruptThreadEvent) ); + m_interruptThreadEvent = NULL; } - CloseServiceHandle(hscm); - } - } - - CHECK_TRUE( CloseHandle(m_readEvent) ); - m_readEvent = NULL; - CHECK_TRUE( CloseHandle(m_interruptThreadEvent) ); - m_interruptThreadEvent = NULL; - } } -bool Engine::pause() -{ - if (m_device != INVALID_HANDLE_VALUE) { - do { - m_interruptThreadReason = InterruptThreadReason_Pause; - SetEvent(m_interruptThreadEvent); - } while (WaitForSingleObject(m_threadEvent, 100) != WAIT_OBJECT_0); +bool Engine::pause() { + if (m_device != INVALID_HANDLE_VALUE) { + do { + m_interruptThreadReason = InterruptThreadReason_Pause; + SetEvent(m_interruptThreadEvent); + } while (WaitForSingleObject(m_threadEvent, 100) != WAIT_OBJECT_0); #ifndef NO_DRIVER - close(); + close(); #endif // !NO_DRIVER - } - return true; + } + return true; } -bool Engine::resume() -{ - if (m_device == INVALID_HANDLE_VALUE) { +bool Engine::resume() { + if (m_device == INVALID_HANDLE_VALUE) { #ifndef NO_DRIVER - if (!open()) { - return false; // FIXME - } + if (!open()) { + return false; // FIXME + } #endif // !NO_DRIVER - do { - m_interruptThreadReason = InterruptThreadReason_Resume; - SetEvent(m_interruptThreadEvent); - } while (WaitForSingleObject(m_threadEvent, 100) != WAIT_OBJECT_0); - } - return true; + do { + m_interruptThreadReason = InterruptThreadReason_Resume; + SetEvent(m_interruptThreadEvent); + } while (WaitForSingleObject(m_threadEvent, 100) != WAIT_OBJECT_0); + } + return true; } -bool Engine::prepairQuit() -{ - // terminate and unload DLL for ThumbSense support if loaded - manageTs4mayu(_T("sts4mayu.dll"), _T("SynCOM.dll"), - false, &m_sts4mayu); - manageTs4mayu(_T("cts4mayu.dll"), _T("TouchPad.dll"), - false, &m_cts4mayu); - return true; +bool Engine::prepairQuit() { + // terminate and unload DLL for ThumbSense support if loaded + manageTs4mayu(_T("sts4mayu.dll"), _T("SynCOM.dll"), + false, &m_sts4mayu); + manageTs4mayu(_T("cts4mayu.dll"), _T("TouchPad.dll"), + false, &m_cts4mayu); + return true; } -Engine::~Engine() -{ - stop(); - CHECK_TRUE( CloseHandle(m_eSync) ); - - // close m_device +Engine::~Engine() { + stop(); + CHECK_TRUE( CloseHandle(m_eSync) ); + + // close m_device #ifndef NO_DRIVER - close(); + close(); #endif // !NO_DRIVER - // destroy named pipe for &SetImeString - if (m_hookPipe && m_hookPipe != INVALID_HANDLE_VALUE) - { - DisconnectNamedPipe(m_hookPipe); - CHECK_TRUE( CloseHandle(m_hookPipe) ); - } + // destroy named pipe for &SetImeString + if (m_hookPipe && m_hookPipe != INVALID_HANDLE_VALUE) { + DisconnectNamedPipe(m_hookPipe); + CHECK_TRUE( CloseHandle(m_hookPipe) ); + } } void Engine::manageTs4mayu(TCHAR *i_ts4mayuDllName, - TCHAR *i_dependDllName, - bool i_load, HMODULE *i_pTs4mayu) -{ - Acquire a(&m_log, 0); - - if (i_load == false) - { - if (*i_pTs4mayu) - { - bool (WINAPI *pTs4mayuTerm)(); - - pTs4mayuTerm = (bool (WINAPI*)())GetProcAddress(*i_pTs4mayu, "ts4mayuTerm"); - if (pTs4mayuTerm() == true) - FreeLibrary(*i_pTs4mayu); - *i_pTs4mayu = NULL; - m_log << i_ts4mayuDllName <<_T(" unloaded") << std::endl; - } - } - else - { - if (*i_pTs4mayu) - { - m_log << i_ts4mayuDllName << _T(" already loaded") << std::endl; - } - else - { - if (SearchPath(NULL, i_dependDllName, NULL, 0, NULL, NULL) == 0) - { - m_log << _T("load ") << i_ts4mayuDllName - << _T(" failed: can't find ") << i_dependDllName - << std::endl; - } - else - { - *i_pTs4mayu = LoadLibrary(i_ts4mayuDllName); - if (*i_pTs4mayu == NULL) - { - m_log << _T("load ") << i_ts4mayuDllName - << _T(" failed: can't find it") << std::endl; - } - else - { - bool (WINAPI *pTs4mayuInit)(UINT); - - pTs4mayuInit = (bool (WINAPI*)(UINT))GetProcAddress(*i_pTs4mayu, "ts4mayuInit"); - if (pTs4mayuInit(m_threadId) == true) - m_log << i_ts4mayuDllName <<_T(" loaded") << std::endl; - else - m_log << i_ts4mayuDllName - <<_T(" load failed: can't initialize") << std::endl; + TCHAR *i_dependDllName, + bool i_load, HMODULE *i_pTs4mayu) { + Acquire a(&m_log, 0); + + if (i_load == false) { + if (*i_pTs4mayu) { + bool (WINAPI *pTs4mayuTerm)(); + + pTs4mayuTerm = (bool (WINAPI*)())GetProcAddress(*i_pTs4mayu, "ts4mayuTerm"); + if (pTs4mayuTerm() == true) + FreeLibrary(*i_pTs4mayu); + *i_pTs4mayu = NULL; + m_log << i_ts4mayuDllName <<_T(" unloaded") << std::endl; + } + } else { + if (*i_pTs4mayu) { + m_log << i_ts4mayuDllName << _T(" already loaded") << std::endl; + } else { + if (SearchPath(NULL, i_dependDllName, NULL, 0, NULL, NULL) == 0) { + m_log << _T("load ") << i_ts4mayuDllName + << _T(" failed: can't find ") << i_dependDllName + << std::endl; + } else { + *i_pTs4mayu = LoadLibrary(i_ts4mayuDllName); + if (*i_pTs4mayu == NULL) { + m_log << _T("load ") << i_ts4mayuDllName + << _T(" failed: can't find it") << std::endl; + } else { + bool (WINAPI *pTs4mayuInit)(UINT); + + pTs4mayuInit = (bool (WINAPI*)(UINT))GetProcAddress(*i_pTs4mayu, "ts4mayuInit"); + if (pTs4mayuInit(m_threadId) == true) + m_log << i_ts4mayuDllName <<_T(" loaded") << std::endl; + else + m_log << i_ts4mayuDllName + <<_T(" load failed: can't initialize") << std::endl; + } + } + } } - } - } - } } // set m_setting -bool Engine::setSetting(Setting *i_setting) -{ - Acquire a(&m_cs); - if (m_isSynchronizing) - return false; - - if (m_setting) - { - for (Keyboard::KeyIterator i = m_setting->m_keyboard.getKeyIterator(); - *i; ++ i) - { - Key *key = i_setting->m_keyboard.searchKey(*(*i)); - if (key) - { - key->m_isPressed = (*i)->m_isPressed; - key->m_isPressedOnWin32 = (*i)->m_isPressedOnWin32; - key->m_isPressedByAssign = (*i)->m_isPressedByAssign; - } - } - if (m_lastGeneratedKey) - m_lastGeneratedKey = - i_setting->m_keyboard.searchKey(*m_lastGeneratedKey); - for (size_t i = 0; i < NUMBER_OF(m_lastPressedKey); ++ i) - if (m_lastPressedKey[i]) - m_lastPressedKey[i] = - i_setting->m_keyboard.searchKey(*m_lastPressedKey[i]); - } - - m_setting = i_setting; - - manageTs4mayu(_T("sts4mayu.dll"), _T("SynCOM.dll"), - m_setting->m_sts4mayu, &m_sts4mayu); - manageTs4mayu(_T("cts4mayu.dll"), _T("TouchPad.dll"), - m_setting->m_cts4mayu, &m_cts4mayu); - - g_hookData->m_correctKanaLockHandling = m_setting->m_correctKanaLockHandling; - if (m_currentFocusOfThread) - { - for (FocusOfThreads::iterator i = m_focusOfThreads.begin(); - i != m_focusOfThreads.end(); i ++) - { - FocusOfThread *fot = &(*i).second; - m_setting->m_keymaps.searchWindow(&fot->m_keymaps, - fot->m_className, fot->m_titleName); - } - } - m_setting->m_keymaps.searchWindow(&m_globalFocus.m_keymaps, _T(""), _T("")); - if (m_globalFocus.m_keymaps.empty()) - { - Acquire a(&m_log, 0); - m_log << _T("internal error: m_globalFocus.m_keymap is empty") - << std::endl; - } - m_currentFocusOfThread = &m_globalFocus; - setCurrentKeymap(m_globalFocus.m_keymaps.front()); - m_hwndFocus = NULL; - return true; +bool Engine::setSetting(Setting *i_setting) { + Acquire a(&m_cs); + if (m_isSynchronizing) + return false; + + if (m_setting) { + for (Keyboard::KeyIterator i = m_setting->m_keyboard.getKeyIterator(); + *i; ++ i) { + Key *key = i_setting->m_keyboard.searchKey(*(*i)); + if (key) { + key->m_isPressed = (*i)->m_isPressed; + key->m_isPressedOnWin32 = (*i)->m_isPressedOnWin32; + key->m_isPressedByAssign = (*i)->m_isPressedByAssign; + } + } + if (m_lastGeneratedKey) + m_lastGeneratedKey = + i_setting->m_keyboard.searchKey(*m_lastGeneratedKey); + for (size_t i = 0; i < NUMBER_OF(m_lastPressedKey); ++ i) + if (m_lastPressedKey[i]) + m_lastPressedKey[i] = + i_setting->m_keyboard.searchKey(*m_lastPressedKey[i]); + } + + m_setting = i_setting; + + manageTs4mayu(_T("sts4mayu.dll"), _T("SynCOM.dll"), + m_setting->m_sts4mayu, &m_sts4mayu); + manageTs4mayu(_T("cts4mayu.dll"), _T("TouchPad.dll"), + m_setting->m_cts4mayu, &m_cts4mayu); + + g_hookData->m_correctKanaLockHandling = m_setting->m_correctKanaLockHandling; + if (m_currentFocusOfThread) { + for (FocusOfThreads::iterator i = m_focusOfThreads.begin(); + i != m_focusOfThreads.end(); i ++) { + FocusOfThread *fot = &(*i).second; + m_setting->m_keymaps.searchWindow(&fot->m_keymaps, + fot->m_className, fot->m_titleName); + } + } + m_setting->m_keymaps.searchWindow(&m_globalFocus.m_keymaps, _T(""), _T("")); + if (m_globalFocus.m_keymaps.empty()) { + Acquire a(&m_log, 0); + m_log << _T("internal error: m_globalFocus.m_keymap is empty") + << std::endl; + } + m_currentFocusOfThread = &m_globalFocus; + setCurrentKeymap(m_globalFocus.m_keymaps.front()); + m_hwndFocus = NULL; + return true; } -void Engine::checkShow(HWND i_hwnd) -{ - // update show style of window - // this update should be done in hook DLL, but to - // avoid update-loss for some applications(such as - // cmd.exe), we update here. - bool isMaximized = false; - bool isMinimized = false; - bool isMDIMaximized = false; - bool isMDIMinimized = false; - while (i_hwnd) - { +void Engine::checkShow(HWND i_hwnd) { + // update show style of window + // this update should be done in hook DLL, but to + // avoid update-loss for some applications(such as + // cmd.exe), we update here. + bool isMaximized = false; + bool isMinimized = false; + bool isMDIMaximized = false; + bool isMDIMinimized = false; + while (i_hwnd) { #ifdef MAYU64 - LONG_PTR exStyle = GetWindowLongPtr(i_hwnd, GWL_EXSTYLE); + LONG_PTR exStyle = GetWindowLongPtr(i_hwnd, GWL_EXSTYLE); #else - LONG exStyle = GetWindowLong(i_hwnd, GWL_EXSTYLE); + LONG exStyle = GetWindowLong(i_hwnd, GWL_EXSTYLE); #endif - if (exStyle & WS_EX_MDICHILD) - { - WINDOWPLACEMENT placement; - placement.length = sizeof(WINDOWPLACEMENT); - if (GetWindowPlacement(i_hwnd, &placement)) - { - switch (placement.showCmd) - { - case SW_SHOWMAXIMIZED: - isMDIMaximized = true; - break; - case SW_SHOWMINIMIZED: - isMDIMinimized = true; - break; - case SW_SHOWNORMAL: - default: - break; - } - } - } + if (exStyle & WS_EX_MDICHILD) { + WINDOWPLACEMENT placement; + placement.length = sizeof(WINDOWPLACEMENT); + if (GetWindowPlacement(i_hwnd, &placement)) { + switch (placement.showCmd) { + case SW_SHOWMAXIMIZED: + isMDIMaximized = true; + break; + case SW_SHOWMINIMIZED: + isMDIMinimized = true; + break; + case SW_SHOWNORMAL: + default: + break; + } + } + } #ifdef MAYU64 - LONG_PTR style = GetWindowLongPtr(i_hwnd, GWL_STYLE); + LONG_PTR style = GetWindowLongPtr(i_hwnd, GWL_STYLE); #else - LONG style = GetWindowLong(i_hwnd, GWL_STYLE); + LONG style = GetWindowLong(i_hwnd, GWL_STYLE); #endif - if ((style & WS_CHILD) == 0) - { - WINDOWPLACEMENT placement; - placement.length = sizeof(WINDOWPLACEMENT); - if (GetWindowPlacement(i_hwnd, &placement)) - { - switch (placement.showCmd) - { - case SW_SHOWMAXIMIZED: - isMaximized = true; - break; - case SW_SHOWMINIMIZED: - isMinimized = true; - break; - case SW_SHOWNORMAL: - default: - break; - } - } - } - i_hwnd = GetParent(i_hwnd); - } - setShow(isMDIMaximized, isMDIMinimized, true); - setShow(isMaximized, isMinimized, false); + if ((style & WS_CHILD) == 0) { + WINDOWPLACEMENT placement; + placement.length = sizeof(WINDOWPLACEMENT); + if (GetWindowPlacement(i_hwnd, &placement)) { + switch (placement.showCmd) { + case SW_SHOWMAXIMIZED: + isMaximized = true; + break; + case SW_SHOWMINIMIZED: + isMinimized = true; + break; + case SW_SHOWNORMAL: + default: + break; + } + } + } + i_hwnd = GetParent(i_hwnd); + } + setShow(isMDIMaximized, isMDIMinimized, true); + setShow(isMaximized, isMinimized, false); } // focus -bool Engine::setFocus(HWND i_hwndFocus, DWORD i_threadId, - const tstringi &i_className, const tstringi &i_titleName, - bool i_isConsole) -{ - Acquire a(&m_cs); - if (m_isSynchronizing) - return false; - if (i_hwndFocus == NULL) - return true; - - // remove newly created thread's id from m_detachedThreadIds - if (!m_detachedThreadIds.empty()) - { - DetachedThreadIds::iterator i; - bool retry; - do - { - retry = false; - for (i = m_detachedThreadIds.begin(); - i != m_detachedThreadIds.end(); ++ i) - if (*i == i_threadId) - { - m_detachedThreadIds.erase(i); - retry = true; - break; +bool Engine::setFocus(HWND i_hwndFocus, DWORD i_threadId, + const tstringi &i_className, const tstringi &i_titleName, + bool i_isConsole) { + Acquire a(&m_cs); + if (m_isSynchronizing) + return false; + if (i_hwndFocus == NULL) + return true; + + // remove newly created thread's id from m_detachedThreadIds + if (!m_detachedThreadIds.empty()) { + DetachedThreadIds::iterator i; + bool retry; + do { + retry = false; + for (i = m_detachedThreadIds.begin(); + i != m_detachedThreadIds.end(); ++ i) + if (*i == i_threadId) { + m_detachedThreadIds.erase(i); + retry = true; + break; + } + } while (retry); + } + + FocusOfThread *fot; + FocusOfThreads::iterator i = m_focusOfThreads.find(i_threadId); + if (i != m_focusOfThreads.end()) { + fot = &(*i).second; + if (fot->m_hwndFocus == i_hwndFocus && + fot->m_isConsole == i_isConsole && + fot->m_className == i_className && + fot->m_titleName == i_titleName) + return true; + } else { + i = m_focusOfThreads.insert( + FocusOfThreads::value_type(i_threadId, FocusOfThread())).first; + fot = &(*i).second; + fot->m_threadId = i_threadId; } - } while (retry); - } - - FocusOfThread *fot; - FocusOfThreads::iterator i = m_focusOfThreads.find(i_threadId); - if (i != m_focusOfThreads.end()) - { - fot = &(*i).second; - if (fot->m_hwndFocus == i_hwndFocus && - fot->m_isConsole == i_isConsole && - fot->m_className == i_className && - fot->m_titleName == i_titleName) - return true; - } - else - { - i = m_focusOfThreads.insert( - FocusOfThreads::value_type(i_threadId, FocusOfThread())).first; - fot = &(*i).second; - fot->m_threadId = i_threadId; - } - fot->m_hwndFocus = i_hwndFocus; - fot->m_isConsole = i_isConsole; - fot->m_className = i_className; - fot->m_titleName = i_titleName; - - if (m_setting) - { - m_setting->m_keymaps.searchWindow(&fot->m_keymaps, - i_className, i_titleName); - ASSERT(0 < fot->m_keymaps.size()); - } - else - fot->m_keymaps.clear(); - checkShow(i_hwndFocus); - return true; + fot->m_hwndFocus = i_hwndFocus; + fot->m_isConsole = i_isConsole; + fot->m_className = i_className; + fot->m_titleName = i_titleName; + + if (m_setting) { + m_setting->m_keymaps.searchWindow(&fot->m_keymaps, + i_className, i_titleName); + ASSERT(0 < fot->m_keymaps.size()); + } else + fot->m_keymaps.clear(); + checkShow(i_hwndFocus); + return true; } // lock state bool Engine::setLockState(bool i_isNumLockToggled, - bool i_isCapsLockToggled, - bool i_isScrollLockToggled, - bool i_isKanaLockToggled, - bool i_isImeLockToggled, - bool i_isImeCompToggled) -{ - Acquire a(&m_cs); - if (m_isSynchronizing) - return false; - m_currentLock.on(Modifier::Type_NumLock, i_isNumLockToggled); - m_currentLock.on(Modifier::Type_CapsLock, i_isCapsLockToggled); - m_currentLock.on(Modifier::Type_ScrollLock, i_isScrollLockToggled); - m_currentLock.on(Modifier::Type_KanaLock, i_isKanaLockToggled); - m_currentLock.on(Modifier::Type_ImeLock, i_isImeLockToggled); - m_currentLock.on(Modifier::Type_ImeComp, i_isImeCompToggled); - return true; + bool i_isCapsLockToggled, + bool i_isScrollLockToggled, + bool i_isKanaLockToggled, + bool i_isImeLockToggled, + bool i_isImeCompToggled) { + Acquire a(&m_cs); + if (m_isSynchronizing) + return false; + m_currentLock.on(Modifier::Type_NumLock, i_isNumLockToggled); + m_currentLock.on(Modifier::Type_CapsLock, i_isCapsLockToggled); + m_currentLock.on(Modifier::Type_ScrollLock, i_isScrollLockToggled); + m_currentLock.on(Modifier::Type_KanaLock, i_isKanaLockToggled); + m_currentLock.on(Modifier::Type_ImeLock, i_isImeLockToggled); + m_currentLock.on(Modifier::Type_ImeComp, i_isImeCompToggled); + return true; } // show bool Engine::setShow(bool i_isMaximized, bool i_isMinimized, - bool i_isMDI) -{ - Acquire a(&m_cs); - if (m_isSynchronizing) - return false; - Acquire b(&m_log, 1); - Modifier::Type max, min; - if (i_isMDI == true) { - max = Modifier::Type_MdiMaximized; - min = Modifier::Type_MdiMinimized; - } - else - { - max = Modifier::Type_Maximized; - min = Modifier::Type_Minimized; - } - m_currentLock.on(max, i_isMaximized); - m_currentLock.on(min, i_isMinimized); - m_log << _T("Set show to ") << (i_isMaximized ? _T("Maximized") : - i_isMinimized ? _T("Minimized") : _T("Normal")); - if (i_isMDI == true) - { - m_log << _T(" (MDI)"); - } - m_log << std::endl; - return true; + bool i_isMDI) { + Acquire a(&m_cs); + if (m_isSynchronizing) + return false; + Acquire b(&m_log, 1); + Modifier::Type max, min; + if (i_isMDI == true) { + max = Modifier::Type_MdiMaximized; + min = Modifier::Type_MdiMinimized; + } else { + max = Modifier::Type_Maximized; + min = Modifier::Type_Minimized; + } + m_currentLock.on(max, i_isMaximized); + m_currentLock.on(min, i_isMinimized); + m_log << _T("Set show to ") << (i_isMaximized ? _T("Maximized") : + i_isMinimized ? _T("Minimized") : _T("Normal")); + if (i_isMDI == true) { + m_log << _T(" (MDI)"); + } + m_log << std::endl; + return true; } // sync -bool Engine::syncNotify() -{ - Acquire a(&m_cs); - if (!m_isSynchronizing) - return false; - CHECK_TRUE( SetEvent(m_eSync) ); - return true; +bool Engine::syncNotify() { + Acquire a(&m_cs); + if (!m_isSynchronizing) + return false; + CHECK_TRUE( SetEvent(m_eSync) ); + return true; } // thread detach notify -bool Engine::threadDetachNotify(DWORD i_threadId) -{ - Acquire a(&m_cs); - m_detachedThreadIds.push_back(i_threadId); - return true; +bool Engine::threadDetachNotify(DWORD i_threadId) { + Acquire a(&m_cs); + m_detachedThreadIds.push_back(i_threadId); + return true; } // get help message -void Engine::getHelpMessages(tstring *o_helpMessage, tstring *o_helpTitle) -{ - Acquire a(&m_cs); - *o_helpMessage = m_helpMessage; - *o_helpTitle = m_helpTitle; +void Engine::getHelpMessages(tstring *o_helpMessage, tstring *o_helpTitle) { + Acquire a(&m_cs); + *o_helpMessage = m_helpMessage; + *o_helpTitle = m_helpTitle; } // command notify void Engine::commandNotify( - HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam) -{ - Acquire b(&m_log, 0); - HWND hf = m_hwndFocus; - if (!hf) - return; - - if (GetWindowThreadProcessId(hf, NULL) == - GetWindowThreadProcessId(m_hwndAssocWindow, NULL)) - return; // inhibit the investigation of MADO TSUKAI NO YUUTSU - - const _TCHAR *target = NULL; - int number_target = 0; - - if (i_hwnd == hf) - target = _T("ToItself"); - else if (i_hwnd == GetParent(hf)) - target = _T("ToParentWindow"); - else - { - // Function::toMainWindow - HWND h = hf; - while (true) - { - HWND p = GetParent(h); - if (!p) - break; - h = p; - } - if (i_hwnd == h) - target = _T("ToMainWindow"); - else - { - // Function::toOverlappedWindow - HWND h = hf; - while (h) - { + HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam) { + Acquire b(&m_log, 0); + HWND hf = m_hwndFocus; + if (!hf) + return; + + if (GetWindowThreadProcessId(hf, NULL) == + GetWindowThreadProcessId(m_hwndAssocWindow, NULL)) + return; // inhibit the investigation of MADO TSUKAI NO YUUTSU + + const _TCHAR *target = NULL; + int number_target = 0; + + if (i_hwnd == hf) + target = _T("ToItself"); + else if (i_hwnd == GetParent(hf)) + target = _T("ToParentWindow"); + else { + // Function::toMainWindow + HWND h = hf; + while (true) { + HWND p = GetParent(h); + if (!p) + break; + h = p; + } + if (i_hwnd == h) + target = _T("ToMainWindow"); + else { + // Function::toOverlappedWindow + HWND h = hf; + while (h) { #ifdef MAYU64 - LONG_PTR style = GetWindowLongPtr(h, GWL_STYLE); + LONG_PTR style = GetWindowLongPtr(h, GWL_STYLE); #else - LONG style = GetWindowLong(h, GWL_STYLE); + LONG style = GetWindowLong(h, GWL_STYLE); #endif - if ((style & WS_CHILD) == 0) - break; - h = GetParent(h); - } - if (i_hwnd == h) - target = _T("ToOverlappedWindow"); - else - { - // number - HWND h = hf; - for (number_target = 0; h; number_target ++, h = GetParent(h)) - if (i_hwnd == h) - break; - return; - } - } - } - - m_log << _T("&PostMessage("); - if (target) - m_log << target; - else - m_log << number_target; - m_log << _T(", ") << i_message + if ((style & WS_CHILD) == 0) + break; + h = GetParent(h); + } + if (i_hwnd == h) + target = _T("ToOverlappedWindow"); + else { + // number + HWND h = hf; + for (number_target = 0; h; number_target ++, h = GetParent(h)) + if (i_hwnd == h) + break; + return; + } + } + } + + m_log << _T("&PostMessage("); + if (target) + m_log << target; + else + m_log << number_target; + m_log << _T(", ") << i_message << _T(", 0x") << std::hex << i_wParam << _T(", 0x") << i_lParam << _T(") # hwnd = ") << reinterpret_cast(i_hwnd) << _T(", ") << _T("message = ") << std::dec; - if (i_message == WM_COMMAND) - m_log << _T("WM_COMMAND, "); - else if (i_message == WM_SYSCOMMAND) - m_log << _T("WM_SYSCOMMAND, "); - else - m_log << i_message << _T(", "); - m_log << _T("wNotifyCode = ") << HIWORD(i_wParam) << _T(", ") + if (i_message == WM_COMMAND) + m_log << _T("WM_COMMAND, "); + else if (i_message == WM_SYSCOMMAND) + m_log << _T("WM_SYSCOMMAND, "); + else + m_log << i_message << _T(", "); + m_log << _T("wNotifyCode = ") << HIWORD(i_wParam) << _T(", ") << _T("wID = ") << LOWORD(i_wParam) << _T(", ") << _T("hwndCtrl = 0x") << std::hex << i_lParam << std::dec << std::endl; } diff --git a/engine.h b/engine.h index fd068a9..636bd61 100644 --- a/engine.h +++ b/engine.h @@ -12,22 +12,20 @@ # include -enum -{ - /// - WM_APP_engineNotify = WM_APP + 110, +enum { + /// + WM_APP_engineNotify = WM_APP + 110, }; /// -enum EngineNotify -{ - EngineNotify_shellExecute, /// - EngineNotify_loadSetting, /// - EngineNotify_showDlg, /// - EngineNotify_helpMessage, /// - EngineNotify_setForegroundWindow, /// - EngineNotify_clearLog, /// +enum EngineNotify { + EngineNotify_shellExecute, /// + EngineNotify_loadSetting, /// + EngineNotify_showDlg, /// + EngineNotify_helpMessage, /// + EngineNotify_setForegroundWindow, /// + EngineNotify_clearLog, /// }; @@ -35,551 +33,570 @@ enum EngineNotify class Engine { private: - enum - { - MAX_GENERATE_KEYBOARD_EVENTS_RECURSION_COUNT = 64, /// - MAX_KEYMAP_PREFIX_HISTORY = 64, /// - }; - - typedef Keymaps::KeymapPtrList KeymapPtrList; /// - - /// focus of a thread - class FocusOfThread - { - public: - DWORD m_threadId; /// thread id - HWND m_hwndFocus; /** window that has focus on + enum { + MAX_GENERATE_KEYBOARD_EVENTS_RECURSION_COUNT = 64, /// + MAX_KEYMAP_PREFIX_HISTORY = 64, /// + }; + + typedef Keymaps::KeymapPtrList KeymapPtrList; /// + + /// focus of a thread + class FocusOfThread + { + public: + DWORD m_threadId; /// thread id + HWND m_hwndFocus; /** window that has focus on the thread */ - tstringi m_className; /// class name of hwndFocus - tstringi m_titleName; /// title name of hwndFocus - bool m_isConsole; /// is hwndFocus console ? - KeymapPtrList m_keymaps; /// keymaps - - public: - /// - FocusOfThread() : m_threadId(0), m_hwndFocus(NULL), m_isConsole(false) { } - }; - typedef std::map FocusOfThreads; /// - - typedef std::list DetachedThreadIds; /// - - /// current status in generateKeyboardEvents - class Current - { - public: - const Keymap *m_keymap; /// current keymap - ModifiedKey m_mkey; /// current processing key that user inputed - /// index in currentFocusOfThread->keymaps - Keymaps::KeymapPtrList::iterator m_i; - - public: - /// - bool isPressed() const - { return m_mkey.m_modifier.isOn(Modifier::Type_Down); } - }; - - friend class FunctionParam; - - /// part of keySeq - enum Part - { - Part_all, /// - Part_up, /// - Part_down, /// - }; - - /// - class EmacsEditKillLine - { - tstring m_buf; /// previous kill-line contents - - public: - bool m_doForceReset; /// - - private: - /// - HGLOBAL makeNewKillLineBuf(const _TCHAR *i_data, int *i_retval); - - public: - /// - void reset() { m_buf.resize(0); } - /** EmacsEditKillLineFunc. - clear the contents of the clopboard - at that time, confirm if it is the result of the previous kill-line - */ - void func(); - /// EmacsEditKillLinePred - int pred(); - }; - - /// window positon for &WindowHMaximize, &WindowVMaximize - class WindowPosition - { - public: - /// - enum Mode - { - Mode_normal, /// - Mode_H, /// - Mode_V, /// - Mode_HV, /// - }; - - public: - HWND m_hwnd; /// - RECT m_rc; /// - Mode m_mode; /// - - public: - /// - WindowPosition(HWND i_hwnd, const RECT &i_rc, Mode i_mode) - : m_hwnd(i_hwnd), m_rc(i_rc), m_mode(i_mode) { } - }; - typedef std::list WindowPositions; - - typedef std::list WindowsWithAlpha; /// windows for &WindowSetAlpha - - enum InterruptThreadReason - { - InterruptThreadReason_Terminate, - InterruptThreadReason_Pause, - InterruptThreadReason_Resume, - }; + tstringi m_className; /// class name of hwndFocus + tstringi m_titleName; /// title name of hwndFocus + bool m_isConsole; /// is hwndFocus console ? + KeymapPtrList m_keymaps; /// keymaps + + public: + /// + FocusOfThread() : m_threadId(0), m_hwndFocus(NULL), m_isConsole(false) { } + }; + typedef std::map FocusOfThreads; /// + + typedef std::list DetachedThreadIds; /// + + /// current status in generateKeyboardEvents + class Current + { + public: + const Keymap *m_keymap; /// current keymap + ModifiedKey m_mkey; /// current processing key that user inputed + /// index in currentFocusOfThread->keymaps + Keymaps::KeymapPtrList::iterator m_i; + + public: + /// + bool isPressed() const { + return m_mkey.m_modifier.isOn(Modifier::Type_Down); + } + }; + + friend class FunctionParam; + + /// part of keySeq + enum Part { + Part_all, /// + Part_up, /// + Part_down, /// + }; + + /// + class EmacsEditKillLine + { + tstring m_buf; /// previous kill-line contents + + public: + bool m_doForceReset; /// + + private: + /// + HGLOBAL makeNewKillLineBuf(const _TCHAR *i_data, int *i_retval); + + public: + /// + void reset() { + m_buf.resize(0); + } + /** EmacsEditKillLineFunc. + clear the contents of the clopboard + at that time, confirm if it is the result of the previous kill-line + */ + void func(); + /// EmacsEditKillLinePred + int pred(); + }; + + /// window positon for &WindowHMaximize, &WindowVMaximize + class WindowPosition + { + public: + /// + enum Mode { + Mode_normal, /// + Mode_H, /// + Mode_V, /// + Mode_HV, /// + }; + + public: + HWND m_hwnd; /// + RECT m_rc; /// + Mode m_mode; /// + + public: + /// + WindowPosition(HWND i_hwnd, const RECT &i_rc, Mode i_mode) + : m_hwnd(i_hwnd), m_rc(i_rc), m_mode(i_mode) { } + }; + typedef std::list WindowPositions; + + typedef std::list WindowsWithAlpha; /// windows for &WindowSetAlpha + + enum InterruptThreadReason { + InterruptThreadReason_Terminate, + InterruptThreadReason_Pause, + InterruptThreadReason_Resume, + }; private: - CriticalSection m_cs; /// criticalSection - - // setting - HWND m_hwndAssocWindow; /** associated window (we post + CriticalSection m_cs; /// criticalSection + + // setting + HWND m_hwndAssocWindow; /** associated window (we post message to it) */ - Setting * volatile m_setting; /// setting - - // engine thread state - HANDLE m_device; /// mayu device - bool m_didMayuStartDevice; /** Did the mayu start the + Setting * volatile m_setting; /// setting + + // engine thread state + HANDLE m_device; /// mayu device + bool m_didMayuStartDevice; /** Did the mayu start the mayu-device ? */ - HANDLE m_threadEvent; /** 1. thread has been started + HANDLE m_threadEvent; /** 1. thread has been started 2. thread is about to end*/ - HANDLE m_threadHandle; - unsigned m_threadId; - tstring m_mayudVersion; /// version of mayud.sys + HANDLE m_threadHandle; + unsigned m_threadId; + tstring m_mayudVersion; /// version of mayud.sys #ifdef NO_DRIVER - std::deque m_kidq; - CriticalSection m_cskidq; + std::deque m_kidq; + CriticalSection m_cskidq; #endif // NO_DRIVER - HANDLE m_readEvent; /** reading from mayu device + HANDLE m_readEvent; /** reading from mayu device has been completed */ - HANDLE m_interruptThreadEvent; /// interrupt thread event - volatile InterruptThreadReason - m_interruptThreadReason; /// interrupt thread reason - OVERLAPPED m_ol; /** for async read/write of + HANDLE m_interruptThreadEvent; /// interrupt thread event + volatile InterruptThreadReason + m_interruptThreadReason; /// interrupt thread reason + OVERLAPPED m_ol; /** for async read/write of mayu device */ - HANDLE m_hookPipe; /// named pipe for &SetImeString - HMODULE m_sts4mayu; /// DLL module for ThumbSense - HMODULE m_cts4mayu; /// DLL module for ThumbSense - bool volatile m_doForceTerminate; /// terminate engine thread - bool volatile m_isLogMode; /// is logging mode ? - bool volatile m_isEnabled; /// is enabled ? - bool volatile m_isSynchronizing; /// is synchronizing ? - HANDLE m_eSync; /// event for synchronization - int m_generateKeyboardEventsRecursionGuard; /** guard against too many + HANDLE m_hookPipe; /// named pipe for &SetImeString + HMODULE m_sts4mayu; /// DLL module for ThumbSense + HMODULE m_cts4mayu; /// DLL module for ThumbSense + bool volatile m_doForceTerminate; /// terminate engine thread + bool volatile m_isLogMode; /// is logging mode ? + bool volatile m_isEnabled; /// is enabled ? + bool volatile m_isSynchronizing; /// is synchronizing ? + HANDLE m_eSync; /// event for synchronization + int m_generateKeyboardEventsRecursionGuard; /** guard against too many recursion */ - - // current key state - Modifier m_currentLock; /// current lock key's state - int m_currentKeyPressCount; /** how many keys are pressed + + // current key state + Modifier m_currentLock; /// current lock key's state + int m_currentKeyPressCount; /** how many keys are pressed phisically ? */ - int m_currentKeyPressCountOnWin32; /** how many keys are pressed + int m_currentKeyPressCountOnWin32; /** how many keys are pressed on win32 ? */ - Key *m_lastGeneratedKey; /// last generated key - Key *m_lastPressedKey[2]; /// last pressed key - ModifiedKey m_oneShotKey; /// one shot key - unsigned int m_oneShotRepeatableRepeatCount; /// repeat count of one shot key - bool m_isPrefix; /// is prefix ? - bool m_doesIgnoreModifierForPrefix; /** does ignore modifier key + Key *m_lastGeneratedKey; /// last generated key + Key *m_lastPressedKey[2]; /// last pressed key + ModifiedKey m_oneShotKey; /// one shot key + unsigned int m_oneShotRepeatableRepeatCount; /// repeat count of one shot key + bool m_isPrefix; /// is prefix ? + bool m_doesIgnoreModifierForPrefix; /** does ignore modifier key when prefixed ? */ - bool m_doesEditNextModifier; /** does edit next user input + bool m_doesEditNextModifier; /** does edit next user input key's modifier ? */ - Modifier m_modifierForNextKey; /** modifier for next key if + Modifier m_modifierForNextKey; /** modifier for next key if above is true */ - /** current keymaps. -
-
when &OtherWindowClass -
currentKeymap becoms currentKeymaps[++ Current::i] -
when &KeymapParent -
currentKeymap becoms currentKeyamp->parentKeymap -
other -
currentKeyamp becoms *Current::i -
- */ - const Keymap * volatile m_currentKeymap; /// current keymap - FocusOfThreads /*volatile*/ m_focusOfThreads; /// - FocusOfThread * volatile m_currentFocusOfThread; /// - FocusOfThread m_globalFocus; /// - HWND m_hwndFocus; /// current focus window - DetachedThreadIds m_detachedThreadIds; /// - - // for functions - KeymapPtrList m_keymapPrefixHistory; /// for &KeymapPrevPrefix - EmacsEditKillLine m_emacsEditKillLine; /// for &EmacsEditKillLine - const ActionFunction *m_afShellExecute; /// for &ShellExecute - - WindowPositions m_windowPositions; /// - WindowsWithAlpha m_windowsWithAlpha; /// - - tstring m_helpMessage; /// for &HelpMessage - tstring m_helpTitle; /// for &HelpMessage - int m_variable; /// for &Variable, - /// &Repeat + /** current keymaps. +
+
when &OtherWindowClass +
currentKeymap becoms currentKeymaps[++ Current::i] +
when &KeymapParent +
currentKeymap becoms currentKeyamp->parentKeymap +
other +
currentKeyamp becoms *Current::i +
+ */ + const Keymap * volatile m_currentKeymap; /// current keymap + FocusOfThreads /*volatile*/ m_focusOfThreads; /// + FocusOfThread * volatile m_currentFocusOfThread; /// + FocusOfThread m_globalFocus; /// + HWND m_hwndFocus; /// current focus window + DetachedThreadIds m_detachedThreadIds; /// + + // for functions + KeymapPtrList m_keymapPrefixHistory; /// for &KeymapPrevPrefix + EmacsEditKillLine m_emacsEditKillLine; /// for &EmacsEditKillLine + const ActionFunction *m_afShellExecute; /// for &ShellExecute + + WindowPositions m_windowPositions; /// + WindowsWithAlpha m_windowsWithAlpha; /// + + tstring m_helpMessage; /// for &HelpMessage + tstring m_helpTitle; /// for &HelpMessage + int m_variable; /// for &Variable, + /// &Repeat public: - tomsgstream &m_log; /** log stream (output to log + tomsgstream &m_log; /** log stream (output to log dialog's edit) */ - + public: #ifdef NO_DRIVER - /// keyboard handler thread - static unsigned int WINAPI keyboardDetour(Engine *i_this, KBDLLHOOKSTRUCT *i_kid); + /// keyboard handler thread + static unsigned int WINAPI keyboardDetour(Engine *i_this, KBDLLHOOKSTRUCT *i_kid); private: - /// - unsigned int keyboardDetour(KBDLLHOOKSTRUCT *i_kid); - /// - unsigned int injectInput(const KEYBOARD_INPUT_DATA *i_kid, const KBDLLHOOKSTRUCT *i_kidRaw); + /// + unsigned int keyboardDetour(KBDLLHOOKSTRUCT *i_kid); + /// + unsigned int injectInput(const KEYBOARD_INPUT_DATA *i_kid, const KBDLLHOOKSTRUCT *i_kidRaw); #endif // NO_DRIVER - + private: - /// keyboard handler thread - static unsigned int WINAPI keyboardHandler(void *i_this); - /// - void keyboardHandler(); - - /// check focus window - void checkFocusWindow(); - /// is modifier pressed ? - bool isPressed(Modifier::Type i_mt); - /// fix modifier key - bool fixModifierKey(ModifiedKey *io_mkey, Keymap::AssignMode *o_am); - - /// output to log - void outputToLog(const Key *i_key, const ModifiedKey &i_mkey, - int i_debugLevel); - - /// genete modifier events - void generateModifierEvents(const Modifier &i_mod); - - /// genete event - void generateEvents(Current i_c, const Keymap *i_keymap, Key *i_event); - - /// generate keyboard event - void generateKeyEvent(Key *i_key, bool i_doPress, bool i_isByAssign); - /// - void generateActionEvents(const Current &i_c, const Action *i_a, - bool i_doPress); - /// - void generateKeySeqEvents(const Current &i_c, const KeySeq *i_keySeq, - Part i_part); - /// - void generateKeyboardEvents(const Current &i_c); - /// - void beginGeneratingKeyboardEvents(const Current &i_c, bool i_isModifier); - - /// pop all pressed key on win32 - void keyboardResetOnWin32(); - - /// get current modifiers - Modifier getCurrentModifiers(Key *i_key, bool i_isPressed); - - /// describe bindings - void describeBindings(); - - /// update m_lastPressedKey - void updateLastPressedKey(Key *i_key); - - /// set current keymap - void setCurrentKeymap(const Keymap *i_keymap, - bool i_doesAddToHistory = false); - /** open mayu device - @return true if mayu device successfully is opened - */ - bool open(); - - /// close mayu device - void close(); - - /// load/unload [sc]ts4mayu.dll - void manageTs4mayu(TCHAR *i_ts4mayuDllName, TCHAR *i_dependDllName, - bool i_load, HMODULE *i_pTs4mayu); + /// keyboard handler thread + static unsigned int WINAPI keyboardHandler(void *i_this); + /// + void keyboardHandler(); + + /// check focus window + void checkFocusWindow(); + /// is modifier pressed ? + bool isPressed(Modifier::Type i_mt); + /// fix modifier key + bool fixModifierKey(ModifiedKey *io_mkey, Keymap::AssignMode *o_am); + + /// output to log + void outputToLog(const Key *i_key, const ModifiedKey &i_mkey, + int i_debugLevel); + + /// genete modifier events + void generateModifierEvents(const Modifier &i_mod); + + /// genete event + void generateEvents(Current i_c, const Keymap *i_keymap, Key *i_event); + + /// generate keyboard event + void generateKeyEvent(Key *i_key, bool i_doPress, bool i_isByAssign); + /// + void generateActionEvents(const Current &i_c, const Action *i_a, + bool i_doPress); + /// + void generateKeySeqEvents(const Current &i_c, const KeySeq *i_keySeq, + Part i_part); + /// + void generateKeyboardEvents(const Current &i_c); + /// + void beginGeneratingKeyboardEvents(const Current &i_c, bool i_isModifier); + + /// pop all pressed key on win32 + void keyboardResetOnWin32(); + + /// get current modifiers + Modifier getCurrentModifiers(Key *i_key, bool i_isPressed); + + /// describe bindings + void describeBindings(); + + /// update m_lastPressedKey + void updateLastPressedKey(Key *i_key); + + /// set current keymap + void setCurrentKeymap(const Keymap *i_keymap, + bool i_doesAddToHistory = false); + /** open mayu device + @return true if mayu device successfully is opened + */ + bool open(); + + /// close mayu device + void close(); + + /// load/unload [sc]ts4mayu.dll + void manageTs4mayu(TCHAR *i_ts4mayuDllName, TCHAR *i_dependDllName, + bool i_load, HMODULE *i_pTs4mayu); private: - // BEGINING OF FUNCTION DEFINITION - /// send a default key to Windows - void funcDefault(FunctionParam *i_param); - /// use a corresponding key of a parent keymap - void funcKeymapParent(FunctionParam *i_param); - /// use a corresponding key of a current window - void funcKeymapWindow(FunctionParam *i_param); - /// use a corresponding key of the previous prefixed keymap - void funcKeymapPrevPrefix(FunctionParam *i_param, int i_previous); - /// use a corresponding key of an other window class, or use a default key - void funcOtherWindowClass(FunctionParam *i_param); - /// prefix key - void funcPrefix(FunctionParam *i_param, const Keymap *i_keymap, - BooleanType i_doesIgnoreModifiers = BooleanType_true); - /// other keymap's key - void funcKeymap(FunctionParam *i_param, const Keymap *i_keymap); - /// sync - void funcSync(FunctionParam *i_param); - /// toggle lock - void funcToggle(FunctionParam *i_param, ModifierLockType i_lock, - ToggleType i_toggle = ToggleType_toggle); - /// edit next user input key's modifier - void funcEditNextModifier(FunctionParam *i_param, - const Modifier &i_modifier); - /// variable - void funcVariable(FunctionParam *i_param, int i_mag, int i_inc); - /// repeat N times - void funcRepeat(FunctionParam *i_param, const KeySeq *i_keySeq, - int i_max = 10); - /// undefined (bell) - void funcUndefined(FunctionParam *i_param); - /// ignore - void funcIgnore(FunctionParam *i_param); - /// post message - void funcPostMessage(FunctionParam *i_param, ToWindowType i_window, - UINT i_message, WPARAM i_wParam, LPARAM i_lParam); - /// ShellExecute - void funcShellExecute(FunctionParam *i_param, const StrExprArg &i_operation, - const StrExprArg &i_file, const StrExprArg &i_parameters, - const StrExprArg &i_directory, - ShowCommandType i_showCommand); - /// SetForegroundWindow - void funcSetForegroundWindow(FunctionParam *i_param, - const tregex &i_windowClassName, - LogicalOperatorType i_logicalOp - = LogicalOperatorType_and, - const tregex &i_windowTitleName - = tregex(_T(".*"))); - /// load setting - void funcLoadSetting(FunctionParam *i_param, - const StrExprArg &i_name = StrExprArg()); - /// virtual key - void funcVK(FunctionParam *i_param, VKey i_vkey); - /// wait - void funcWait(FunctionParam *i_param, int i_milliSecond); - /// investigate WM_COMMAND, WM_SYSCOMMAND - void funcInvestigateCommand(FunctionParam *i_param); - /// show mayu dialog box - void funcMayuDialog(FunctionParam *i_param, MayuDialogType i_dialog, - ShowCommandType i_showCommand); - /// describe bindings - void funcDescribeBindings(FunctionParam *i_param); - /// show help message - void funcHelpMessage(FunctionParam *i_param, - const StrExprArg &i_title = StrExprArg(), - const StrExprArg &i_message = StrExprArg()); - /// show variable - void funcHelpVariable(FunctionParam *i_param, const StrExprArg &i_title); - /// raise window - void funcWindowRaise(FunctionParam *i_param, - TargetWindowType i_twt = TargetWindowType_overlapped); - /// lower window - void funcWindowLower(FunctionParam *i_param, - TargetWindowType i_twt = TargetWindowType_overlapped); - /// minimize window - void funcWindowMinimize(FunctionParam *i_param, TargetWindowType i_twt - = TargetWindowType_overlapped); - /// maximize window - void funcWindowMaximize(FunctionParam *i_param, TargetWindowType i_twt - = TargetWindowType_overlapped); - /// maximize window horizontally - void funcWindowHMaximize(FunctionParam *i_param, TargetWindowType i_twt - = TargetWindowType_overlapped); - /// maximize window virtically - void funcWindowVMaximize(FunctionParam *i_param, TargetWindowType i_twt - = TargetWindowType_overlapped); - /// maximize window virtically or horizontally - void funcWindowHVMaximize(FunctionParam *i_param, BooleanType i_isHorizontal, - TargetWindowType i_twt - = TargetWindowType_overlapped); - /// move window - void funcWindowMove(FunctionParam *i_param, int i_dx, int i_dy, - TargetWindowType i_twt - = TargetWindowType_overlapped); - /// move window to ... - void funcWindowMoveTo(FunctionParam *i_param, GravityType i_gravityType, - int i_dx, int i_dy, TargetWindowType i_twt - = TargetWindowType_overlapped); - /// move window visibly - void funcWindowMoveVisibly(FunctionParam *i_param, - TargetWindowType i_twt - = TargetWindowType_overlapped); - /// move window to other monitor - void funcWindowMonitorTo(FunctionParam *i_param, - WindowMonitorFromType i_fromType, int i_monitor, - BooleanType i_adjustPos = BooleanType_true, - BooleanType i_adjustSize = BooleanType_false); - /// move window to other monitor - void funcWindowMonitor(FunctionParam *i_param, int i_monitor, - BooleanType i_adjustPos = BooleanType_true, - BooleanType i_adjustSize = BooleanType_false); - /// - void funcWindowClingToLeft(FunctionParam *i_param, - TargetWindowType i_twt - = TargetWindowType_overlapped); - /// - void funcWindowClingToRight(FunctionParam *i_param, - TargetWindowType i_twt - = TargetWindowType_overlapped); - /// - void funcWindowClingToTop(FunctionParam *i_param, - TargetWindowType i_twt - = TargetWindowType_overlapped); - /// - void funcWindowClingToBottom(FunctionParam *i_param, - TargetWindowType i_twt - = TargetWindowType_overlapped); - /// close window - void funcWindowClose(FunctionParam *i_param, - TargetWindowType i_twt = TargetWindowType_overlapped); - /// toggle top-most flag of the window - void funcWindowToggleTopMost(FunctionParam *i_param); - /// identify the window - void funcWindowIdentify(FunctionParam *i_param); - /// set alpha blending parameter to the window - void funcWindowSetAlpha(FunctionParam *i_param, int i_alpha); - /// redraw the window - void funcWindowRedraw(FunctionParam *i_param); - /// resize window to - void funcWindowResizeTo(FunctionParam *i_param, int i_width, int i_height, - TargetWindowType i_twt - = TargetWindowType_overlapped); - /// move the mouse cursor - void funcMouseMove(FunctionParam *i_param, int i_dx, int i_dy); - /// send a mouse-wheel-message to Windows - void funcMouseWheel(FunctionParam *i_param, int i_delta); - /// convert the contents of the Clipboard to upper case or lower case - void funcClipboardChangeCase(FunctionParam *i_param, - BooleanType i_doesConvertToUpperCase); - /// convert the contents of the Clipboard to upper case - void funcClipboardUpcaseWord(FunctionParam *i_param); - /// convert the contents of the Clipboard to lower case - void funcClipboardDowncaseWord(FunctionParam *i_param); - /// set the contents of the Clipboard to the string - void funcClipboardCopy(FunctionParam *i_param, const StrExprArg &i_text); - /// - void funcEmacsEditKillLinePred(FunctionParam *i_param, - const KeySeq *i_keySeq1, - const KeySeq *i_keySeq2); - /// - void funcEmacsEditKillLineFunc(FunctionParam *i_param); - /// clear log - void funcLogClear(FunctionParam *i_param); - /// recenter - void funcRecenter(FunctionParam *i_param); - /// Direct SSTP - void funcDirectSSTP(FunctionParam *i_param, - const tregex &i_name, - const StrExprArg &i_protocol, - const std::list &i_headers); - /// PlugIn - void funcPlugIn(FunctionParam *i_param, - const StrExprArg &i_dllName, - const StrExprArg &i_funcName = StrExprArg(), - const StrExprArg &i_funcParam = StrExprArg(), - BooleanType i_doesCreateThread = BooleanType_false); - /// set IME open status - void funcSetImeStatus(FunctionParam *i_param, ToggleType i_toggle = ToggleType_toggle); - /// set string to IME - void funcSetImeString(FunctionParam *i_param, const StrExprArg &i_data); - /// enter to mouse event hook mode - void funcMouseHook(FunctionParam *i_param, MouseHookType i_hookType, int i_hookParam); - - // END OF FUNCTION DEFINITION + // BEGINING OF FUNCTION DEFINITION + /// send a default key to Windows + void funcDefault(FunctionParam *i_param); + /// use a corresponding key of a parent keymap + void funcKeymapParent(FunctionParam *i_param); + /// use a corresponding key of a current window + void funcKeymapWindow(FunctionParam *i_param); + /// use a corresponding key of the previous prefixed keymap + void funcKeymapPrevPrefix(FunctionParam *i_param, int i_previous); + /// use a corresponding key of an other window class, or use a default key + void funcOtherWindowClass(FunctionParam *i_param); + /// prefix key + void funcPrefix(FunctionParam *i_param, const Keymap *i_keymap, + BooleanType i_doesIgnoreModifiers = BooleanType_true); + /// other keymap's key + void funcKeymap(FunctionParam *i_param, const Keymap *i_keymap); + /// sync + void funcSync(FunctionParam *i_param); + /// toggle lock + void funcToggle(FunctionParam *i_param, ModifierLockType i_lock, + ToggleType i_toggle = ToggleType_toggle); + /// edit next user input key's modifier + void funcEditNextModifier(FunctionParam *i_param, + const Modifier &i_modifier); + /// variable + void funcVariable(FunctionParam *i_param, int i_mag, int i_inc); + /// repeat N times + void funcRepeat(FunctionParam *i_param, const KeySeq *i_keySeq, + int i_max = 10); + /// undefined (bell) + void funcUndefined(FunctionParam *i_param); + /// ignore + void funcIgnore(FunctionParam *i_param); + /// post message + void funcPostMessage(FunctionParam *i_param, ToWindowType i_window, + UINT i_message, WPARAM i_wParam, LPARAM i_lParam); + /// ShellExecute + void funcShellExecute(FunctionParam *i_param, const StrExprArg &i_operation, + const StrExprArg &i_file, const StrExprArg &i_parameters, + const StrExprArg &i_directory, + ShowCommandType i_showCommand); + /// SetForegroundWindow + void funcSetForegroundWindow(FunctionParam *i_param, + const tregex &i_windowClassName, + LogicalOperatorType i_logicalOp + = LogicalOperatorType_and, + const tregex &i_windowTitleName + = tregex(_T(".*"))); + /// load setting + void funcLoadSetting(FunctionParam *i_param, + const StrExprArg &i_name = StrExprArg()); + /// virtual key + void funcVK(FunctionParam *i_param, VKey i_vkey); + /// wait + void funcWait(FunctionParam *i_param, int i_milliSecond); + /// investigate WM_COMMAND, WM_SYSCOMMAND + void funcInvestigateCommand(FunctionParam *i_param); + /// show mayu dialog box + void funcMayuDialog(FunctionParam *i_param, MayuDialogType i_dialog, + ShowCommandType i_showCommand); + /// describe bindings + void funcDescribeBindings(FunctionParam *i_param); + /// show help message + void funcHelpMessage(FunctionParam *i_param, + const StrExprArg &i_title = StrExprArg(), + const StrExprArg &i_message = StrExprArg()); + /// show variable + void funcHelpVariable(FunctionParam *i_param, const StrExprArg &i_title); + /// raise window + void funcWindowRaise(FunctionParam *i_param, + TargetWindowType i_twt = TargetWindowType_overlapped); + /// lower window + void funcWindowLower(FunctionParam *i_param, + TargetWindowType i_twt = TargetWindowType_overlapped); + /// minimize window + void funcWindowMinimize(FunctionParam *i_param, TargetWindowType i_twt + = TargetWindowType_overlapped); + /// maximize window + void funcWindowMaximize(FunctionParam *i_param, TargetWindowType i_twt + = TargetWindowType_overlapped); + /// maximize window horizontally + void funcWindowHMaximize(FunctionParam *i_param, TargetWindowType i_twt + = TargetWindowType_overlapped); + /// maximize window virtically + void funcWindowVMaximize(FunctionParam *i_param, TargetWindowType i_twt + = TargetWindowType_overlapped); + /// maximize window virtically or horizontally + void funcWindowHVMaximize(FunctionParam *i_param, BooleanType i_isHorizontal, + TargetWindowType i_twt + = TargetWindowType_overlapped); + /// move window + void funcWindowMove(FunctionParam *i_param, int i_dx, int i_dy, + TargetWindowType i_twt + = TargetWindowType_overlapped); + /// move window to ... + void funcWindowMoveTo(FunctionParam *i_param, GravityType i_gravityType, + int i_dx, int i_dy, TargetWindowType i_twt + = TargetWindowType_overlapped); + /// move window visibly + void funcWindowMoveVisibly(FunctionParam *i_param, + TargetWindowType i_twt + = TargetWindowType_overlapped); + /// move window to other monitor + void funcWindowMonitorTo(FunctionParam *i_param, + WindowMonitorFromType i_fromType, int i_monitor, + BooleanType i_adjustPos = BooleanType_true, + BooleanType i_adjustSize = BooleanType_false); + /// move window to other monitor + void funcWindowMonitor(FunctionParam *i_param, int i_monitor, + BooleanType i_adjustPos = BooleanType_true, + BooleanType i_adjustSize = BooleanType_false); + /// + void funcWindowClingToLeft(FunctionParam *i_param, + TargetWindowType i_twt + = TargetWindowType_overlapped); + /// + void funcWindowClingToRight(FunctionParam *i_param, + TargetWindowType i_twt + = TargetWindowType_overlapped); + /// + void funcWindowClingToTop(FunctionParam *i_param, + TargetWindowType i_twt + = TargetWindowType_overlapped); + /// + void funcWindowClingToBottom(FunctionParam *i_param, + TargetWindowType i_twt + = TargetWindowType_overlapped); + /// close window + void funcWindowClose(FunctionParam *i_param, + TargetWindowType i_twt = TargetWindowType_overlapped); + /// toggle top-most flag of the window + void funcWindowToggleTopMost(FunctionParam *i_param); + /// identify the window + void funcWindowIdentify(FunctionParam *i_param); + /// set alpha blending parameter to the window + void funcWindowSetAlpha(FunctionParam *i_param, int i_alpha); + /// redraw the window + void funcWindowRedraw(FunctionParam *i_param); + /// resize window to + void funcWindowResizeTo(FunctionParam *i_param, int i_width, int i_height, + TargetWindowType i_twt + = TargetWindowType_overlapped); + /// move the mouse cursor + void funcMouseMove(FunctionParam *i_param, int i_dx, int i_dy); + /// send a mouse-wheel-message to Windows + void funcMouseWheel(FunctionParam *i_param, int i_delta); + /// convert the contents of the Clipboard to upper case or lower case + void funcClipboardChangeCase(FunctionParam *i_param, + BooleanType i_doesConvertToUpperCase); + /// convert the contents of the Clipboard to upper case + void funcClipboardUpcaseWord(FunctionParam *i_param); + /// convert the contents of the Clipboard to lower case + void funcClipboardDowncaseWord(FunctionParam *i_param); + /// set the contents of the Clipboard to the string + void funcClipboardCopy(FunctionParam *i_param, const StrExprArg &i_text); + /// + void funcEmacsEditKillLinePred(FunctionParam *i_param, + const KeySeq *i_keySeq1, + const KeySeq *i_keySeq2); + /// + void funcEmacsEditKillLineFunc(FunctionParam *i_param); + /// clear log + void funcLogClear(FunctionParam *i_param); + /// recenter + void funcRecenter(FunctionParam *i_param); + /// Direct SSTP + void funcDirectSSTP(FunctionParam *i_param, + const tregex &i_name, + const StrExprArg &i_protocol, + const std::list &i_headers); + /// PlugIn + void funcPlugIn(FunctionParam *i_param, + const StrExprArg &i_dllName, + const StrExprArg &i_funcName = StrExprArg(), + const StrExprArg &i_funcParam = StrExprArg(), + BooleanType i_doesCreateThread = BooleanType_false); + /// set IME open status + void funcSetImeStatus(FunctionParam *i_param, ToggleType i_toggle = ToggleType_toggle); + /// set string to IME + void funcSetImeString(FunctionParam *i_param, const StrExprArg &i_data); + /// enter to mouse event hook mode + void funcMouseHook(FunctionParam *i_param, MouseHookType i_hookType, int i_hookParam); + + // END OF FUNCTION DEFINITION # define FUNCTION_FRIEND # include "functions.h" # undef FUNCTION_FRIEND - + public: - /// - Engine(tomsgstream &i_log); - /// - ~Engine(); - - /// start/stop keyboard handler thread - void start(); - /// - void stop(); - - /// pause keyboard handler thread and close device - bool pause(); - - /// resume keyboard handler thread and re-open device - bool resume(); - - /// do some procedure before quit which must be done synchronously - /// (i.e. not on WM_QUIT) - bool prepairQuit(); - - /// logging mode - void enableLogMode(bool i_isLogMode = true) { m_isLogMode = i_isLogMode; } - /// - void disableLogMode() { m_isLogMode = false; } - - /// enable/disable engine - void enable(bool i_isEnabled = true) { m_isEnabled = i_isEnabled; } - /// - void disable() { m_isEnabled = false; } - /// - bool getIsEnabled() const { return m_isEnabled; } - - /// associated window - void setAssociatedWndow(HWND i_hwnd) { m_hwndAssocWindow = i_hwnd; } - - /// associated window - HWND getAssociatedWndow() const { return m_hwndAssocWindow; } - - /// setting - bool setSetting(Setting *i_setting); - - /// focus - bool setFocus(HWND i_hwndFocus, DWORD i_threadId, - const tstringi &i_className, - const tstringi &i_titleName, bool i_isConsole); - - /// lock state - bool setLockState(bool i_isNumLockToggled, bool i_isCapsLockToggled, - bool i_isScrollLockToggled, bool i_isKanaLockToggled, - bool i_isImeLockToggled, bool i_isImeCompToggled); - - /// show - void checkShow(HWND i_hwnd); - bool setShow(bool i_isMaximized, bool i_isMinimized, bool i_isMDI); - - /// sync - bool syncNotify(); - - /// thread detach notify - bool threadDetachNotify(DWORD i_threadId); - - /// shell execute - void shellExecute(); - - /// get help message - void getHelpMessages(tstring *o_helpMessage, tstring *o_helpTitle); - - /// command notify - void commandNotify(HWND i_hwnd, UINT i_message, WPARAM i_wParam, - LPARAM i_lParam); - - /// get current window class name - const tstringi &getCurrentWindowClassName() const { return m_currentFocusOfThread->m_className; } - - /// get current window title name - const tstringi &getCurrentWindowTitleName() const { return m_currentFocusOfThread->m_titleName; } - - /// get mayud version - const tstring &getMayudVersion() const { return m_mayudVersion; } + /// + Engine(tomsgstream &i_log); + /// + ~Engine(); + + /// start/stop keyboard handler thread + void start(); + /// + void stop(); + + /// pause keyboard handler thread and close device + bool pause(); + + /// resume keyboard handler thread and re-open device + bool resume(); + + /// do some procedure before quit which must be done synchronously + /// (i.e. not on WM_QUIT) + bool prepairQuit(); + + /// logging mode + void enableLogMode(bool i_isLogMode = true) { + m_isLogMode = i_isLogMode; + } + /// + void disableLogMode() { + m_isLogMode = false; + } + + /// enable/disable engine + void enable(bool i_isEnabled = true) { + m_isEnabled = i_isEnabled; + } + /// + void disable() { + m_isEnabled = false; + } + /// + bool getIsEnabled() const { + return m_isEnabled; + } + + /// associated window + void setAssociatedWndow(HWND i_hwnd) { + m_hwndAssocWindow = i_hwnd; + } + + /// associated window + HWND getAssociatedWndow() const { + return m_hwndAssocWindow; + } + + /// setting + bool setSetting(Setting *i_setting); + + /// focus + bool setFocus(HWND i_hwndFocus, DWORD i_threadId, + const tstringi &i_className, + const tstringi &i_titleName, bool i_isConsole); + + /// lock state + bool setLockState(bool i_isNumLockToggled, bool i_isCapsLockToggled, + bool i_isScrollLockToggled, bool i_isKanaLockToggled, + bool i_isImeLockToggled, bool i_isImeCompToggled); + + /// show + void checkShow(HWND i_hwnd); + bool setShow(bool i_isMaximized, bool i_isMinimized, bool i_isMDI); + + /// sync + bool syncNotify(); + + /// thread detach notify + bool threadDetachNotify(DWORD i_threadId); + + /// shell execute + void shellExecute(); + + /// get help message + void getHelpMessages(tstring *o_helpMessage, tstring *o_helpTitle); + + /// command notify + void commandNotify(HWND i_hwnd, UINT i_message, WPARAM i_wParam, + LPARAM i_lParam); + + /// get current window class name + const tstringi &getCurrentWindowClassName() const { + return m_currentFocusOfThread->m_className; + } + + /// get current window title name + const tstringi &getCurrentWindowTitleName() const { + return m_currentFocusOfThread->m_titleName; + } + + /// get mayud version + const tstring &getMayudVersion() const { + return m_mayudVersion; + } }; @@ -587,11 +604,11 @@ public: class FunctionParam { public: - bool m_isPressed; /// is key pressed ? - HWND m_hwnd; /// - Engine::Current m_c; /// new context - bool m_doesNeedEndl; /// need endl ? - const ActionFunction *m_af; /// + bool m_isPressed; /// is key pressed ? + HWND m_hwnd; /// + Engine::Current m_c; /// new context + bool m_doesNeedEndl; /// need endl ? + const ActionFunction *m_af; /// }; diff --git a/errormessage.h b/errormessage.h index d70f87b..a547d98 100644 --- a/errormessage.h +++ b/errormessage.h @@ -12,61 +12,58 @@ /// class ErrorMessage { - tstringstream m_ost; /// - + tstringstream m_ost; /// + public: - /// - ErrorMessage() { } - /// - ErrorMessage(const ErrorMessage &i_em) { m_ost << i_em.getMessage(); } - - /// get error message - tstring getMessage() const - { - return m_ost.str(); - } - - /// add message - template ErrorMessage &operator<<(const T &i_value) - { - m_ost << i_value; - return *this; - } - - /// ios manipulator - ErrorMessage &operator<<( - std::ios_base &(*i_manip)(std::ios_base&)) - { - m_ost << i_manip; - return *this; - } + /// + ErrorMessage() { } + /// + ErrorMessage(const ErrorMessage &i_em) { + m_ost << i_em.getMessage(); + } + + /// get error message + tstring getMessage() const { + return m_ost.str(); + } + + /// add message + template ErrorMessage &operator<<(const T &i_value) { + m_ost << i_value; + return *this; + } + + /// ios manipulator + ErrorMessage &operator<<( + std::ios_base &(*i_manip)(std::ios_base&)) { + m_ost << i_manip; + return *this; + } #ifdef UNICODE - /// add message - template<> ErrorMessage &operator<<(const std::string &i_value) - { - m_ost << to_wstring(i_value); - return *this; - } - - /// add message - typedef const char *const_char_ptr; - template<> ErrorMessage &operator<<(const const_char_ptr &i_value) - { - m_ost << to_wstring(i_value); - return *this; - } + /// add message + template<> ErrorMessage &operator<<(const std::string &i_value) { + m_ost << to_wstring(i_value); + return *this; + } + + /// add message + typedef const char *const_char_ptr; + template<> ErrorMessage &operator<<(const const_char_ptr &i_value) { + m_ost << to_wstring(i_value); + return *this; + } #endif - - /// stream output - friend tostream &operator<<(tostream &i_ost, const ErrorMessage &i_em); + + /// stream output + friend tostream &operator<<(tostream &i_ost, const ErrorMessage &i_em); }; /// stream output inline tostream &operator<<(tostream &i_ost, const ErrorMessage &i_em) { - return i_ost << i_em.getMessage(); + return i_ost << i_em.getMessage(); } @@ -74,12 +71,11 @@ inline tostream &operator<<(tostream &i_ost, const ErrorMessage &i_em) class WarningMessage : public ErrorMessage { public: - /// add message - template WarningMessage &operator<<(const T &i_value) - { - ErrorMessage::operator<<(i_value); - return *this; - } + /// add message + template WarningMessage &operator<<(const T &i_value) { + ErrorMessage::operator<<(i_value); + return *this; + } }; diff --git a/focus.cpp b/focus.cpp index d59fda9..bf20d3d 100644 --- a/focus.cpp +++ b/focus.cpp @@ -8,63 +8,59 @@ /// static LRESULT CALLBACK WndProc( - HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam) + HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam) { - switch (i_message) - { - case WM_KEYDOWN: - case WM_SYSKEYDOWN: - case WM_KEYUP: - case WM_SYSKEYUP: - SendMessage(GetParent(i_hwnd), WM_APP_notifyVKey, i_wParam, i_lParam); - return 0; - case WM_CHAR: - case WM_DEADCHAR: - return 0; - case WM_LBUTTONDOWN: - { - SetFocus(i_hwnd); - return 0; - } - case WM_SETFOCUS: - { - RECT rc; - GetClientRect(i_hwnd, &rc); - CreateCaret(i_hwnd, reinterpret_cast(NULL), 2, - rcHeight(&rc) / 2); - ShowCaret(i_hwnd); - SetCaretPos(rcWidth(&rc) / 2, rcHeight(&rc) / 4); - SendMessage(GetParent(i_hwnd), WM_APP_notifyFocus, - TRUE, (LPARAM)i_hwnd); - return 0; - } - case WM_KILLFOCUS: - { - HideCaret(i_hwnd); - DestroyCaret(); - SendMessage(GetParent(i_hwnd), WM_APP_notifyFocus, - FALSE, (LPARAM)i_hwnd); - return 0; - } - case WM_GETDLGCODE: - return DLGC_WANTALLKEYS; - } - return DefWindowProc(i_hwnd, i_message, i_wParam, i_lParam); + switch (i_message) { + case WM_KEYDOWN: + case WM_SYSKEYDOWN: + case WM_KEYUP: + case WM_SYSKEYUP: + SendMessage(GetParent(i_hwnd), WM_APP_notifyVKey, i_wParam, i_lParam); + return 0; + case WM_CHAR: + case WM_DEADCHAR: + return 0; + case WM_LBUTTONDOWN: { + SetFocus(i_hwnd); + return 0; + } + case WM_SETFOCUS: { + RECT rc; + GetClientRect(i_hwnd, &rc); + CreateCaret(i_hwnd, reinterpret_cast(NULL), 2, + rcHeight(&rc) / 2); + ShowCaret(i_hwnd); + SetCaretPos(rcWidth(&rc) / 2, rcHeight(&rc) / 4); + SendMessage(GetParent(i_hwnd), WM_APP_notifyFocus, + TRUE, (LPARAM)i_hwnd); + return 0; + } + case WM_KILLFOCUS: { + HideCaret(i_hwnd); + DestroyCaret(); + SendMessage(GetParent(i_hwnd), WM_APP_notifyFocus, + FALSE, (LPARAM)i_hwnd); + return 0; + } + case WM_GETDLGCODE: + return DLGC_WANTALLKEYS; + } + return DefWindowProc(i_hwnd, i_message, i_wParam, i_lParam); } ATOM Register_focus() { - WNDCLASS wc; - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.lpfnWndProc = WndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = g_hInst; - wc.hIcon = NULL; - wc.hCursor = LoadCursor(NULL, IDC_IBEAM); - wc.hbrBackground = reinterpret_cast(COLOR_WINDOW + 1); - wc.lpszMenuName = NULL; - wc.lpszClassName = _T("mayuFocus"); - return RegisterClass(&wc); + WNDCLASS wc; + wc.style = CS_HREDRAW | CS_VREDRAW; + wc.lpfnWndProc = WndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = g_hInst; + wc.hIcon = NULL; + wc.hCursor = LoadCursor(NULL, IDC_IBEAM); + wc.hbrBackground = reinterpret_cast(COLOR_WINDOW + 1); + wc.lpszMenuName = NULL; + wc.lpszClassName = _T("mayuFocus"); + return RegisterClass(&wc); } diff --git a/focus.h b/focus.h index 8c9969f..2c9c9f5 100644 --- a/focus.h +++ b/focus.h @@ -11,10 +11,9 @@ /// extern ATOM Register_focus(); -enum -{ - WM_APP_notifyFocus = WM_APP + 103, - WM_APP_notifyVKey = WM_APP + 104, +enum { + WM_APP_notifyFocus = WM_APP + 103, + WM_APP_notifyVKey = WM_APP + 104, }; diff --git a/function.cpp b/function.cpp index 3136b70..eb86eca 100644 --- a/function.cpp +++ b/function.cpp @@ -25,35 +25,33 @@ template class TypeTable { public: - T m_type; - const _TCHAR *m_name; + T m_type; + const _TCHAR *m_name; }; template static inline bool getTypeName(tstring *o_name, T i_type, - const TypeTable *i_table, size_t i_n) + const TypeTable *i_table, size_t i_n) { - for (size_t i = 0; i < i_n; ++ i) - if (i_table[i].m_type == i_type) - { - *o_name = i_table[i].m_name; - return true; - } - return false; + for (size_t i = 0; i < i_n; ++ i) + if (i_table[i].m_type == i_type) { + *o_name = i_table[i].m_name; + return true; + } + return false; } template static inline bool getTypeValue(T *o_type, const tstringi &i_name, - const TypeTable *i_table, size_t i_n) + const TypeTable *i_table, size_t i_n) { - for (size_t i = 0; i < i_n; ++ i) - if (i_table[i].m_name == i_name) - { - *o_type = i_table[i].m_type; - return true; - } - return false; + for (size_t i = 0; i < i_n; ++ i) + if (i_table[i].m_name == i_name) { + *o_type = i_table[i].m_type; + return true; + } + return false; } @@ -64,23 +62,23 @@ bool getTypeValue(T *o_type, const tstringi &i_name, // stream output tostream &operator<<(tostream &i_ost, VKey i_data) { - if (i_data & VKey_extended) - i_ost << _T("E-"); - if (i_data & VKey_released) - i_ost << _T("U-"); - if (i_data & VKey_pressed) - i_ost << _T("D-"); + if (i_data & VKey_extended) + i_ost << _T("E-"); + if (i_data & VKey_released) + i_ost << _T("U-"); + if (i_data & VKey_pressed) + i_ost << _T("D-"); - u_int8 code = i_data & ~(VKey_extended | VKey_released | VKey_pressed); - const VKeyTable *vkt; - for (vkt = g_vkeyTable; vkt->m_name; ++ vkt) - if (vkt->m_code == code) - break; - if (vkt->m_name) - i_ost << vkt->m_name; - else - i_ost << _T("0x") << std::hex << code << std::dec; - return i_ost; + u_int8 code = i_data & ~(VKey_extended | VKey_released | VKey_pressed); + const VKeyTable *vkt; + for (vkt = g_vkeyTable; vkt->m_name; ++ vkt) + if (vkt->m_code == code) + break; + if (vkt->m_name) + i_ost << vkt->m_name; + else + i_ost << _T("0x") << std::hex << code << std::dec; + return i_ost; } @@ -90,33 +88,32 @@ tostream &operator<<(tostream &i_ost, VKey i_data) // ToWindowType table typedef TypeTable TypeTable_ToWindowType; -static const TypeTable_ToWindowType g_toWindowTypeTable[] = -{ - { ToWindowType_toOverlappedWindow, _T("toOverlappedWindow") }, - { ToWindowType_toMainWindow, _T("toMainWindow") }, - { ToWindowType_toItself, _T("toItself") }, - { ToWindowType_toParentWindow, _T("toParentWindow") }, +static const TypeTable_ToWindowType g_toWindowTypeTable[] = { + { ToWindowType_toOverlappedWindow, _T("toOverlappedWindow") }, + { ToWindowType_toMainWindow, _T("toMainWindow") }, + { ToWindowType_toItself, _T("toItself") }, + { ToWindowType_toParentWindow, _T("toParentWindow") }, }; // stream output tostream &operator<<(tostream &i_ost, ToWindowType i_data) { - tstring name; - if (getTypeName(&name, i_data, - g_toWindowTypeTable, NUMBER_OF(g_toWindowTypeTable))) - i_ost << name; - else - i_ost << static_cast(i_data); - return i_ost; + tstring name; + if (getTypeName(&name, i_data, + g_toWindowTypeTable, NUMBER_OF(g_toWindowTypeTable))) + i_ost << name; + else + i_ost << static_cast(i_data); + return i_ost; } // get value of ToWindowType bool getTypeValue(ToWindowType *o_type, const tstring &i_name) { - return getTypeValue(o_type, i_name, - g_toWindowTypeTable, NUMBER_OF(g_toWindowTypeTable)); + return getTypeValue(o_type, i_name, + g_toWindowTypeTable, NUMBER_OF(g_toWindowTypeTable)); } @@ -126,42 +123,41 @@ bool getTypeValue(ToWindowType *o_type, const tstring &i_name) // GravityType table typedef TypeTable TypeTable_GravityType; -static const TypeTable_GravityType g_gravityTypeTable[] = -{ - { GravityType_C, _T("C") }, - { GravityType_N, _T("N") }, - { GravityType_E, _T("E") }, - { GravityType_W, _T("W") }, - { GravityType_S, _T("S") }, - { GravityType_NW, _T("NW") }, - { GravityType_NW, _T("WN") }, - { GravityType_NE, _T("NE") }, - { GravityType_NE, _T("EN") }, - { GravityType_SW, _T("SW") }, - { GravityType_SW, _T("WS") }, - { GravityType_SE, _T("SE") }, - { GravityType_SE, _T("ES") }, +static const TypeTable_GravityType g_gravityTypeTable[] = { + { GravityType_C, _T("C") }, + { GravityType_N, _T("N") }, + { GravityType_E, _T("E") }, + { GravityType_W, _T("W") }, + { GravityType_S, _T("S") }, + { GravityType_NW, _T("NW") }, + { GravityType_NW, _T("WN") }, + { GravityType_NE, _T("NE") }, + { GravityType_NE, _T("EN") }, + { GravityType_SW, _T("SW") }, + { GravityType_SW, _T("WS") }, + { GravityType_SE, _T("SE") }, + { GravityType_SE, _T("ES") }, }; // stream output tostream &operator<<(tostream &i_ost, GravityType i_data) { - tstring name; - if (getTypeName(&name, i_data, - g_gravityTypeTable, NUMBER_OF(g_gravityTypeTable))) - i_ost << name; - else - i_ost << _T("(GravityType internal error)"); - return i_ost; + tstring name; + if (getTypeName(&name, i_data, + g_gravityTypeTable, NUMBER_OF(g_gravityTypeTable))) + i_ost << name; + else + i_ost << _T("(GravityType internal error)"); + return i_ost; } // get value of GravityType bool getTypeValue(GravityType *o_type, const tstring &i_name) { - return getTypeValue(o_type, i_name, - g_gravityTypeTable, NUMBER_OF(g_gravityTypeTable)); + return getTypeValue(o_type, i_name, + g_gravityTypeTable, NUMBER_OF(g_gravityTypeTable)); } @@ -171,32 +167,31 @@ bool getTypeValue(GravityType *o_type, const tstring &i_name) // MouseHookType table typedef TypeTable TypeTable_MouseHookType; -static const TypeTable_MouseHookType g_mouseHookTypeTable[] = -{ - { MouseHookType_None, _T("None") }, - { MouseHookType_Wheel, _T("Wheel") }, - { MouseHookType_WindowMove, _T("WindowMove") }, +static const TypeTable_MouseHookType g_mouseHookTypeTable[] = { + { MouseHookType_None, _T("None") }, + { MouseHookType_Wheel, _T("Wheel") }, + { MouseHookType_WindowMove, _T("WindowMove") }, }; // stream output tostream &operator<<(tostream &i_ost, MouseHookType i_data) { - tstring name; - if (getTypeName(&name, i_data, - g_mouseHookTypeTable, NUMBER_OF(g_mouseHookTypeTable))) - i_ost << name; - else - i_ost << _T("(MouseHookType internal error)"); - return i_ost; + tstring name; + if (getTypeName(&name, i_data, + g_mouseHookTypeTable, NUMBER_OF(g_mouseHookTypeTable))) + i_ost << name; + else + i_ost << _T("(MouseHookType internal error)"); + return i_ost; } // get value of MouseHookType bool getTypeValue(MouseHookType *o_type, const tstring &i_name) { - return getTypeValue(o_type, i_name, g_mouseHookTypeTable, - NUMBER_OF(g_mouseHookTypeTable)); + return getTypeValue(o_type, i_name, g_mouseHookTypeTable, + NUMBER_OF(g_mouseHookTypeTable)); } @@ -206,31 +201,30 @@ bool getTypeValue(MouseHookType *o_type, const tstring &i_name) // ModifierLockType table typedef TypeTable TypeTable_MayuDialogType; -static const TypeTable_MayuDialogType g_mayuDialogTypeTable[] = -{ - { MayuDialogType_investigate, _T("investigate") }, - { MayuDialogType_log, _T("log") }, +static const TypeTable_MayuDialogType g_mayuDialogTypeTable[] = { + { MayuDialogType_investigate, _T("investigate") }, + { MayuDialogType_log, _T("log") }, }; // stream output tostream &operator<<(tostream &i_ost, MayuDialogType i_data) { - tstring name; - if (getTypeName(&name, i_data, - g_mayuDialogTypeTable, NUMBER_OF(g_mayuDialogTypeTable))) - i_ost << name; - else - i_ost << _T("(MayuDialogType internal error)"); - return i_ost; + tstring name; + if (getTypeName(&name, i_data, + g_mayuDialogTypeTable, NUMBER_OF(g_mayuDialogTypeTable))) + i_ost << name; + else + i_ost << _T("(MayuDialogType internal error)"); + return i_ost; } // get value of MayuDialogType bool getTypeValue(MayuDialogType *o_type, const tstring &i_name) { - return getTypeValue(o_type, i_name, g_mayuDialogTypeTable, - NUMBER_OF(g_mayuDialogTypeTable)); + return getTypeValue(o_type, i_name, g_mayuDialogTypeTable, + NUMBER_OF(g_mayuDialogTypeTable)); } @@ -240,35 +234,34 @@ bool getTypeValue(MayuDialogType *o_type, const tstring &i_name) // ToggleType table typedef TypeTable TypeTable_ToggleType; -static const TypeTable_ToggleType g_toggleType[] = -{ - { ToggleType_toggle, _T("toggle") }, - { ToggleType_off, _T("off") }, - { ToggleType_off, _T("false") }, - { ToggleType_off, _T("released") }, - { ToggleType_on, _T("on") }, - { ToggleType_on, _T("true") }, - { ToggleType_on, _T("pressed") }, +static const TypeTable_ToggleType g_toggleType[] = { + { ToggleType_toggle, _T("toggle") }, + { ToggleType_off, _T("off") }, + { ToggleType_off, _T("false") }, + { ToggleType_off, _T("released") }, + { ToggleType_on, _T("on") }, + { ToggleType_on, _T("true") }, + { ToggleType_on, _T("pressed") }, }; // stream output tostream &operator<<(tostream &i_ost, ToggleType i_data) { - tstring name; - if (getTypeName(&name, i_data, g_toggleType, NUMBER_OF(g_toggleType))) - i_ost << name; - else - i_ost << _T("(ToggleType internal error)"); - return i_ost; + tstring name; + if (getTypeName(&name, i_data, g_toggleType, NUMBER_OF(g_toggleType))) + i_ost << name; + else + i_ost << _T("(ToggleType internal error)"); + return i_ost; } // get value of ToggleType bool getTypeValue(ToggleType *o_type, const tstring &i_name) { - return getTypeValue(o_type, i_name, g_toggleType, - NUMBER_OF(g_toggleType)); + return getTypeValue(o_type, i_name, g_toggleType, + NUMBER_OF(g_toggleType)); } @@ -278,39 +271,38 @@ bool getTypeValue(ToggleType *o_type, const tstring &i_name) // ModifierLockType table typedef TypeTable TypeTable_ModifierLockType; -static const TypeTable_ModifierLockType g_modifierLockTypeTable[] = -{ - { ModifierLockType_Lock0, _T("lock0") }, - { ModifierLockType_Lock1, _T("lock1") }, - { ModifierLockType_Lock2, _T("lock2") }, - { ModifierLockType_Lock3, _T("lock3") }, - { ModifierLockType_Lock4, _T("lock4") }, - { ModifierLockType_Lock5, _T("lock5") }, - { ModifierLockType_Lock6, _T("lock6") }, - { ModifierLockType_Lock7, _T("lock7") }, - { ModifierLockType_Lock8, _T("lock8") }, - { ModifierLockType_Lock9, _T("lock9") }, +static const TypeTable_ModifierLockType g_modifierLockTypeTable[] = { + { ModifierLockType_Lock0, _T("lock0") }, + { ModifierLockType_Lock1, _T("lock1") }, + { ModifierLockType_Lock2, _T("lock2") }, + { ModifierLockType_Lock3, _T("lock3") }, + { ModifierLockType_Lock4, _T("lock4") }, + { ModifierLockType_Lock5, _T("lock5") }, + { ModifierLockType_Lock6, _T("lock6") }, + { ModifierLockType_Lock7, _T("lock7") }, + { ModifierLockType_Lock8, _T("lock8") }, + { ModifierLockType_Lock9, _T("lock9") }, }; // stream output tostream &operator<<(tostream &i_ost, ModifierLockType i_data) { - tstring name; - if (getTypeName(&name, i_data, - g_modifierLockTypeTable, NUMBER_OF(g_modifierLockTypeTable))) - i_ost << name; - else - i_ost << _T("(ModifierLockType internal error)"); - return i_ost; + tstring name; + if (getTypeName(&name, i_data, + g_modifierLockTypeTable, NUMBER_OF(g_modifierLockTypeTable))) + i_ost << name; + else + i_ost << _T("(ModifierLockType internal error)"); + return i_ost; } // get value of ModifierLockType bool getTypeValue(ModifierLockType *o_type, const tstring &i_name) { - return getTypeValue(o_type, i_name, g_modifierLockTypeTable, - NUMBER_OF(g_modifierLockTypeTable)); + return getTypeValue(o_type, i_name, g_modifierLockTypeTable, + NUMBER_OF(g_modifierLockTypeTable)); } @@ -320,41 +312,40 @@ bool getTypeValue(ModifierLockType *o_type, const tstring &i_name) // ShowCommandType table typedef TypeTable TypeTable_ShowCommandType; -static const TypeTable_ShowCommandType g_showCommandTypeTable[] = -{ - { ShowCommandType_hide, _T("hide") }, - { ShowCommandType_maximize, _T("maximize") }, - { ShowCommandType_minimize, _T("minimize") }, - { ShowCommandType_restore, _T("restore") }, - { ShowCommandType_show, _T("show") }, - { ShowCommandType_showDefault, _T("showDefault") }, - { ShowCommandType_showMaximized, _T("showMaximized") }, - { ShowCommandType_showMinimized, _T("showMinimized") }, - { ShowCommandType_showMinNoActive, _T("showMinNoActive") }, - { ShowCommandType_showNA, _T("showNA") }, - { ShowCommandType_showNoActivate, _T("showNoActivate") }, - { ShowCommandType_showNormal, _T("showNormal") }, +static const TypeTable_ShowCommandType g_showCommandTypeTable[] = { + { ShowCommandType_hide, _T("hide") }, + { ShowCommandType_maximize, _T("maximize") }, + { ShowCommandType_minimize, _T("minimize") }, + { ShowCommandType_restore, _T("restore") }, + { ShowCommandType_show, _T("show") }, + { ShowCommandType_showDefault, _T("showDefault") }, + { ShowCommandType_showMaximized, _T("showMaximized") }, + { ShowCommandType_showMinimized, _T("showMinimized") }, + { ShowCommandType_showMinNoActive, _T("showMinNoActive") }, + { ShowCommandType_showNA, _T("showNA") }, + { ShowCommandType_showNoActivate, _T("showNoActivate") }, + { ShowCommandType_showNormal, _T("showNormal") }, }; // stream output tostream &operator<<(tostream &i_ost, ShowCommandType i_data) { - tstring name; - if (getTypeName(&name, i_data, - g_showCommandTypeTable, NUMBER_OF(g_showCommandTypeTable))) - i_ost << name; - else - i_ost << _T("(ShowCommandType internal error)"); - return i_ost; + tstring name; + if (getTypeName(&name, i_data, + g_showCommandTypeTable, NUMBER_OF(g_showCommandTypeTable))) + i_ost << name; + else + i_ost << _T("(ShowCommandType internal error)"); + return i_ost; } // get value of ShowCommandType bool getTypeValue(ShowCommandType *o_type, const tstring &i_name) { - return getTypeValue(o_type, i_name, g_showCommandTypeTable, - NUMBER_OF(g_showCommandTypeTable)); + return getTypeValue(o_type, i_name, g_showCommandTypeTable, + NUMBER_OF(g_showCommandTypeTable)); } @@ -364,31 +355,30 @@ bool getTypeValue(ShowCommandType *o_type, const tstring &i_name) // ModifierLockType table typedef TypeTable TypeTable_TargetWindowType; -static const TypeTable_TargetWindowType g_targetWindowType[] = -{ - { TargetWindowType_overlapped, _T("overlapped") }, - { TargetWindowType_mdi, _T("mdi") }, +static const TypeTable_TargetWindowType g_targetWindowType[] = { + { TargetWindowType_overlapped, _T("overlapped") }, + { TargetWindowType_mdi, _T("mdi") }, }; // stream output tostream &operator<<(tostream &i_ost, TargetWindowType i_data) { - tstring name; - if (getTypeName(&name, i_data, - g_targetWindowType, NUMBER_OF(g_targetWindowType))) - i_ost << name; - else - i_ost << _T("(TargetWindowType internal error)"); - return i_ost; + tstring name; + if (getTypeName(&name, i_data, + g_targetWindowType, NUMBER_OF(g_targetWindowType))) + i_ost << name; + else + i_ost << _T("(TargetWindowType internal error)"); + return i_ost; } // get value of TargetWindowType bool getTypeValue(TargetWindowType *o_type, const tstring &i_name) { - return getTypeValue(o_type, i_name, g_targetWindowType, - NUMBER_OF(g_targetWindowType)); + return getTypeValue(o_type, i_name, g_targetWindowType, + NUMBER_OF(g_targetWindowType)); } @@ -398,30 +388,29 @@ bool getTypeValue(TargetWindowType *o_type, const tstring &i_name) // BooleanType table typedef TypeTable TypeTable_BooleanType; -static const TypeTable_BooleanType g_booleanType[] = -{ - { BooleanType_false, _T("false") }, - { BooleanType_true, _T("true") }, +static const TypeTable_BooleanType g_booleanType[] = { + { BooleanType_false, _T("false") }, + { BooleanType_true, _T("true") }, }; // stream output tostream &operator<<(tostream &i_ost, BooleanType i_data) { - tstring name; - if (getTypeName(&name, i_data, g_booleanType, NUMBER_OF(g_booleanType))) - i_ost << name; - else - i_ost << _T("(BooleanType internal error)"); - return i_ost; + tstring name; + if (getTypeName(&name, i_data, g_booleanType, NUMBER_OF(g_booleanType))) + i_ost << name; + else + i_ost << _T("(BooleanType internal error)"); + return i_ost; } // get value of BooleanType bool getTypeValue(BooleanType *o_type, const tstring &i_name) { - return getTypeValue(o_type, i_name, g_booleanType, - NUMBER_OF(g_booleanType)); + return getTypeValue(o_type, i_name, g_booleanType, + NUMBER_OF(g_booleanType)); } @@ -431,31 +420,30 @@ bool getTypeValue(BooleanType *o_type, const tstring &i_name) // LogicalOperatorType table typedef TypeTable TypeTable_LogicalOperatorType; -static const TypeTable_LogicalOperatorType g_logicalOperatorType[] = -{ - { LogicalOperatorType_or, _T("||") }, - { LogicalOperatorType_and, _T("&&") }, +static const TypeTable_LogicalOperatorType g_logicalOperatorType[] = { + { LogicalOperatorType_or, _T("||") }, + { LogicalOperatorType_and, _T("&&") }, }; // stream output tostream &operator<<(tostream &i_ost, LogicalOperatorType i_data) { - tstring name; - if (getTypeName(&name, i_data, g_logicalOperatorType, - NUMBER_OF(g_logicalOperatorType))) - i_ost << name; - else - i_ost << _T("(LogicalOperatorType internal error)"); - return i_ost; + tstring name; + if (getTypeName(&name, i_data, g_logicalOperatorType, + NUMBER_OF(g_logicalOperatorType))) + i_ost << name; + else + i_ost << _T("(LogicalOperatorType internal error)"); + return i_ost; } // get value of LogicalOperatorType bool getTypeValue(LogicalOperatorType *o_type, const tstring &i_name) { - return getTypeValue(o_type, i_name, g_logicalOperatorType, - NUMBER_OF(g_logicalOperatorType)); + return getTypeValue(o_type, i_name, g_logicalOperatorType, + NUMBER_OF(g_logicalOperatorType)); } @@ -465,31 +453,30 @@ bool getTypeValue(LogicalOperatorType *o_type, const tstring &i_name) // WindowMonitorFromType table typedef TypeTable TypeTable_WindowMonitorFromType; -static const TypeTable_WindowMonitorFromType g_windowMonitorFromType[] = -{ - { WindowMonitorFromType_primary, _T("primary") }, - { WindowMonitorFromType_current, _T("current") }, +static const TypeTable_WindowMonitorFromType g_windowMonitorFromType[] = { + { WindowMonitorFromType_primary, _T("primary") }, + { WindowMonitorFromType_current, _T("current") }, }; // stream output tostream &operator<<(tostream &i_ost, WindowMonitorFromType i_data) { - tstring name; - if(getTypeName(&name, i_data, g_windowMonitorFromType, - NUMBER_OF(g_windowMonitorFromType))) - i_ost << name; - else - i_ost << _T("(WindowMonitorFromType internal error)"); - return i_ost; + tstring name; + if (getTypeName(&name, i_data, g_windowMonitorFromType, + NUMBER_OF(g_windowMonitorFromType))) + i_ost << name; + else + i_ost << _T("(WindowMonitorFromType internal error)"); + return i_ost; } // get value of WindowMonitorFromType bool getTypeValue(WindowMonitorFromType *o_type, const tstring &i_name) { - return getTypeValue(o_type, i_name, g_windowMonitorFromType, - NUMBER_OF(g_windowMonitorFromType)); + return getTypeValue(o_type, i_name, g_windowMonitorFromType, + NUMBER_OF(g_windowMonitorFromType)); } @@ -500,12 +487,11 @@ bool getTypeValue(WindowMonitorFromType *o_type, const tstring &i_name) /// stream output tostream &operator<<(tostream &i_ost, const std::list &i_data) { - for (std::list::const_iterator - i = i_data.begin(); i != i_data.end(); ++ i) - { - i_ost << *i << _T(", "); - } - return i_ost; + for (std::list::const_iterator + i = i_data.begin(); i != i_data.end(); ++ i) { + i_ost << *i << _T(", "); + } + return i_ost; } @@ -522,7 +508,7 @@ FunctionData::~FunctionData() // stream output tostream &operator<<(tostream &i_ost, const FunctionData *i_data) { - return i_data->output(i_ost); + return i_data->output(i_ost); } @@ -534,27 +520,27 @@ tostream &operator<<(tostream &i_ost, const FunctionData *i_data) class FunctionCreator { public: - typedef FunctionData *(*Creator)(); /// - + typedef FunctionData *(*Creator)(); /// + public: - const _TCHAR *m_name; /// function name - Creator m_creator; /// function data creator + const _TCHAR *m_name; /// function name + Creator m_creator; /// function data creator }; // create function FunctionData *createFunctionData(const tstring &i_name) { - static + static #define FUNCTION_CREATOR #include "functions.h" #undef FUNCTION_CREATOR - ; + ; - for (size_t i = 0; i != NUMBER_OF(functionCreators); ++ i) - if (i_name == functionCreators[i].m_name) - return functionCreators[i].m_creator(); - return NULL; + for (size_t i = 0; i != NUMBER_OF(functionCreators); ++ i) + if (i_name == functionCreators[i].m_name) + return functionCreators[i].m_creator(); + return NULL; } @@ -565,87 +551,85 @@ FunctionData *createFunctionData(const tstring &i_name) // bool getSuitableWindow(FunctionParam *i_param, HWND *o_hwnd) { - if (!i_param->m_isPressed) - return false; - *o_hwnd = getToplevelWindow(i_param->m_hwnd, NULL); - if (!*o_hwnd) - return false; - return true; + if (!i_param->m_isPressed) + return false; + *o_hwnd = getToplevelWindow(i_param->m_hwnd, NULL); + if (!*o_hwnd) + return false; + return true; } // bool getSuitableMdiWindow(FunctionParam *i_param, HWND *o_hwnd, - TargetWindowType *io_twt, - RECT *o_rcWindow = NULL, RECT *o_rcParent = NULL) -{ - if (!i_param->m_isPressed) - return false; - bool isMdi = *io_twt == TargetWindowType_mdi; - *o_hwnd = getToplevelWindow(i_param->m_hwnd, &isMdi); - *io_twt = isMdi ? TargetWindowType_mdi : TargetWindowType_overlapped; - if (!*o_hwnd) - return false; - switch (*io_twt) - { - case TargetWindowType_overlapped: - if (o_rcWindow) - GetWindowRect(*o_hwnd, o_rcWindow); - if (o_rcParent) { - HMONITOR hm = monitorFromWindow(i_param->m_hwnd, - MONITOR_DEFAULTTONEAREST); - MONITORINFO mi; - mi.cbSize = sizeof(mi); - getMonitorInfo(hm, &mi); - *o_rcParent = mi.rcWork; - } - break; - case TargetWindowType_mdi: - if (o_rcWindow) - getChildWindowRect(*o_hwnd, o_rcWindow); - if (o_rcParent) - GetClientRect(GetParent(*o_hwnd), o_rcParent); - break; - } - return true; + TargetWindowType *io_twt, + RECT *o_rcWindow = NULL, RECT *o_rcParent = NULL) +{ + if (!i_param->m_isPressed) + return false; + bool isMdi = *io_twt == TargetWindowType_mdi; + *o_hwnd = getToplevelWindow(i_param->m_hwnd, &isMdi); + *io_twt = isMdi ? TargetWindowType_mdi : TargetWindowType_overlapped; + if (!*o_hwnd) + return false; + switch (*io_twt) { + case TargetWindowType_overlapped: + if (o_rcWindow) + GetWindowRect(*o_hwnd, o_rcWindow); + if (o_rcParent) { + HMONITOR hm = monitorFromWindow(i_param->m_hwnd, + MONITOR_DEFAULTTONEAREST); + MONITORINFO mi; + mi.cbSize = sizeof(mi); + getMonitorInfo(hm, &mi); + *o_rcParent = mi.rcWork; + } + break; + case TargetWindowType_mdi: + if (o_rcWindow) + getChildWindowRect(*o_hwnd, o_rcWindow); + if (o_rcParent) + GetClientRect(GetParent(*o_hwnd), o_rcParent); + break; + } + return true; } // get clipboard text (you must call closeClopboard()) static const _TCHAR *getTextFromClipboard(HGLOBAL *o_hdata) { - *o_hdata = NULL; - - if (!OpenClipboard(NULL)) - return NULL; + *o_hdata = NULL; + + if (!OpenClipboard(NULL)) + return NULL; #ifdef UNICODE - *o_hdata = GetClipboardData(CF_UNICODETEXT); + *o_hdata = GetClipboardData(CF_UNICODETEXT); #else - *o_hdata = GetClipboardData(CF_TEXT); + *o_hdata = GetClipboardData(CF_TEXT); #endif - if (!*o_hdata) - return NULL; - - _TCHAR *data = reinterpret_cast<_TCHAR *>(GlobalLock(*o_hdata)); - if (!data) - return NULL; - return data; + if (!*o_hdata) + return NULL; + + _TCHAR *data = reinterpret_cast<_TCHAR *>(GlobalLock(*o_hdata)); + if (!data) + return NULL; + return data; } // close clipboard that opend by getTextFromClipboard() static void closeClipboard(HGLOBAL i_hdata, HGLOBAL i_hdataNew = NULL) { - if (i_hdata) - GlobalUnlock(i_hdata); - if (i_hdataNew) - { - EmptyClipboard(); + if (i_hdata) + GlobalUnlock(i_hdata); + if (i_hdataNew) { + EmptyClipboard(); #ifdef UNICODE - SetClipboardData(CF_UNICODETEXT, i_hdataNew); + SetClipboardData(CF_UNICODETEXT, i_hdataNew); #else - SetClipboardData(CF_TEXT, i_hdataNew); + SetClipboardData(CF_TEXT, i_hdataNew); #endif - } - CloseClipboard(); + } + CloseClipboard(); } @@ -654,83 +638,76 @@ static void closeClipboard(HGLOBAL i_hdata, HGLOBAL i_hdataNew = NULL) // at that time, confirm if it is the result of the previous kill-line void Engine::EmacsEditKillLine::func() { - if (!m_buf.empty()) - { - HGLOBAL g; - const _TCHAR *text = getTextFromClipboard(&g); - if (text == NULL || m_buf != text) - reset(); - closeClipboard(g); - } - if (OpenClipboard(NULL)) - { - EmptyClipboard(); - CloseClipboard(); - } + if (!m_buf.empty()) { + HGLOBAL g; + const _TCHAR *text = getTextFromClipboard(&g); + if (text == NULL || m_buf != text) + reset(); + closeClipboard(g); + } + if (OpenClipboard(NULL)) { + EmptyClipboard(); + CloseClipboard(); + } } /** if the text of the clipboard is @doc
-1: EDIT Control (at EOL C-K): ""            => buf + "\r\n", Delete   
-0: EDIT Control (other  C-K): "(.+)"        => buf + "\1"             
-0: IE FORM TEXTAREA (at EOL C-K): "\r\n"    => buf + "\r\n"           
+1: EDIT Control (at EOL C-K): ""            => buf + "\r\n", Delete
+0: EDIT Control (other  C-K): "(.+)"        => buf + "\1"
+0: IE FORM TEXTAREA (at EOL C-K): "\r\n"    => buf + "\r\n"
 2: IE FORM TEXTAREA (other C-K): "(.+)\r\n" => buf + "\1", Return Left
 ^retval
 
*/ HGLOBAL Engine::EmacsEditKillLine::makeNewKillLineBuf( - const _TCHAR *i_data, int *o_retval) -{ - size_t len = m_buf.size(); - len += _tcslen(i_data) + 3; - - HGLOBAL hdata = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, - len * sizeof(_TCHAR)); - if (!hdata) - return NULL; - _TCHAR *dataNew = reinterpret_cast<_TCHAR *>(GlobalLock(hdata)); - *dataNew = _T('\0'); - if (!m_buf.empty()) - _tcscpy(dataNew, m_buf.c_str()); - - len = _tcslen(i_data); - if (3 <= len && - i_data[len - 2] == _T('\r') && i_data[len - 1] == _T('\n')) - { - _tcscat(dataNew, i_data); - len = _tcslen(dataNew); - dataNew[len - 2] = _T('\0'); // chomp - *o_retval = 2; - } - else if (len == 0) - { - _tcscat(dataNew, _T("\r\n")); - *o_retval = 1; - } - else - { - _tcscat(dataNew, i_data); - *o_retval = 0; - } - - m_buf = dataNew; - - GlobalUnlock(hdata); - return hdata; + const _TCHAR *i_data, int *o_retval) +{ + size_t len = m_buf.size(); + len += _tcslen(i_data) + 3; + + HGLOBAL hdata = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, + len * sizeof(_TCHAR)); + if (!hdata) + return NULL; + _TCHAR *dataNew = reinterpret_cast<_TCHAR *>(GlobalLock(hdata)); + *dataNew = _T('\0'); + if (!m_buf.empty()) + _tcscpy(dataNew, m_buf.c_str()); + + len = _tcslen(i_data); + if (3 <= len && + i_data[len - 2] == _T('\r') && i_data[len - 1] == _T('\n')) { + _tcscat(dataNew, i_data); + len = _tcslen(dataNew); + dataNew[len - 2] = _T('\0'); // chomp + *o_retval = 2; + } else if (len == 0) { + _tcscat(dataNew, _T("\r\n")); + *o_retval = 1; + } else { + _tcscat(dataNew, i_data); + *o_retval = 0; + } + + m_buf = dataNew; + + GlobalUnlock(hdata); + return hdata; } // EmacsEditKillLinePred int Engine::EmacsEditKillLine::pred() { - HGLOBAL g; - const _TCHAR *text = getTextFromClipboard(&g); - int retval; - HGLOBAL hdata = makeNewKillLineBuf(text ? text : _T(""), &retval); - closeClipboard(g, hdata); - return retval; + HGLOBAL g; + const _TCHAR *text = getTextFromClipboard(&g); + int retval; + HGLOBAL hdata = makeNewKillLineBuf(text ? text : _T(""), &retval); + closeClipboard(g, hdata); + return retval; } @@ -741,395 +718,377 @@ int Engine::EmacsEditKillLine::pred() // send a default key to Windows void Engine::funcDefault(FunctionParam *i_param) { - { - Acquire a(&m_log, 1); - m_log << std::endl; - i_param->m_doesNeedEndl = false; - } - if (i_param->m_isPressed) - generateModifierEvents(i_param->m_c.m_mkey.m_modifier); - generateKeyEvent(i_param->m_c.m_mkey.m_key, i_param->m_isPressed, true); + { + Acquire a(&m_log, 1); + m_log << std::endl; + i_param->m_doesNeedEndl = false; + } + if (i_param->m_isPressed) + generateModifierEvents(i_param->m_c.m_mkey.m_modifier); + generateKeyEvent(i_param->m_c.m_mkey.m_key, i_param->m_isPressed, true); } // use a corresponding key of a parent keymap void Engine::funcKeymapParent(FunctionParam *i_param) { - Current c(i_param->m_c); - c.m_keymap = c.m_keymap->getParentKeymap(); - if (!c.m_keymap) - { - funcDefault(i_param); - return; - } - - { - Acquire a(&m_log, 1); - m_log << _T("(") << c.m_keymap->getName() << _T(")") << std::endl; - } - i_param->m_doesNeedEndl = false; - generateKeyboardEvents(c); + Current c(i_param->m_c); + c.m_keymap = c.m_keymap->getParentKeymap(); + if (!c.m_keymap) { + funcDefault(i_param); + return; + } + + { + Acquire a(&m_log, 1); + m_log << _T("(") << c.m_keymap->getName() << _T(")") << std::endl; + } + i_param->m_doesNeedEndl = false; + generateKeyboardEvents(c); } // use a corresponding key of a current window void Engine::funcKeymapWindow(FunctionParam *i_param) { - Current c(i_param->m_c); - c.m_keymap = m_currentFocusOfThread->m_keymaps.front(); - c.m_i = m_currentFocusOfThread->m_keymaps.begin(); - generateKeyboardEvents(c); + Current c(i_param->m_c); + c.m_keymap = m_currentFocusOfThread->m_keymaps.front(); + c.m_i = m_currentFocusOfThread->m_keymaps.begin(); + generateKeyboardEvents(c); } // use a corresponding key of the previous prefixed keymap void Engine::funcKeymapPrevPrefix(FunctionParam *i_param, int i_previous) { - Current c(i_param->m_c); - if (0 < i_previous && 0 <= m_keymapPrefixHistory.size() - i_previous) - { - int n = i_previous - 1; - KeymapPtrList::reverse_iterator i = m_keymapPrefixHistory.rbegin(); - while (0 < n && i != m_keymapPrefixHistory.rend()) - --n, ++i; - c.m_keymap = *i; - generateKeyboardEvents(c); - } + Current c(i_param->m_c); + if (0 < i_previous && 0 <= m_keymapPrefixHistory.size() - i_previous) { + int n = i_previous - 1; + KeymapPtrList::reverse_iterator i = m_keymapPrefixHistory.rbegin(); + while (0 < n && i != m_keymapPrefixHistory.rend()) + --n, ++i; + c.m_keymap = *i; + generateKeyboardEvents(c); + } } // use a corresponding key of an other window class, or use a default key void Engine::funcOtherWindowClass(FunctionParam *i_param) { - Current c(i_param->m_c); - ++ c.m_i; - if (c.m_i == m_currentFocusOfThread->m_keymaps.end()) - { - funcDefault(i_param); - return; - } - - c.m_keymap = *c.m_i; - { - Acquire a(&m_log, 1); - m_log << _T("(") << c.m_keymap->getName() << _T(")") << std::endl; - } - i_param->m_doesNeedEndl = false; - generateKeyboardEvents(c); + Current c(i_param->m_c); + ++ c.m_i; + if (c.m_i == m_currentFocusOfThread->m_keymaps.end()) { + funcDefault(i_param); + return; + } + + c.m_keymap = *c.m_i; + { + Acquire a(&m_log, 1); + m_log << _T("(") << c.m_keymap->getName() << _T(")") << std::endl; + } + i_param->m_doesNeedEndl = false; + generateKeyboardEvents(c); } // prefix key void Engine::funcPrefix(FunctionParam *i_param, const Keymap *i_keymap, - BooleanType i_doesIgnoreModifiers) -{ - if (!i_param->m_isPressed) - return; - - setCurrentKeymap(i_keymap, true); - - // generate prefixed event - generateEvents(i_param->m_c, m_currentKeymap, &Event::prefixed); - - m_isPrefix = true; - m_doesEditNextModifier = false; - m_doesIgnoreModifierForPrefix = !!i_doesIgnoreModifiers; - - { - Acquire a(&m_log, 1); - m_log << _T("(") << i_keymap->getName() << _T(", ") - << (i_doesIgnoreModifiers ? _T("true") : _T("false")) << _T(")"); - } + BooleanType i_doesIgnoreModifiers) +{ + if (!i_param->m_isPressed) + return; + + setCurrentKeymap(i_keymap, true); + + // generate prefixed event + generateEvents(i_param->m_c, m_currentKeymap, &Event::prefixed); + + m_isPrefix = true; + m_doesEditNextModifier = false; + m_doesIgnoreModifierForPrefix = !!i_doesIgnoreModifiers; + + { + Acquire a(&m_log, 1); + m_log << _T("(") << i_keymap->getName() << _T(", ") + << (i_doesIgnoreModifiers ? _T("true") : _T("false")) << _T(")"); + } } // other keymap's key void Engine::funcKeymap(FunctionParam *i_param, const Keymap *i_keymap) { - Current c(i_param->m_c); - c.m_keymap = i_keymap; - { - Acquire a(&m_log, 1); - m_log << _T("(") << c.m_keymap->getName() << _T(")") << std::endl; - i_param->m_doesNeedEndl = false; - } - generateKeyboardEvents(c); + Current c(i_param->m_c); + c.m_keymap = i_keymap; + { + Acquire a(&m_log, 1); + m_log << _T("(") << c.m_keymap->getName() << _T(")") << std::endl; + i_param->m_doesNeedEndl = false; + } + generateKeyboardEvents(c); } // sync void Engine::funcSync(FunctionParam *i_param) { - if (i_param->m_isPressed) - generateModifierEvents(i_param->m_af->m_modifier); - if (!i_param->m_isPressed || m_currentFocusOfThread->m_isConsole) - return; - - Key *sync = m_setting->m_keyboard.getSyncKey(); - if (sync->getScanCodesSize() == 0) - return; - const ScanCode *sc = sync->getScanCodes(); - - // set variables exported from mayu.dll - g_hookData->m_syncKey = sc->m_scan; - g_hookData->m_syncKeyIsExtended = !!(sc->m_flags & ScanCode::E0E1); - m_isSynchronizing = true; - generateKeyEvent(sync, false, false); - - m_cs.release(); - DWORD r = WaitForSingleObject(m_eSync, 5000); - if (r == WAIT_TIMEOUT) - { - Acquire a(&m_log, 0); - m_log << _T(" *FAILED*") << std::endl; - } - m_cs.acquire(); - m_isSynchronizing = false; + if (i_param->m_isPressed) + generateModifierEvents(i_param->m_af->m_modifier); + if (!i_param->m_isPressed || m_currentFocusOfThread->m_isConsole) + return; + + Key *sync = m_setting->m_keyboard.getSyncKey(); + if (sync->getScanCodesSize() == 0) + return; + const ScanCode *sc = sync->getScanCodes(); + + // set variables exported from mayu.dll + g_hookData->m_syncKey = sc->m_scan; + g_hookData->m_syncKeyIsExtended = !!(sc->m_flags & ScanCode::E0E1); + m_isSynchronizing = true; + generateKeyEvent(sync, false, false); + + m_cs.release(); + DWORD r = WaitForSingleObject(m_eSync, 5000); + if (r == WAIT_TIMEOUT) { + Acquire a(&m_log, 0); + m_log << _T(" *FAILED*") << std::endl; + } + m_cs.acquire(); + m_isSynchronizing = false; } // toggle lock void Engine::funcToggle(FunctionParam *i_param, ModifierLockType i_lock, - ToggleType i_toggle) -{ - if (i_param->m_isPressed) // ignore PRESS - return; - - Modifier::Type mt = static_cast(i_lock); - switch (i_toggle) - { - case ToggleType_toggle: - m_currentLock.press(mt, !m_currentLock.isPressed(mt)); - break; - case ToggleType_off: - m_currentLock.press(mt, false); - break; - case ToggleType_on: - m_currentLock.press(mt, true); - break; - } + ToggleType i_toggle) +{ + if (i_param->m_isPressed) // ignore PRESS + return; + + Modifier::Type mt = static_cast(i_lock); + switch (i_toggle) { + case ToggleType_toggle: + m_currentLock.press(mt, !m_currentLock.isPressed(mt)); + break; + case ToggleType_off: + m_currentLock.press(mt, false); + break; + case ToggleType_on: + m_currentLock.press(mt, true); + break; + } } // edit next user input key's modifier void Engine::funcEditNextModifier(FunctionParam *i_param, - const Modifier &i_modifier) + const Modifier &i_modifier) { - if (!i_param->m_isPressed) - return; - - m_isPrefix = true; - m_doesEditNextModifier = true; - m_doesIgnoreModifierForPrefix = true; - m_modifierForNextKey = i_modifier; + if (!i_param->m_isPressed) + return; + + m_isPrefix = true; + m_doesEditNextModifier = true; + m_doesIgnoreModifierForPrefix = true; + m_modifierForNextKey = i_modifier; } // variable void Engine::funcVariable(FunctionParam *i_param, int i_mag, int i_inc) { - if (!i_param->m_isPressed) - return; - m_variable *= i_mag; - m_variable += i_inc; + if (!i_param->m_isPressed) + return; + m_variable *= i_mag; + m_variable += i_inc; } // repeat N times void Engine::funcRepeat(FunctionParam *i_param, const KeySeq *i_keySeq, - int i_max) + int i_max) { - if (i_param->m_isPressed) - { - int end = MIN(m_variable, i_max); - for (int i = 0; i < end - 1; ++ i) - generateKeySeqEvents(i_param->m_c, i_keySeq, Part_all); - if (0 < end) - generateKeySeqEvents(i_param->m_c, i_keySeq, Part_down); - } - else - generateKeySeqEvents(i_param->m_c, i_keySeq, Part_up); + if (i_param->m_isPressed) { + int end = MIN(m_variable, i_max); + for (int i = 0; i < end - 1; ++ i) + generateKeySeqEvents(i_param->m_c, i_keySeq, Part_all); + if (0 < end) + generateKeySeqEvents(i_param->m_c, i_keySeq, Part_down); + } else + generateKeySeqEvents(i_param->m_c, i_keySeq, Part_up); } // undefined (bell) void Engine::funcUndefined(FunctionParam *i_param) { - if (!i_param->m_isPressed) - return; - MessageBeep(MB_OK); + if (!i_param->m_isPressed) + return; + MessageBeep(MB_OK); } // ignore void Engine::funcIgnore(FunctionParam *) { - // do nothing + // do nothing } // post message void Engine::funcPostMessage(FunctionParam *i_param, ToWindowType i_window, - UINT i_message, WPARAM i_wParam, LPARAM i_lParam) -{ - if (!i_param->m_isPressed) - return; - - int window = static_cast(i_window); - - HWND hwnd = i_param->m_hwnd; - if (0 < window) - { - for (int i = 0; i < window; ++ i) - hwnd = GetParent(hwnd); - } - else if (window == ToWindowType_toMainWindow) - { - while (true) - { - HWND p = GetParent(hwnd); - if (!p) - break; - hwnd = p; - } - } - else if (window == ToWindowType_toOverlappedWindow) - { - while (hwnd) - { + UINT i_message, WPARAM i_wParam, LPARAM i_lParam) +{ + if (!i_param->m_isPressed) + return; + + int window = static_cast(i_window); + + HWND hwnd = i_param->m_hwnd; + if (0 < window) { + for (int i = 0; i < window; ++ i) + hwnd = GetParent(hwnd); + } else if (window == ToWindowType_toMainWindow) { + while (true) { + HWND p = GetParent(hwnd); + if (!p) + break; + hwnd = p; + } + } else if (window == ToWindowType_toOverlappedWindow) { + while (hwnd) { #ifdef MAYU64 - LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE); + LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE); #else - LONG style = GetWindowLong(hwnd, GWL_STYLE); + LONG style = GetWindowLong(hwnd, GWL_STYLE); #endif - if ((style & WS_CHILD) == 0) - break; - hwnd = GetParent(hwnd); - } - } + if ((style & WS_CHILD) == 0) + break; + hwnd = GetParent(hwnd); + } + } - if (hwnd) - PostMessage(hwnd, i_message, i_wParam, i_lParam); + if (hwnd) + PostMessage(hwnd, i_message, i_wParam, i_lParam); } // ShellExecute void Engine::funcShellExecute(FunctionParam *i_param, - const StrExprArg &/*i_operation*/, - const StrExprArg &/*i_file*/, - const StrExprArg &/*i_parameters*/, - const StrExprArg &/*i_directory*/, - ShowCommandType /*i_showCommand*/) + const StrExprArg &/*i_operation*/, + const StrExprArg &/*i_file*/, + const StrExprArg &/*i_parameters*/, + const StrExprArg &/*i_directory*/, + ShowCommandType /*i_showCommand*/) { - if (!i_param->m_isPressed) - return; - m_afShellExecute = i_param->m_af; - PostMessage(m_hwndAssocWindow, - WM_APP_engineNotify, EngineNotify_shellExecute, 0); + if (!i_param->m_isPressed) + return; + m_afShellExecute = i_param->m_af; + PostMessage(m_hwndAssocWindow, + WM_APP_engineNotify, EngineNotify_shellExecute, 0); } // shell execute void Engine::shellExecute() { - Acquire a(&m_cs); - - FunctionData_ShellExecute *fd = - reinterpret_cast( - m_afShellExecute->m_functionData); - - int r = (int)ShellExecute( - NULL, - fd->m_operation.eval().empty() ? _T("open") : fd->m_operation.eval().c_str(), - fd->m_file.eval().empty() ? NULL : fd->m_file.eval().c_str(), - fd->m_parameters.eval().empty() ? NULL : fd->m_parameters.eval().c_str(), - fd->m_directory.eval().empty() ? NULL : fd->m_directory.eval().c_str(), - fd->m_showCommand); - if (32 < r) - return; // success - - typedef TypeTable ErrorTable; - static const ErrorTable errorTable[] = - { - { 0, _T("The operating system is out of memory or resources.") }, - { ERROR_FILE_NOT_FOUND, _T("The specified file was not found.") }, - { ERROR_PATH_NOT_FOUND, _T("The specified path was not found.") }, - { ERROR_BAD_FORMAT, _T("The .exe file is invalid ") - _T("(non-Win32R .exe or error in .exe image).") }, - { SE_ERR_ACCESSDENIED, - _T("The operating system denied access to the specified file.") }, - { SE_ERR_ASSOCINCOMPLETE, - _T("The file name association is incomplete or invalid.") }, - { SE_ERR_DDEBUSY, - _T("The DDE transaction could not be completed ") - _T("because other DDE transactions were being processed. ") }, - { SE_ERR_DDEFAIL, _T("The DDE transaction failed.") }, - { SE_ERR_DDETIMEOUT, _T("The DDE transaction could not be completed ") - _T("because the request timed out.") }, - { SE_ERR_DLLNOTFOUND, - _T("The specified dynamic-link library was not found.") }, - { SE_ERR_FNF, _T("The specified file was not found.") }, - { SE_ERR_NOASSOC, _T("There is no application associated ") - _T("with the given file name extension.") }, - { SE_ERR_OOM, - _T("There was not enough memory to complete the operation.") }, - { SE_ERR_PNF, _T("The specified path was not found.") }, - { SE_ERR_SHARE, _T("A sharing violation occurred.") }, - }; - - tstring errorMessage(_T("Unknown error.")); - getTypeName(&errorMessage, r, errorTable, NUMBER_OF(errorTable)); - - Acquire b(&m_log, 0); - m_log << _T("error: ") << fd << _T(": ") << errorMessage << std::endl; -} - - -struct EnumWindowsForSetForegroundWindowParam -{ - const FunctionData_SetForegroundWindow *m_fd; - HWND m_hwnd; + Acquire a(&m_cs); + + FunctionData_ShellExecute *fd = + reinterpret_cast( + m_afShellExecute->m_functionData); + + int r = (int)ShellExecute( + NULL, + fd->m_operation.eval().empty() ? _T("open") : fd->m_operation.eval().c_str(), + fd->m_file.eval().empty() ? NULL : fd->m_file.eval().c_str(), + fd->m_parameters.eval().empty() ? NULL : fd->m_parameters.eval().c_str(), + fd->m_directory.eval().empty() ? NULL : fd->m_directory.eval().c_str(), + fd->m_showCommand); + if (32 < r) + return; // success + + typedef TypeTable ErrorTable; + static const ErrorTable errorTable[] = { + { 0, _T("The operating system is out of memory or resources.") }, + { ERROR_FILE_NOT_FOUND, _T("The specified file was not found.") }, + { ERROR_PATH_NOT_FOUND, _T("The specified path was not found.") }, + { ERROR_BAD_FORMAT, _T("The .exe file is invalid ") + _T("(non-Win32R .exe or error in .exe image).") }, + { SE_ERR_ACCESSDENIED, + _T("The operating system denied access to the specified file.") }, + { SE_ERR_ASSOCINCOMPLETE, + _T("The file name association is incomplete or invalid.") }, + { SE_ERR_DDEBUSY, + _T("The DDE transaction could not be completed ") + _T("because other DDE transactions were being processed. ") }, + { SE_ERR_DDEFAIL, _T("The DDE transaction failed.") }, + { SE_ERR_DDETIMEOUT, _T("The DDE transaction could not be completed ") + _T("because the request timed out.") }, + { SE_ERR_DLLNOTFOUND, + _T("The specified dynamic-link library was not found.") }, + { SE_ERR_FNF, _T("The specified file was not found.") }, + { SE_ERR_NOASSOC, _T("There is no application associated ") + _T("with the given file name extension.") }, + { SE_ERR_OOM, + _T("There was not enough memory to complete the operation.") }, + { SE_ERR_PNF, _T("The specified path was not found.") }, + { SE_ERR_SHARE, _T("A sharing violation occurred.") }, + }; + + tstring errorMessage(_T("Unknown error.")); + getTypeName(&errorMessage, r, errorTable, NUMBER_OF(errorTable)); + + Acquire b(&m_log, 0); + m_log << _T("error: ") << fd << _T(": ") << errorMessage << std::endl; +} + + +struct EnumWindowsForSetForegroundWindowParam { + const FunctionData_SetForegroundWindow *m_fd; + HWND m_hwnd; public: - EnumWindowsForSetForegroundWindowParam( - const FunctionData_SetForegroundWindow *i_fd) - : m_fd(i_fd), - m_hwnd(NULL) - { - } + EnumWindowsForSetForegroundWindowParam( + const FunctionData_SetForegroundWindow *i_fd) + : m_fd(i_fd), + m_hwnd(NULL) { + } }; /// enum windows for SetForegroundWindow static BOOL CALLBACK enumWindowsForSetForegroundWindow( - HWND i_hwnd, LPARAM i_lParam) -{ - EnumWindowsForSetForegroundWindowParam &ep = - *reinterpret_cast(i_lParam); - - _TCHAR name[GANA_MAX_ATOM_LENGTH]; - if (!GetClassName(i_hwnd, name, NUMBER_OF(name))) - return TRUE; - tsmatch what; - if (!boost::regex_search(tstring(name), what, ep.m_fd->m_windowClassName)) - if (ep.m_fd->m_logicalOp == LogicalOperatorType_and) - return TRUE; // match failed - - if (ep.m_fd->m_logicalOp == LogicalOperatorType_and) - { - if (GetWindowText(i_hwnd, name, NUMBER_OF(name)) == 0) - name[0] = _T('\0'); - if (!boost::regex_search(tstring(name), what, - ep.m_fd->m_windowTitleName)) - return TRUE; // match failed - } + HWND i_hwnd, LPARAM i_lParam) +{ + EnumWindowsForSetForegroundWindowParam &ep = + *reinterpret_cast(i_lParam); + + _TCHAR name[GANA_MAX_ATOM_LENGTH]; + if (!GetClassName(i_hwnd, name, NUMBER_OF(name))) + return TRUE; + tsmatch what; + if (!boost::regex_search(tstring(name), what, ep.m_fd->m_windowClassName)) + if (ep.m_fd->m_logicalOp == LogicalOperatorType_and) + return TRUE; // match failed + + if (ep.m_fd->m_logicalOp == LogicalOperatorType_and) { + if (GetWindowText(i_hwnd, name, NUMBER_OF(name)) == 0) + name[0] = _T('\0'); + if (!boost::regex_search(tstring(name), what, + ep.m_fd->m_windowTitleName)) + return TRUE; // match failed + } - ep.m_hwnd = i_hwnd; - return FALSE; + ep.m_hwnd = i_hwnd; + return FALSE; } /// SetForegroundWindow void Engine::funcSetForegroundWindow(FunctionParam *i_param, const tregex &, - LogicalOperatorType , const tregex &) + LogicalOperatorType , const tregex &) { - if (!i_param->m_isPressed) - return; - EnumWindowsForSetForegroundWindowParam - ep(static_cast( - i_param->m_af->m_functionData)); - EnumWindows(enumWindowsForSetForegroundWindow, - reinterpret_cast(&ep)); - if (ep.m_hwnd) - PostMessage(m_hwndAssocWindow, - WM_APP_engineNotify, EngineNotify_setForegroundWindow, - reinterpret_cast(ep.m_hwnd)); + if (!i_param->m_isPressed) + return; + EnumWindowsForSetForegroundWindowParam + ep(static_cast( + i_param->m_af->m_functionData)); + EnumWindows(enumWindowsForSetForegroundWindow, + reinterpret_cast(&ep)); + if (ep.m_hwnd) + PostMessage(m_hwndAssocWindow, + WM_APP_engineNotify, EngineNotify_setForegroundWindow, + reinterpret_cast(ep.m_hwnd)); } @@ -1137,1215 +1096,1157 @@ void Engine::funcSetForegroundWindow(FunctionParam *i_param, const tregex &, // load setting void Engine::funcLoadSetting(FunctionParam *i_param, const StrExprArg &i_name) { - if (!i_param->m_isPressed) - return; - if (!i_name.eval().empty()) - { - // set MAYU_REGISTRY_ROOT\.mayuIndex which name is same with i_name - Registry reg(MAYU_REGISTRY_ROOT); - - tregex split(_T("^([^;]*);([^;]*);(.*)$")); - tstringi dot_mayu; - for (size_t i = 0; i < MAX_MAYU_REGISTRY_ENTRIES; ++ i) - { - _TCHAR buf[100]; - _sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), i); - if (!reg.read(buf, &dot_mayu)) - break; - - tsmatch what; - if (boost::regex_match(dot_mayu, what, split) && - what.str(1) == i_name.eval()) - { - reg.write(_T(".mayuIndex"), i); - goto success; - } - } - - { - Acquire a(&m_log, 0); - m_log << _T("unknown setting name: ") << i_name; - } - return; - - success: ; - } - PostMessage(m_hwndAssocWindow, - WM_APP_engineNotify, EngineNotify_loadSetting, 0); + if (!i_param->m_isPressed) + return; + if (!i_name.eval().empty()) { + // set MAYU_REGISTRY_ROOT\.mayuIndex which name is same with i_name + Registry reg(MAYU_REGISTRY_ROOT); + + tregex split(_T("^([^;]*);([^;]*);(.*)$")); + tstringi dot_mayu; + for (size_t i = 0; i < MAX_MAYU_REGISTRY_ENTRIES; ++ i) { + _TCHAR buf[100]; + _sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), i); + if (!reg.read(buf, &dot_mayu)) + break; + + tsmatch what; + if (boost::regex_match(dot_mayu, what, split) && + what.str(1) == i_name.eval()) { + reg.write(_T(".mayuIndex"), i); + goto success; + } + } + + { + Acquire a(&m_log, 0); + m_log << _T("unknown setting name: ") << i_name; + } + return; + +success: + ; + } + PostMessage(m_hwndAssocWindow, + WM_APP_engineNotify, EngineNotify_loadSetting, 0); } // virtual key void Engine::funcVK(FunctionParam *i_param, VKey i_vkey) { - long key = static_cast(i_vkey); - BYTE vkey = static_cast(i_vkey); - bool isExtended = !!(key & VKey_extended); - bool isUp = !i_param->m_isPressed && !!(key & VKey_released); - bool isDown = i_param->m_isPressed && !!(key & VKey_pressed); - - if (vkey == VK_LBUTTON && isDown) - mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); - else if (vkey == VK_LBUTTON && isUp) - mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); - else if (vkey == VK_MBUTTON && isDown) - mouse_event(MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0, 0); - else if (vkey == VK_MBUTTON && isUp) - mouse_event(MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0); - else if (vkey == VK_RBUTTON && isDown) - mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0); - else if (vkey == VK_RBUTTON && isUp) - mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0); - else if (vkey == VK_XBUTTON1 && isDown) - mouse_event(MOUSEEVENTF_XDOWN, 0, 0, XBUTTON1, 0); - else if (vkey == VK_XBUTTON1 && isUp) - mouse_event(MOUSEEVENTF_XUP, 0, 0, XBUTTON1, 0); - else if (vkey == VK_XBUTTON2 && isDown) - mouse_event(MOUSEEVENTF_XDOWN, 0, 0, XBUTTON2, 0); - else if (vkey == VK_XBUTTON2 && isUp) - mouse_event(MOUSEEVENTF_XUP, 0, 0, XBUTTON2, 0); - else if (isUp || isDown) - keybd_event(vkey, - static_cast(MapVirtualKey(vkey, 0)), - (isExtended ? KEYEVENTF_EXTENDEDKEY : 0) | - (i_param->m_isPressed ? 0 : KEYEVENTF_KEYUP), 0); + long key = static_cast(i_vkey); + BYTE vkey = static_cast(i_vkey); + bool isExtended = !!(key & VKey_extended); + bool isUp = !i_param->m_isPressed && !!(key & VKey_released); + bool isDown = i_param->m_isPressed && !!(key & VKey_pressed); + + if (vkey == VK_LBUTTON && isDown) + mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); + else if (vkey == VK_LBUTTON && isUp) + mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); + else if (vkey == VK_MBUTTON && isDown) + mouse_event(MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0, 0); + else if (vkey == VK_MBUTTON && isUp) + mouse_event(MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0); + else if (vkey == VK_RBUTTON && isDown) + mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0); + else if (vkey == VK_RBUTTON && isUp) + mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0); + else if (vkey == VK_XBUTTON1 && isDown) + mouse_event(MOUSEEVENTF_XDOWN, 0, 0, XBUTTON1, 0); + else if (vkey == VK_XBUTTON1 && isUp) + mouse_event(MOUSEEVENTF_XUP, 0, 0, XBUTTON1, 0); + else if (vkey == VK_XBUTTON2 && isDown) + mouse_event(MOUSEEVENTF_XDOWN, 0, 0, XBUTTON2, 0); + else if (vkey == VK_XBUTTON2 && isUp) + mouse_event(MOUSEEVENTF_XUP, 0, 0, XBUTTON2, 0); + else if (isUp || isDown) + keybd_event(vkey, + static_cast(MapVirtualKey(vkey, 0)), + (isExtended ? KEYEVENTF_EXTENDEDKEY : 0) | + (i_param->m_isPressed ? 0 : KEYEVENTF_KEYUP), 0); } // wait void Engine::funcWait(FunctionParam *i_param, int i_milliSecond) { - if (!i_param->m_isPressed) - return; - if (i_milliSecond < 0 || 5000 < i_milliSecond) // too long wait - return; - - m_isSynchronizing = true; - m_cs.release(); - Sleep(i_milliSecond); - m_cs.acquire(); - m_isSynchronizing = false; + if (!i_param->m_isPressed) + return; + if (i_milliSecond < 0 || 5000 < i_milliSecond) // too long wait + return; + + m_isSynchronizing = true; + m_cs.release(); + Sleep(i_milliSecond); + m_cs.acquire(); + m_isSynchronizing = false; } // investigate WM_COMMAND, WM_SYSCOMMAND void Engine::funcInvestigateCommand(FunctionParam *i_param) { - if (!i_param->m_isPressed) - return; - Acquire a(&m_log, 0); - g_hookData->m_doesNotifyCommand = !g_hookData->m_doesNotifyCommand; - if (g_hookData->m_doesNotifyCommand) - m_log << _T(" begin") << std::endl; - else - m_log << _T(" end") << std::endl; + if (!i_param->m_isPressed) + return; + Acquire a(&m_log, 0); + g_hookData->m_doesNotifyCommand = !g_hookData->m_doesNotifyCommand; + if (g_hookData->m_doesNotifyCommand) + m_log << _T(" begin") << std::endl; + else + m_log << _T(" end") << std::endl; } // show mayu dialog box void Engine::funcMayuDialog(FunctionParam *i_param, MayuDialogType i_dialog, - ShowCommandType i_showCommand) + ShowCommandType i_showCommand) { - if (!i_param->m_isPressed) - return; - PostMessage(getAssociatedWndow(), WM_APP_engineNotify, EngineNotify_showDlg, - static_cast(i_dialog) | - static_cast(i_showCommand)); + if (!i_param->m_isPressed) + return; + PostMessage(getAssociatedWndow(), WM_APP_engineNotify, EngineNotify_showDlg, + static_cast(i_dialog) | + static_cast(i_showCommand)); } // describe bindings void Engine::funcDescribeBindings(FunctionParam *i_param) { - if (!i_param->m_isPressed) - return; - { - Acquire a(&m_log, 1); - m_log << std::endl; - } - describeBindings(); + if (!i_param->m_isPressed) + return; + { + Acquire a(&m_log, 1); + m_log << std::endl; + } + describeBindings(); } // show help message void Engine::funcHelpMessage(FunctionParam *i_param, const StrExprArg &i_title, - const StrExprArg &i_message) + const StrExprArg &i_message) { - if (!i_param->m_isPressed) - return; + if (!i_param->m_isPressed) + return; - m_helpTitle = i_title.eval(); - m_helpMessage = i_message.eval(); - bool doesShow = !(i_title.eval().size() == 0 && i_message.eval().size() == 0); - PostMessage(getAssociatedWndow(), WM_APP_engineNotify, - EngineNotify_helpMessage, doesShow); + m_helpTitle = i_title.eval(); + m_helpMessage = i_message.eval(); + bool doesShow = !(i_title.eval().size() == 0 && i_message.eval().size() == 0); + PostMessage(getAssociatedWndow(), WM_APP_engineNotify, + EngineNotify_helpMessage, doesShow); } // show variable void Engine::funcHelpVariable(FunctionParam *i_param, const StrExprArg &i_title) { - if (!i_param->m_isPressed) - return; + if (!i_param->m_isPressed) + return; - _TCHAR buf[20]; - _sntprintf(buf, NUMBER_OF(buf), _T("%d"), m_variable); + _TCHAR buf[20]; + _sntprintf(buf, NUMBER_OF(buf), _T("%d"), m_variable); - m_helpTitle = i_title.eval(); - m_helpMessage = buf; - PostMessage(getAssociatedWndow(), WM_APP_engineNotify, - EngineNotify_helpMessage, true); + m_helpTitle = i_title.eval(); + m_helpMessage = buf; + PostMessage(getAssociatedWndow(), WM_APP_engineNotify, + EngineNotify_helpMessage, true); } // raise window void Engine::funcWindowRaise(FunctionParam *i_param, - TargetWindowType i_twt) + TargetWindowType i_twt) { - HWND hwnd; - if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt)) - return; - SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, - SWP_ASYNCWINDOWPOS | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOSIZE); + HWND hwnd; + if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt)) + return; + SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, + SWP_ASYNCWINDOWPOS | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOSIZE); } // lower window void Engine::funcWindowLower(FunctionParam *i_param, TargetWindowType i_twt) { - HWND hwnd; - if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt)) - return; - SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, - SWP_ASYNCWINDOWPOS | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOSIZE); + HWND hwnd; + if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt)) + return; + SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, + SWP_ASYNCWINDOWPOS | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOSIZE); } // minimize window void Engine::funcWindowMinimize(FunctionParam *i_param, TargetWindowType i_twt) { - HWND hwnd; - if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt)) - return; - PostMessage(hwnd, WM_SYSCOMMAND, - IsIconic(hwnd) ? SC_RESTORE : SC_MINIMIZE, 0); + HWND hwnd; + if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt)) + return; + PostMessage(hwnd, WM_SYSCOMMAND, + IsIconic(hwnd) ? SC_RESTORE : SC_MINIMIZE, 0); } // maximize window void Engine::funcWindowMaximize(FunctionParam *i_param, TargetWindowType i_twt) { - HWND hwnd; - if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt)) - return; - PostMessage(hwnd, WM_SYSCOMMAND, - IsZoomed(hwnd) ? SC_RESTORE : SC_MAXIMIZE, 0); + HWND hwnd; + if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt)) + return; + PostMessage(hwnd, WM_SYSCOMMAND, + IsZoomed(hwnd) ? SC_RESTORE : SC_MAXIMIZE, 0); } // maximize horizontally or virtically void Engine::funcWindowHVMaximize(FunctionParam *i_param, - BooleanType i_isHorizontal, - TargetWindowType i_twt) -{ - HWND hwnd; - RECT rc, rcd; - if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt, &rc, &rcd)) - return; - - // erase non window - while (true) - { - WindowPositions::iterator i = m_windowPositions.begin(); - WindowPositions::iterator end = m_windowPositions.end(); - for (; i != end; ++ i) - if (!IsWindow((*i).m_hwnd)) - break; - if (i == end) - break; - m_windowPositions.erase(i); - } - - // find target - WindowPositions::iterator i = m_windowPositions.begin(); - WindowPositions::iterator end = m_windowPositions.end(); - WindowPositions::iterator target = end; - for (; i != end; ++ i) - if ((*i).m_hwnd == hwnd) - { - target = i; - break; - } - - if (IsZoomed(hwnd)) - PostMessage(hwnd, WM_SYSCOMMAND, SC_RESTORE, 0); - else - { - WindowPosition::Mode mode = WindowPosition::Mode_normal; - - if (target != end) - { - WindowPosition &wp = *target; - rc = wp.m_rc; - if (wp.m_mode == WindowPosition::Mode_HV) - mode = wp.m_mode = - i_isHorizontal ? WindowPosition::Mode_V : WindowPosition::Mode_H; - else if (( i_isHorizontal && wp.m_mode == WindowPosition::Mode_V) || - (!i_isHorizontal && wp.m_mode == WindowPosition::Mode_H)) - mode = wp.m_mode = WindowPosition::Mode_HV; - else - m_windowPositions.erase(target); - } - else - { - mode = i_isHorizontal ? WindowPosition::Mode_H : WindowPosition::Mode_V; - m_windowPositions.push_front(WindowPosition(hwnd, rc, mode)); - } - - if (static_cast(mode) & static_cast(WindowPosition::Mode_H)) - rc.left = rcd.left, rc.right = rcd.right; - if (static_cast(mode) & static_cast(WindowPosition::Mode_V)) - rc.top = rcd.top, rc.bottom = rcd.bottom; - - asyncMoveWindow(hwnd, rc.left, rc.top, rcWidth(&rc), rcHeight(&rc)); - } + BooleanType i_isHorizontal, + TargetWindowType i_twt) +{ + HWND hwnd; + RECT rc, rcd; + if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt, &rc, &rcd)) + return; + + // erase non window + while (true) { + WindowPositions::iterator i = m_windowPositions.begin(); + WindowPositions::iterator end = m_windowPositions.end(); + for (; i != end; ++ i) + if (!IsWindow((*i).m_hwnd)) + break; + if (i == end) + break; + m_windowPositions.erase(i); + } + + // find target + WindowPositions::iterator i = m_windowPositions.begin(); + WindowPositions::iterator end = m_windowPositions.end(); + WindowPositions::iterator target = end; + for (; i != end; ++ i) + if ((*i).m_hwnd == hwnd) { + target = i; + break; + } + + if (IsZoomed(hwnd)) + PostMessage(hwnd, WM_SYSCOMMAND, SC_RESTORE, 0); + else { + WindowPosition::Mode mode = WindowPosition::Mode_normal; + + if (target != end) { + WindowPosition &wp = *target; + rc = wp.m_rc; + if (wp.m_mode == WindowPosition::Mode_HV) + mode = wp.m_mode = + i_isHorizontal ? WindowPosition::Mode_V : WindowPosition::Mode_H; + else if (( i_isHorizontal && wp.m_mode == WindowPosition::Mode_V) || + (!i_isHorizontal && wp.m_mode == WindowPosition::Mode_H)) + mode = wp.m_mode = WindowPosition::Mode_HV; + else + m_windowPositions.erase(target); + } else { + mode = i_isHorizontal ? WindowPosition::Mode_H : WindowPosition::Mode_V; + m_windowPositions.push_front(WindowPosition(hwnd, rc, mode)); + } + + if (static_cast(mode) & static_cast(WindowPosition::Mode_H)) + rc.left = rcd.left, rc.right = rcd.right; + if (static_cast(mode) & static_cast(WindowPosition::Mode_V)) + rc.top = rcd.top, rc.bottom = rcd.bottom; + + asyncMoveWindow(hwnd, rc.left, rc.top, rcWidth(&rc), rcHeight(&rc)); + } } // maximize window horizontally void Engine::funcWindowHMaximize(FunctionParam *i_param, - TargetWindowType i_twt) + TargetWindowType i_twt) { - funcWindowHVMaximize(i_param, BooleanType_true, i_twt); + funcWindowHVMaximize(i_param, BooleanType_true, i_twt); } // maximize window virtically void Engine::funcWindowVMaximize(FunctionParam *i_param, - TargetWindowType i_twt) + TargetWindowType i_twt) { - funcWindowHVMaximize(i_param, BooleanType_false, i_twt); + funcWindowHVMaximize(i_param, BooleanType_false, i_twt); } // move window void Engine::funcWindowMove(FunctionParam *i_param, int i_dx, int i_dy, - TargetWindowType i_twt) + TargetWindowType i_twt) { - funcWindowMoveTo(i_param, GravityType_C, i_dx, i_dy, i_twt); + funcWindowMoveTo(i_param, GravityType_C, i_dx, i_dy, i_twt); } // move window to ... void Engine::funcWindowMoveTo(FunctionParam *i_param, - GravityType i_gravityType, - int i_dx, int i_dy, TargetWindowType i_twt) + GravityType i_gravityType, + int i_dx, int i_dy, TargetWindowType i_twt) { - HWND hwnd; - RECT rc, rcd; - if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt, &rc, &rcd)) - return; - - int x = rc.left + i_dx; - int y = rc.top + i_dy; + HWND hwnd; + RECT rc, rcd; + if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt, &rc, &rcd)) + return; + + int x = rc.left + i_dx; + int y = rc.top + i_dy; - if (i_gravityType & GravityType_N) - y = i_dy + rcd.top; - if (i_gravityType & GravityType_E) - x = i_dx + rcd.right - rcWidth(&rc); - if (i_gravityType & GravityType_W) - x = i_dx + rcd.left; - if (i_gravityType & GravityType_S) - y = i_dy + rcd.bottom - rcHeight(&rc); - asyncMoveWindow(hwnd, x, y); + if (i_gravityType & GravityType_N) + y = i_dy + rcd.top; + if (i_gravityType & GravityType_E) + x = i_dx + rcd.right - rcWidth(&rc); + if (i_gravityType & GravityType_W) + x = i_dx + rcd.left; + if (i_gravityType & GravityType_S) + y = i_dy + rcd.bottom - rcHeight(&rc); + asyncMoveWindow(hwnd, x, y); } // move window visibly void Engine::funcWindowMoveVisibly(FunctionParam *i_param, - TargetWindowType i_twt) + TargetWindowType i_twt) { - HWND hwnd; - RECT rc, rcd; - if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt, &rc, &rcd)) - return; + HWND hwnd; + RECT rc, rcd; + if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt, &rc, &rcd)) + return; - int x = rc.left; - int y = rc.top; - if (rc.left < rcd.left) - x = rcd.left; - else if (rcd.right < rc.right) - x = rcd.right - rcWidth(&rc); - if (rc.top < rcd.top) - y = rcd.top; - else if (rcd.bottom < rc.bottom) - y = rcd.bottom - rcHeight(&rc); - asyncMoveWindow(hwnd, x, y); + int x = rc.left; + int y = rc.top; + if (rc.left < rcd.left) + x = rcd.left; + else if (rcd.right < rc.right) + x = rcd.right - rcWidth(&rc); + if (rc.top < rcd.top) + y = rcd.top; + else if (rcd.bottom < rc.bottom) + y = rcd.bottom - rcHeight(&rc); + asyncMoveWindow(hwnd, x, y); } -struct EnumDisplayMonitorsForWindowMonitorToParam -{ - std::vector m_monitors; - std::vector m_monitorinfos; - int m_primaryMonitorIdx; - int m_currentMonitorIdx; +struct EnumDisplayMonitorsForWindowMonitorToParam { + std::vector m_monitors; + std::vector m_monitorinfos; + int m_primaryMonitorIdx; + int m_currentMonitorIdx; - HMONITOR m_hmon; + HMONITOR m_hmon; public: - EnumDisplayMonitorsForWindowMonitorToParam(HMONITOR i_hmon) - : m_hmon(i_hmon), - m_primaryMonitorIdx(-1), m_currentMonitorIdx(-1) - { - } + EnumDisplayMonitorsForWindowMonitorToParam(HMONITOR i_hmon) + : m_hmon(i_hmon), + m_primaryMonitorIdx(-1), m_currentMonitorIdx(-1) { + } }; static BOOL CALLBACK enumDisplayMonitorsForWindowMonitorTo( - HMONITOR i_hmon, HDC i_hdc, LPRECT i_rcMonitor, LPARAM i_data) + HMONITOR i_hmon, HDC i_hdc, LPRECT i_rcMonitor, LPARAM i_data) { - EnumDisplayMonitorsForWindowMonitorToParam &ep = - *reinterpret_cast(i_data); + EnumDisplayMonitorsForWindowMonitorToParam &ep = + *reinterpret_cast(i_data); - ep.m_monitors.push_back(i_hmon); + ep.m_monitors.push_back(i_hmon); - MONITORINFO mi; - mi.cbSize = sizeof(mi); - getMonitorInfo(i_hmon, &mi); - ep.m_monitorinfos.push_back(mi); + MONITORINFO mi; + mi.cbSize = sizeof(mi); + getMonitorInfo(i_hmon, &mi); + ep.m_monitorinfos.push_back(mi); - if(mi.dwFlags & MONITORINFOF_PRIMARY) - ep.m_primaryMonitorIdx = ep.m_monitors.size() - 1; - if(i_hmon == ep.m_hmon) - ep.m_currentMonitorIdx = ep.m_monitors.size() - 1; + if (mi.dwFlags & MONITORINFOF_PRIMARY) + ep.m_primaryMonitorIdx = ep.m_monitors.size() - 1; + if (i_hmon == ep.m_hmon) + ep.m_currentMonitorIdx = ep.m_monitors.size() - 1; - return TRUE; + return TRUE; } /// move window to other monitor void Engine::funcWindowMonitorTo( - FunctionParam *i_param, WindowMonitorFromType i_fromType, int i_monitor, - BooleanType i_adjustPos, BooleanType i_adjustSize) -{ - HWND hwnd; - if(! getSuitableWindow(i_param, &hwnd)) - return; - - HMONITOR hmonCur; - hmonCur = monitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); - - EnumDisplayMonitorsForWindowMonitorToParam ep(hmonCur); - enumDisplayMonitors(NULL, NULL, enumDisplayMonitorsForWindowMonitorTo, - reinterpret_cast(&ep)); - if(ep.m_monitors.size() < 1 || - ep.m_primaryMonitorIdx < 0 || ep.m_currentMonitorIdx < 0) - return; - - int targetIdx; - switch(i_fromType) { - case WindowMonitorFromType_primary: - targetIdx = (ep.m_primaryMonitorIdx + i_monitor) % ep.m_monitors.size(); - break; - - case WindowMonitorFromType_current: - targetIdx = (ep.m_currentMonitorIdx + i_monitor) % ep.m_monitors.size(); - break; - } - if(ep.m_currentMonitorIdx == targetIdx) - return; - - RECT rcCur, rcTarget, rcWin; - rcCur = ep.m_monitorinfos[ep.m_currentMonitorIdx].rcWork; - rcTarget = ep.m_monitorinfos[targetIdx].rcWork; - GetWindowRect(hwnd, &rcWin); - - int x = rcTarget.left + (rcWin.left - rcCur.left); - int y = rcTarget.top + (rcWin.top - rcCur.top); - int w = rcWidth(&rcWin); - int h = rcHeight(&rcWin); - - if(i_adjustPos) { - if(x + w > rcTarget.right) - x = rcTarget.right - w; - if(x < rcTarget.left) - x = rcTarget.left; - if(w > rcWidth(&rcTarget)) { - x = rcTarget.left; - w = rcWidth(&rcTarget); - } - - if(y + h > rcTarget.bottom) - y = rcTarget.bottom - h; - if(y < rcTarget.top) - y = rcTarget.top; - if(h > rcHeight(&rcTarget)) { - y = rcTarget.top; - h = rcHeight(&rcTarget); - } - } - - if(i_adjustPos && i_adjustSize) { - if(IsZoomed(hwnd)) - PostMessage(hwnd, WM_SYSCOMMAND, SC_RESTORE, 0); - asyncMoveWindow(hwnd, x, y, w, h); - } else { - asyncMoveWindow(hwnd, x, y); - } + FunctionParam *i_param, WindowMonitorFromType i_fromType, int i_monitor, + BooleanType i_adjustPos, BooleanType i_adjustSize) +{ + HWND hwnd; + if (! getSuitableWindow(i_param, &hwnd)) + return; + + HMONITOR hmonCur; + hmonCur = monitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); + + EnumDisplayMonitorsForWindowMonitorToParam ep(hmonCur); + enumDisplayMonitors(NULL, NULL, enumDisplayMonitorsForWindowMonitorTo, + reinterpret_cast(&ep)); + if (ep.m_monitors.size() < 1 || + ep.m_primaryMonitorIdx < 0 || ep.m_currentMonitorIdx < 0) + return; + + int targetIdx; + switch (i_fromType) { + case WindowMonitorFromType_primary: + targetIdx = (ep.m_primaryMonitorIdx + i_monitor) % ep.m_monitors.size(); + break; + + case WindowMonitorFromType_current: + targetIdx = (ep.m_currentMonitorIdx + i_monitor) % ep.m_monitors.size(); + break; + } + if (ep.m_currentMonitorIdx == targetIdx) + return; + + RECT rcCur, rcTarget, rcWin; + rcCur = ep.m_monitorinfos[ep.m_currentMonitorIdx].rcWork; + rcTarget = ep.m_monitorinfos[targetIdx].rcWork; + GetWindowRect(hwnd, &rcWin); + + int x = rcTarget.left + (rcWin.left - rcCur.left); + int y = rcTarget.top + (rcWin.top - rcCur.top); + int w = rcWidth(&rcWin); + int h = rcHeight(&rcWin); + + if (i_adjustPos) { + if (x + w > rcTarget.right) + x = rcTarget.right - w; + if (x < rcTarget.left) + x = rcTarget.left; + if (w > rcWidth(&rcTarget)) { + x = rcTarget.left; + w = rcWidth(&rcTarget); + } + + if (y + h > rcTarget.bottom) + y = rcTarget.bottom - h; + if (y < rcTarget.top) + y = rcTarget.top; + if (h > rcHeight(&rcTarget)) { + y = rcTarget.top; + h = rcHeight(&rcTarget); + } + } + + if (i_adjustPos && i_adjustSize) { + if (IsZoomed(hwnd)) + PostMessage(hwnd, WM_SYSCOMMAND, SC_RESTORE, 0); + asyncMoveWindow(hwnd, x, y, w, h); + } else { + asyncMoveWindow(hwnd, x, y); + } } /// move window to other monitor void Engine::funcWindowMonitor( - FunctionParam *i_param, int i_monitor, - BooleanType i_adjustPos, BooleanType i_adjustSize) + FunctionParam *i_param, int i_monitor, + BooleanType i_adjustPos, BooleanType i_adjustSize) { - funcWindowMonitorTo(i_param, WindowMonitorFromType_primary, i_monitor, - i_adjustPos, i_adjustSize); + funcWindowMonitorTo(i_param, WindowMonitorFromType_primary, i_monitor, + i_adjustPos, i_adjustSize); } // void Engine::funcWindowClingToLeft(FunctionParam *i_param, - TargetWindowType i_twt) + TargetWindowType i_twt) { - funcWindowMoveTo(i_param, GravityType_W, 0, 0, i_twt); + funcWindowMoveTo(i_param, GravityType_W, 0, 0, i_twt); } // void Engine::funcWindowClingToRight(FunctionParam *i_param, - TargetWindowType i_twt) + TargetWindowType i_twt) { - funcWindowMoveTo(i_param, GravityType_E, 0, 0, i_twt); + funcWindowMoveTo(i_param, GravityType_E, 0, 0, i_twt); } // void Engine::funcWindowClingToTop(FunctionParam *i_param, - TargetWindowType i_twt) + TargetWindowType i_twt) { - funcWindowMoveTo(i_param, GravityType_N, 0, 0, i_twt); + funcWindowMoveTo(i_param, GravityType_N, 0, 0, i_twt); } // void Engine::funcWindowClingToBottom(FunctionParam *i_param, - TargetWindowType i_twt) + TargetWindowType i_twt) { - funcWindowMoveTo(i_param, GravityType_S, 0, 0, i_twt); + funcWindowMoveTo(i_param, GravityType_S, 0, 0, i_twt); } // close window void Engine::funcWindowClose(FunctionParam *i_param, TargetWindowType i_twt) { - HWND hwnd; - if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt)) - return; - PostMessage(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0); + HWND hwnd; + if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt)) + return; + PostMessage(hwnd, WM_SYSCOMMAND, SC_CLOSE, 0); } // toggle top-most flag of the window void Engine::funcWindowToggleTopMost(FunctionParam *i_param) { - HWND hwnd; - if (!getSuitableWindow(i_param, &hwnd)) - return; - SetWindowPos( - hwnd, + HWND hwnd; + if (!getSuitableWindow(i_param, &hwnd)) + return; + SetWindowPos( + hwnd, #ifdef MAYU64 - (GetWindowLongPtr(hwnd, GWL_EXSTYLE) & WS_EX_TOPMOST) ? + (GetWindowLongPtr(hwnd, GWL_EXSTYLE) & WS_EX_TOPMOST) ? #else - (GetWindowLong(hwnd, GWL_EXSTYLE) & WS_EX_TOPMOST) ? + (GetWindowLong(hwnd, GWL_EXSTYLE) & WS_EX_TOPMOST) ? #endif - HWND_NOTOPMOST : HWND_TOPMOST, - 0, 0, 0, 0, - SWP_ASYNCWINDOWPOS | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOSIZE); + HWND_NOTOPMOST : HWND_TOPMOST, + 0, 0, 0, 0, + SWP_ASYNCWINDOWPOS | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOSIZE); } // identify the window void Engine::funcWindowIdentify(FunctionParam *i_param) { - if (!i_param->m_isPressed) - return; - - _TCHAR className[GANA_MAX_ATOM_LENGTH]; - bool ok = false; - if (GetClassName(i_param->m_hwnd, className, NUMBER_OF(className))) - { - if (_tcsicmp(className, _T("ConsoleWindowClass")) == 0) - { - _TCHAR titleName[1024]; - if (GetWindowText(i_param->m_hwnd, titleName, NUMBER_OF(titleName)) == 0) - titleName[0] = _T('\0'); - { - Acquire a(&m_log, 1); - m_log << _T("HWND:\t") << std::hex - << reinterpret_cast(i_param->m_hwnd) - << std::dec << std::endl; - } - Acquire a(&m_log, 0); - m_log << _T("CLASS:\t") << className << std::endl; - m_log << _T("TITLE:\t") << titleName << std::endl; - - HWND hwnd = getToplevelWindow(i_param->m_hwnd, NULL); - RECT rc; - GetWindowRect(hwnd, &rc); - m_log << _T("Toplevel Window Position/Size: (") - << rc.left << _T(", ") << rc.top << _T(") / (") - << rcWidth(&rc) << _T("x") << rcHeight(&rc) - << _T(")") << std::endl; - - SystemParametersInfo(SPI_GETWORKAREA, 0, (void *)&rc, FALSE); - m_log << _T("Desktop Window Position/Size: (") - << rc.left << _T(", ") << rc.top << _T(") / (") - << rcWidth(&rc) << _T("x") << rcHeight(&rc) - << _T(")") << std::endl; - - m_log << std::endl; - ok = true; - } - } - if (!ok) - { - UINT WM_MAYU_MESSAGE = RegisterWindowMessage( - addSessionId(WM_MAYU_MESSAGE_NAME).c_str()); - CHECK_TRUE( PostMessage(i_param->m_hwnd, WM_MAYU_MESSAGE, - MayuMessage_notifyName, 0) ); - } + if (!i_param->m_isPressed) + return; + + _TCHAR className[GANA_MAX_ATOM_LENGTH]; + bool ok = false; + if (GetClassName(i_param->m_hwnd, className, NUMBER_OF(className))) { + if (_tcsicmp(className, _T("ConsoleWindowClass")) == 0) { + _TCHAR titleName[1024]; + if (GetWindowText(i_param->m_hwnd, titleName, NUMBER_OF(titleName)) == 0) + titleName[0] = _T('\0'); + { + Acquire a(&m_log, 1); + m_log << _T("HWND:\t") << std::hex + << reinterpret_cast(i_param->m_hwnd) + << std::dec << std::endl; + } + Acquire a(&m_log, 0); + m_log << _T("CLASS:\t") << className << std::endl; + m_log << _T("TITLE:\t") << titleName << std::endl; + + HWND hwnd = getToplevelWindow(i_param->m_hwnd, NULL); + RECT rc; + GetWindowRect(hwnd, &rc); + m_log << _T("Toplevel Window Position/Size: (") + << rc.left << _T(", ") << rc.top << _T(") / (") + << rcWidth(&rc) << _T("x") << rcHeight(&rc) + << _T(")") << std::endl; + + SystemParametersInfo(SPI_GETWORKAREA, 0, (void *)&rc, FALSE); + m_log << _T("Desktop Window Position/Size: (") + << rc.left << _T(", ") << rc.top << _T(") / (") + << rcWidth(&rc) << _T("x") << rcHeight(&rc) + << _T(")") << std::endl; + + m_log << std::endl; + ok = true; + } + } + if (!ok) { + UINT WM_MAYU_MESSAGE = RegisterWindowMessage( + addSessionId(WM_MAYU_MESSAGE_NAME).c_str()); + CHECK_TRUE( PostMessage(i_param->m_hwnd, WM_MAYU_MESSAGE, + MayuMessage_notifyName, 0) ); + } } // set alpha blending parameter to the window void Engine::funcWindowSetAlpha(FunctionParam *i_param, int i_alpha) { - HWND hwnd; - if (!getSuitableWindow(i_param, &hwnd)) - return; - - if (i_alpha < 0) // remove all alpha - { - for (WindowsWithAlpha::iterator i = m_windowsWithAlpha.begin(); - i != m_windowsWithAlpha.end(); ++ i) - { + HWND hwnd; + if (!getSuitableWindow(i_param, &hwnd)) + return; + + if (i_alpha < 0) { // remove all alpha + for (WindowsWithAlpha::iterator i = m_windowsWithAlpha.begin(); + i != m_windowsWithAlpha.end(); ++ i) { #ifdef MAYU64 - SetWindowLongPtr(*i, GWL_EXSTYLE, - GetWindowLongPtr(*i, GWL_EXSTYLE) & ~WS_EX_LAYERED); + SetWindowLongPtr(*i, GWL_EXSTYLE, + GetWindowLongPtr(*i, GWL_EXSTYLE) & ~WS_EX_LAYERED); #else - SetWindowLong(*i, GWL_EXSTYLE, - GetWindowLong(*i, GWL_EXSTYLE) & ~WS_EX_LAYERED); + SetWindowLong(*i, GWL_EXSTYLE, + GetWindowLong(*i, GWL_EXSTYLE) & ~WS_EX_LAYERED); #endif - RedrawWindow(*i, NULL, NULL, - RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN); - } - m_windowsWithAlpha.clear(); - } - else - { + RedrawWindow(*i, NULL, NULL, + RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN); + } + m_windowsWithAlpha.clear(); + } else { #ifdef MAYU64 - LONG_PTR exStyle = GetWindowLongPtr(hwnd, GWL_EXSTYLE); + LONG_PTR exStyle = GetWindowLongPtr(hwnd, GWL_EXSTYLE); #else - LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE); + LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE); #endif - if (exStyle & WS_EX_LAYERED) // remove alpha - { - WindowsWithAlpha::iterator - i = std::find(m_windowsWithAlpha.begin(), m_windowsWithAlpha.end(), - hwnd); - if (i == m_windowsWithAlpha.end()) - return; // already layered by the application - - m_windowsWithAlpha.erase(i); - + if (exStyle & WS_EX_LAYERED) { // remove alpha + WindowsWithAlpha::iterator + i = std::find(m_windowsWithAlpha.begin(), m_windowsWithAlpha.end(), + hwnd); + if (i == m_windowsWithAlpha.end()) + return; // already layered by the application + + m_windowsWithAlpha.erase(i); + #ifdef MAYU64 - SetWindowLongPtr(hwnd, GWL_EXSTYLE, exStyle & ~WS_EX_LAYERED); -#else - SetWindowLong(hwnd, GWL_EXSTYLE, exStyle & ~WS_EX_LAYERED); + SetWindowLongPtr(hwnd, GWL_EXSTYLE, exStyle & ~WS_EX_LAYERED); +#else + SetWindowLong(hwnd, GWL_EXSTYLE, exStyle & ~WS_EX_LAYERED); #endif - } - else // add alpha - { + } else { // add alpha #ifdef MAYU64 - SetWindowLongPtr(hwnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED); + SetWindowLongPtr(hwnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED); #else - SetWindowLong(hwnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED); + SetWindowLong(hwnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED); #endif - i_alpha %= 101; - if (!setLayeredWindowAttributes(hwnd, 0, - (BYTE)(255 * i_alpha / 100), LWA_ALPHA)) - { - Acquire a(&m_log, 0); - m_log << _T("error: &WindowSetAlpha(") << i_alpha - << _T(") failed for HWND: ") << std::hex - << hwnd << std::dec << std::endl; - return; - } - m_windowsWithAlpha.push_front(hwnd); - } - RedrawWindow(hwnd, NULL, NULL, - RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN); - } + i_alpha %= 101; + if (!setLayeredWindowAttributes(hwnd, 0, + (BYTE)(255 * i_alpha / 100), LWA_ALPHA)) { + Acquire a(&m_log, 0); + m_log << _T("error: &WindowSetAlpha(") << i_alpha + << _T(") failed for HWND: ") << std::hex + << hwnd << std::dec << std::endl; + return; + } + m_windowsWithAlpha.push_front(hwnd); + } + RedrawWindow(hwnd, NULL, NULL, + RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN); + } } // redraw the window void Engine::funcWindowRedraw(FunctionParam *i_param) { - HWND hwnd; - if (!getSuitableWindow(i_param, &hwnd)) - return; - RedrawWindow(hwnd, NULL, NULL, - RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN); + HWND hwnd; + if (!getSuitableWindow(i_param, &hwnd)) + return; + RedrawWindow(hwnd, NULL, NULL, + RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN); } // resize window to void Engine::funcWindowResizeTo(FunctionParam *i_param, int i_width, - int i_height, TargetWindowType i_twt) -{ - HWND hwnd; - RECT rc, rcd; - if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt, &rc, &rcd)) - return; - - if (i_width == 0) - i_width = rcWidth(&rc); - else if (i_width < 0) - i_width += rcWidth(&rcd); - - if (i_height == 0) - i_height = rcHeight(&rc); - else if (i_height < 0) - i_height += rcHeight(&rcd); - - asyncResize(hwnd, i_width, i_height); + int i_height, TargetWindowType i_twt) +{ + HWND hwnd; + RECT rc, rcd; + if (!getSuitableMdiWindow(i_param, &hwnd, &i_twt, &rc, &rcd)) + return; + + if (i_width == 0) + i_width = rcWidth(&rc); + else if (i_width < 0) + i_width += rcWidth(&rcd); + + if (i_height == 0) + i_height = rcHeight(&rc); + else if (i_height < 0) + i_height += rcHeight(&rcd); + + asyncResize(hwnd, i_width, i_height); } // move the mouse cursor void Engine::funcMouseMove(FunctionParam *i_param, int i_dx, int i_dy) { - if (!i_param->m_isPressed) - return; - POINT pt; - GetCursorPos(&pt); - SetCursorPos(pt.x + i_dx, pt.y + i_dy); + if (!i_param->m_isPressed) + return; + POINT pt; + GetCursorPos(&pt); + SetCursorPos(pt.x + i_dx, pt.y + i_dy); } // send a mouse-wheel-message to Windows void Engine::funcMouseWheel(FunctionParam *i_param, int i_delta) { - if (!i_param->m_isPressed) - return; - mouse_event(MOUSEEVENTF_WHEEL, 0, 0, i_delta, 0); + if (!i_param->m_isPressed) + return; + mouse_event(MOUSEEVENTF_WHEEL, 0, 0, i_delta, 0); } // convert the contents of the Clipboard to upper case void Engine::funcClipboardChangeCase(FunctionParam *i_param, - BooleanType i_doesConvertToUpperCase) -{ - if (!i_param->m_isPressed) - return; - - HGLOBAL hdata; - const _TCHAR *text = getTextFromClipboard(&hdata); - HGLOBAL hdataNew = NULL; - if (text) - { - int size = static_cast(GlobalSize(hdata)); - hdataNew = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, size); - if (hdataNew) - { - if (_TCHAR *dataNew = reinterpret_cast<_TCHAR *>(GlobalLock(hdataNew))) - { - std::memcpy(dataNew, text, size); - _TCHAR *dataEnd = dataNew + size; - while (dataNew < dataEnd && *dataNew) - { - _TCHAR c = *dataNew; - if (_istlead(c)) - dataNew += 2; - else - *dataNew++ = - i_doesConvertToUpperCase ? _totupper(c) : _totlower(c); + BooleanType i_doesConvertToUpperCase) +{ + if (!i_param->m_isPressed) + return; + + HGLOBAL hdata; + const _TCHAR *text = getTextFromClipboard(&hdata); + HGLOBAL hdataNew = NULL; + if (text) { + int size = static_cast(GlobalSize(hdata)); + hdataNew = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, size); + if (hdataNew) { + if (_TCHAR *dataNew = reinterpret_cast<_TCHAR *>(GlobalLock(hdataNew))) { + std::memcpy(dataNew, text, size); + _TCHAR *dataEnd = dataNew + size; + while (dataNew < dataEnd && *dataNew) { + _TCHAR c = *dataNew; + if (_istlead(c)) + dataNew += 2; + else + *dataNew++ = + i_doesConvertToUpperCase ? _totupper(c) : _totlower(c); + } + GlobalUnlock(hdataNew); + } + } } - GlobalUnlock(hdataNew); - } - } - } - closeClipboard(hdata, hdataNew); + closeClipboard(hdata, hdataNew); } // convert the contents of the Clipboard to upper case void Engine::funcClipboardUpcaseWord(FunctionParam *i_param) { - funcClipboardChangeCase(i_param, BooleanType_true); + funcClipboardChangeCase(i_param, BooleanType_true); } // convert the contents of the Clipboard to lower case void Engine::funcClipboardDowncaseWord(FunctionParam *i_param) { - funcClipboardChangeCase(i_param, BooleanType_false); + funcClipboardChangeCase(i_param, BooleanType_false); } // set the contents of the Clipboard to the string void Engine::funcClipboardCopy(FunctionParam *i_param, const StrExprArg &i_text) { - if (!i_param->m_isPressed) - return; - if (!OpenClipboard(NULL)) - return; - - HGLOBAL hdataNew = - GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, - (i_text.eval().size() + 1) * sizeof(_TCHAR)); - if (!hdataNew) - return; - _TCHAR *dataNew = reinterpret_cast<_TCHAR *>(GlobalLock(hdataNew)); - _tcscpy(dataNew, i_text.eval().c_str()); - GlobalUnlock(hdataNew); - closeClipboard(NULL, hdataNew); + if (!i_param->m_isPressed) + return; + if (!OpenClipboard(NULL)) + return; + + HGLOBAL hdataNew = + GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, + (i_text.eval().size() + 1) * sizeof(_TCHAR)); + if (!hdataNew) + return; + _TCHAR *dataNew = reinterpret_cast<_TCHAR *>(GlobalLock(hdataNew)); + _tcscpy(dataNew, i_text.eval().c_str()); + GlobalUnlock(hdataNew); + closeClipboard(NULL, hdataNew); } // void Engine::funcEmacsEditKillLinePred( - FunctionParam *i_param, const KeySeq *i_keySeq1, const KeySeq *i_keySeq2) -{ - m_emacsEditKillLine.m_doForceReset = false; - if (!i_param->m_isPressed) - return; - - int r = m_emacsEditKillLine.pred(); - const KeySeq *keySeq; - if (r == 1) - keySeq = i_keySeq1; - else if (r == 2) - keySeq = i_keySeq2; - else // r == 0 - return; - ASSERT(keySeq); - generateKeySeqEvents(i_param->m_c, keySeq, Part_all); + FunctionParam *i_param, const KeySeq *i_keySeq1, const KeySeq *i_keySeq2) +{ + m_emacsEditKillLine.m_doForceReset = false; + if (!i_param->m_isPressed) + return; + + int r = m_emacsEditKillLine.pred(); + const KeySeq *keySeq; + if (r == 1) + keySeq = i_keySeq1; + else if (r == 2) + keySeq = i_keySeq2; + else // r == 0 + return; + ASSERT(keySeq); + generateKeySeqEvents(i_param->m_c, keySeq, Part_all); } // void Engine::funcEmacsEditKillLineFunc(FunctionParam *i_param) { - if (!i_param->m_isPressed) - return; - m_emacsEditKillLine.func(); - m_emacsEditKillLine.m_doForceReset = false; + if (!i_param->m_isPressed) + return; + m_emacsEditKillLine.func(); + m_emacsEditKillLine.m_doForceReset = false; } // clear log void Engine::funcLogClear(FunctionParam *i_param) { - if (!i_param->m_isPressed) - return; - PostMessage(getAssociatedWndow(), WM_APP_engineNotify, - EngineNotify_clearLog, 0); + if (!i_param->m_isPressed) + return; + PostMessage(getAssociatedWndow(), WM_APP_engineNotify, + EngineNotify_clearLog, 0); } // recenter void Engine::funcRecenter(FunctionParam *i_param) { - if (!i_param->m_isPressed) - return; - if (m_hwndFocus) - { - UINT WM_MAYU_MESSAGE = RegisterWindowMessage( - addSessionId(WM_MAYU_MESSAGE_NAME).c_str()); - PostMessage(m_hwndFocus, WM_MAYU_MESSAGE, MayuMessage_funcRecenter, 0); - } + if (!i_param->m_isPressed) + return; + if (m_hwndFocus) { + UINT WM_MAYU_MESSAGE = RegisterWindowMessage( + addSessionId(WM_MAYU_MESSAGE_NAME).c_str()); + PostMessage(m_hwndFocus, WM_MAYU_MESSAGE, MayuMessage_funcRecenter, 0); + } } // set IME open status void Engine::funcSetImeStatus(FunctionParam *i_param, ToggleType i_toggle) { - if (!i_param->m_isPressed) - return; - if (m_hwndFocus) - { - UINT WM_MAYU_MESSAGE = RegisterWindowMessage( - addSessionId(WM_MAYU_MESSAGE_NAME).c_str()); - int status = -1; - switch (i_toggle) - { - case ToggleType_toggle: - status = -1; - break; - case ToggleType_off: - status = 0; - break; - case ToggleType_on: - status = 1; - break; - } - PostMessage(m_hwndFocus, WM_MAYU_MESSAGE, MayuMessage_funcSetImeStatus, status); - } + if (!i_param->m_isPressed) + return; + if (m_hwndFocus) { + UINT WM_MAYU_MESSAGE = RegisterWindowMessage( + addSessionId(WM_MAYU_MESSAGE_NAME).c_str()); + int status = -1; + switch (i_toggle) { + case ToggleType_toggle: + status = -1; + break; + case ToggleType_off: + status = 0; + break; + case ToggleType_on: + status = 1; + break; + } + PostMessage(m_hwndFocus, WM_MAYU_MESSAGE, MayuMessage_funcSetImeStatus, status); + } } // set IME open status void Engine::funcSetImeString(FunctionParam *i_param, const StrExprArg &i_data) { - if (!i_param->m_isPressed) - return; - if (m_hwndFocus) - { - UINT WM_MAYU_MESSAGE = RegisterWindowMessage( - addSessionId(WM_MAYU_MESSAGE_NAME).c_str()); - PostMessage(m_hwndFocus, WM_MAYU_MESSAGE, MayuMessage_funcSetImeString, i_data.eval().size() * sizeof(_TCHAR)); - - DWORD len = 0; - DWORD error; - DisconnectNamedPipe(m_hookPipe); - ConnectNamedPipe(m_hookPipe, NULL); - error = WriteFile(m_hookPipe, i_data.eval().c_str(), - i_data.eval().size() * sizeof(_TCHAR), - &len, NULL); - - //FlushFileBuffers(m_hookPipe); - } + if (!i_param->m_isPressed) + return; + if (m_hwndFocus) { + UINT WM_MAYU_MESSAGE = RegisterWindowMessage( + addSessionId(WM_MAYU_MESSAGE_NAME).c_str()); + PostMessage(m_hwndFocus, WM_MAYU_MESSAGE, MayuMessage_funcSetImeString, i_data.eval().size() * sizeof(_TCHAR)); + + DWORD len = 0; + DWORD error; + DisconnectNamedPipe(m_hookPipe); + ConnectNamedPipe(m_hookPipe, NULL); + error = WriteFile(m_hookPipe, i_data.eval().c_str(), + i_data.eval().size() * sizeof(_TCHAR), + &len, NULL); + + //FlushFileBuffers(m_hookPipe); + } } // Direct SSTP Server class DirectSSTPServer { public: - tstring m_path; - HWND m_hwnd; - tstring m_name; - tstring m_keroname; + tstring m_path; + HWND m_hwnd; + tstring m_name; + tstring m_keroname; public: - DirectSSTPServer() - : m_hwnd(NULL) - { - } + DirectSSTPServer() + : m_hwnd(NULL) { + } }; class ParseDirectSSTPData { - typedef boost::match_results MR; + typedef boost::match_results MR; public: - typedef std::map DirectSSTPServers; + typedef std::map DirectSSTPServers; private: - DirectSSTPServers *m_directSSTPServers; - + DirectSSTPServers *m_directSSTPServers; + public: - // constructor - ParseDirectSSTPData(DirectSSTPServers *i_directSSTPServers) - : m_directSSTPServers(i_directSSTPServers) - { - } - - bool operator()(const MR& i_what) - { + // constructor + ParseDirectSSTPData(DirectSSTPServers *i_directSSTPServers) + : m_directSSTPServers(i_directSSTPServers) { + } + + bool operator()(const MR& i_what) { #ifdef _UNICODE - tstring id(to_wstring(std::string(i_what[1].first, i_what[1].second))); - tstring member(to_wstring(std::string(i_what[2].first, i_what[2].second))); - tstring value(to_wstring(std::string(i_what[3].first, i_what[3].second))); + tstring id(to_wstring(std::string(i_what[1].first, i_what[1].second))); + tstring member(to_wstring(std::string(i_what[2].first, i_what[2].second))); + tstring value(to_wstring(std::string(i_what[3].first, i_what[3].second))); #else - tstring id(i_what[1].first, i_what[1].second); - tstring member(i_what[2].first, i_what[2].second); - tstring value(i_what[3].first, i_what[3].second); + tstring id(i_what[1].first, i_what[1].second); + tstring member(i_what[2].first, i_what[2].second); + tstring value(i_what[3].first, i_what[3].second); #endif - if (member == _T("path")) - (*m_directSSTPServers)[id].m_path = value; - else if (member == _T("hwnd")) - (*m_directSSTPServers)[id].m_hwnd = - reinterpret_cast(_ttoi(value.c_str())); - else if (member == _T("name")) - (*m_directSSTPServers)[id].m_name = value; - else if (member == _T("keroname")) - (*m_directSSTPServers)[id].m_keroname = value; - return true; - } + if (member == _T("path")) + (*m_directSSTPServers)[id].m_path = value; + else if (member == _T("hwnd")) + (*m_directSSTPServers)[id].m_hwnd = + reinterpret_cast(_ttoi(value.c_str())); + else if (member == _T("name")) + (*m_directSSTPServers)[id].m_name = value; + else if (member == _T("keroname")) + (*m_directSSTPServers)[id].m_keroname = value; + return true; + } }; // Direct SSTP void Engine::funcDirectSSTP(FunctionParam *i_param, - const tregex &i_name, - const StrExprArg &i_protocol, - const std::list &i_headers) -{ - if (!i_param->m_isPressed) - return; - - // check Direct SSTP server exist ? - if (HANDLE hm = OpenMutex(MUTEX_ALL_ACCESS, FALSE, _T("sakura"))) - CloseHandle(hm); - else - { - Acquire a(&m_log, 0); - m_log << _T(" Error(1): Direct SSTP server does not exist."); - return; - } - - HANDLE hfm = OpenFileMapping(FILE_MAP_READ, FALSE, _T("Sakura")); - if (!hfm) - { - Acquire a(&m_log, 0); - m_log << _T(" Error(2): Direct SSTP server does not provide data."); - return; - } - - char *data = - reinterpret_cast(MapViewOfFile(hfm, FILE_MAP_READ, 0, 0, 0)); - if (!data) - { - CloseHandle(hfm); - Acquire a(&m_log, 0); - m_log << _T(" Error(3): Direct SSTP server does not provide data."); - return; - } - - long length = *(long *)data; - const char *begin = data + 4; - const char *end = data + length; - boost::regex getSakura("([0-9a-fA-F]{32})\\.([^\x01]+)\x01(.*?)\r\n"); - - ParseDirectSSTPData::DirectSSTPServers servers; - boost::regex_iterator - it(begin, end, getSakura), last; - for (; it != last; ++it) - ((ParseDirectSSTPData)(&servers))(*it); - - // make request - tstring request; - if (!i_protocol.eval().size()) - request += _T("NOTIFY SSTP/1.1"); - else - request += i_protocol.eval(); - request += _T("\r\n"); - - bool hasSender = false; - for (std::list::const_iterator - i = i_headers.begin(); i != i_headers.end(); ++ i) - { - if (_tcsnicmp(_T("Charset"), i->c_str(), 7) == 0 || - _tcsnicmp(_T("Hwnd"), i->c_str(), 4) == 0) - continue; - if (_tcsnicmp(_T("Sender"), i->c_str(), 6) == 0) - hasSender = true; - request += i->c_str(); - request += _T("\r\n"); - } - - if (!hasSender) - { - request += _T("Sender: "); - request += loadString(IDS_mayu); - request += _T("\r\n"); - } - - _TCHAR buf[100]; - _sntprintf(buf, NUMBER_OF(buf), _T("HWnd: %d\r\n"), - reinterpret_cast(m_hwndAssocWindow)); - request += buf; + const tregex &i_name, + const StrExprArg &i_protocol, + const std::list &i_headers) +{ + if (!i_param->m_isPressed) + return; + + // check Direct SSTP server exist ? + if (HANDLE hm = OpenMutex(MUTEX_ALL_ACCESS, FALSE, _T("sakura"))) + CloseHandle(hm); + else { + Acquire a(&m_log, 0); + m_log << _T(" Error(1): Direct SSTP server does not exist."); + return; + } + + HANDLE hfm = OpenFileMapping(FILE_MAP_READ, FALSE, _T("Sakura")); + if (!hfm) { + Acquire a(&m_log, 0); + m_log << _T(" Error(2): Direct SSTP server does not provide data."); + return; + } + + char *data = + reinterpret_cast(MapViewOfFile(hfm, FILE_MAP_READ, 0, 0, 0)); + if (!data) { + CloseHandle(hfm); + Acquire a(&m_log, 0); + m_log << _T(" Error(3): Direct SSTP server does not provide data."); + return; + } + + long length = *(long *)data; + const char *begin = data + 4; + const char *end = data + length; + boost::regex getSakura("([0-9a-fA-F]{32})\\.([^\x01]+)\x01(.*?)\r\n"); + + ParseDirectSSTPData::DirectSSTPServers servers; + boost::regex_iterator + it(begin, end, getSakura), last; + for (; it != last; ++it) + ((ParseDirectSSTPData)(&servers))(*it); + + // make request + tstring request; + if (!i_protocol.eval().size()) + request += _T("NOTIFY SSTP/1.1"); + else + request += i_protocol.eval(); + request += _T("\r\n"); + + bool hasSender = false; + for (std::list::const_iterator + i = i_headers.begin(); i != i_headers.end(); ++ i) { + if (_tcsnicmp(_T("Charset"), i->c_str(), 7) == 0 || + _tcsnicmp(_T("Hwnd"), i->c_str(), 4) == 0) + continue; + if (_tcsnicmp(_T("Sender"), i->c_str(), 6) == 0) + hasSender = true; + request += i->c_str(); + request += _T("\r\n"); + } + + if (!hasSender) { + request += _T("Sender: "); + request += loadString(IDS_mayu); + request += _T("\r\n"); + } + + _TCHAR buf[100]; + _sntprintf(buf, NUMBER_OF(buf), _T("HWnd: %d\r\n"), + reinterpret_cast(m_hwndAssocWindow)); + request += buf; #ifdef _UNICODE - request += _T("Charset: UTF-8\r\n"); + request += _T("Charset: UTF-8\r\n"); #else - request += _T("Charset: Shift_JIS\r\n"); + request += _T("Charset: Shift_JIS\r\n"); #endif - request += _T("\r\n"); + request += _T("\r\n"); #ifdef _UNICODE - std::string request_UTF_8 = to_UTF_8(request); + std::string request_UTF_8 = to_UTF_8(request); #endif - // send request to Direct SSTP Server which matches i_name; - for (ParseDirectSSTPData::DirectSSTPServers::iterator - i = servers.begin(); i != servers.end(); ++ i) - { - tsmatch what; - if (boost::regex_match(i->second.m_name, what, i_name)) - { - COPYDATASTRUCT cd; - cd.dwData = 9801; + // send request to Direct SSTP Server which matches i_name; + for (ParseDirectSSTPData::DirectSSTPServers::iterator + i = servers.begin(); i != servers.end(); ++ i) { + tsmatch what; + if (boost::regex_match(i->second.m_name, what, i_name)) { + COPYDATASTRUCT cd; + cd.dwData = 9801; #ifdef _UNICODE - cd.cbData = request_UTF_8.size(); - cd.lpData = (void *)request_UTF_8.c_str(); + cd.cbData = request_UTF_8.size(); + cd.lpData = (void *)request_UTF_8.c_str(); #else - cd.cbData = request.size(); - cd.lpData = (void *)request.c_str(); + cd.cbData = request.size(); + cd.lpData = (void *)request.c_str(); #endif #ifdef MAYU64 - DWORD_PTR result; + DWORD_PTR result; #else - DWORD result; + DWORD result; #endif - SendMessageTimeout(i->second.m_hwnd, WM_COPYDATA, - reinterpret_cast(m_hwndAssocWindow), - reinterpret_cast(&cd), - SMTO_ABORTIFHUNG | SMTO_BLOCK, 5000, &result); - } - } - - UnmapViewOfFile(data); - CloseHandle(hfm); + SendMessageTimeout(i->second.m_hwnd, WM_COPYDATA, + reinterpret_cast(m_hwndAssocWindow), + reinterpret_cast(&cd), + SMTO_ABORTIFHUNG | SMTO_BLOCK, 5000, &result); + } + } + + UnmapViewOfFile(data); + CloseHandle(hfm); } namespace shu { - class PlugIn - { - enum Type - { - Type_A, - Type_W - }; - - private: - HMODULE m_dll; - FARPROC m_func; - Type m_type; - tstringq m_funcParam; - - public: - PlugIn() : m_dll(NULL) - { - } - - ~PlugIn() - { - FreeLibrary(m_dll); - } - - bool load(const tstringq &i_dllName, const tstringq &i_funcName, - const tstringq &i_funcParam, tomsgstream &i_log) - { - m_dll = LoadLibrary((_T("Plugins\\") + i_dllName).c_str()); - if (!m_dll) - { - m_dll = LoadLibrary((_T("Plugin\\") + i_dllName).c_str()); - if (!m_dll) - { - m_dll = LoadLibrary(i_dllName.c_str()); - if (!m_dll) - { - Acquire a(&i_log); - i_log << std::endl; - i_log << _T("error: &PlugIn() failed to load ") << i_dllName << std::endl; - return false; - } +class PlugIn +{ + enum Type { + Type_A, + Type_W + }; + +private: + HMODULE m_dll; + FARPROC m_func; + Type m_type; + tstringq m_funcParam; + +public: + PlugIn() : m_dll(NULL) { } - } - // get function + ~PlugIn() { + FreeLibrary(m_dll); + } + + bool load(const tstringq &i_dllName, const tstringq &i_funcName, + const tstringq &i_funcParam, tomsgstream &i_log) { + m_dll = LoadLibrary((_T("Plugins\\") + i_dllName).c_str()); + if (!m_dll) { + m_dll = LoadLibrary((_T("Plugin\\") + i_dllName).c_str()); + if (!m_dll) { + m_dll = LoadLibrary(i_dllName.c_str()); + if (!m_dll) { + Acquire a(&i_log); + i_log << std::endl; + i_log << _T("error: &PlugIn() failed to load ") << i_dllName << std::endl; + return false; + } + } + } + + // get function #ifdef UNICODE # define to_wstring #else # define to_string #endif - m_type = Type_W; - m_func = GetProcAddress(m_dll, to_string(_T("mayu") + i_funcName + _T("W")).c_str()); - if (!m_func) - { - m_type = Type_A; - m_func - = GetProcAddress(m_dll, to_string(_T("mayu") + i_funcName + _T("A")).c_str()); - if (!m_func) - { - m_func = GetProcAddress(m_dll, to_string(_T("mayu") + i_funcName).c_str()); - if (!m_func) - { - m_func = GetProcAddress(m_dll, to_string(i_funcName).c_str()); - if (!m_func) - { - Acquire a(&i_log); - i_log << std::endl; - i_log << _T("error: &PlugIn() failed to find function: ") - << i_funcName << std::endl; - return false; - } - } + m_type = Type_W; + m_func = GetProcAddress(m_dll, to_string(_T("mayu") + i_funcName + _T("W")).c_str()); + if (!m_func) { + m_type = Type_A; + m_func + = GetProcAddress(m_dll, to_string(_T("mayu") + i_funcName + _T("A")).c_str()); + if (!m_func) { + m_func = GetProcAddress(m_dll, to_string(_T("mayu") + i_funcName).c_str()); + if (!m_func) { + m_func = GetProcAddress(m_dll, to_string(i_funcName).c_str()); + if (!m_func) { + Acquire a(&i_log); + i_log << std::endl; + i_log << _T("error: &PlugIn() failed to find function: ") + << i_funcName << std::endl; + return false; + } + } + } + } + + m_funcParam = i_funcParam; + return true; + } + + void exec() { + ASSERT( m_dll ); + ASSERT( m_func ); + + typedef void (WINAPI * PLUGIN_FUNCTION_A)(const char *i_arg); + typedef void (WINAPI * PLUGIN_FUNCTION_W)(const wchar_t *i_arg); + switch (m_type) { + case Type_A: + reinterpret_cast(m_func)(to_string(m_funcParam).c_str()); + break; + case Type_W: + reinterpret_cast(m_func)(to_wstring(m_funcParam).c_str()); + break; + } } - } - - m_funcParam = i_funcParam; - return true; - } - - void exec() - { - ASSERT( m_dll ); - ASSERT( m_func ); - - typedef void (WINAPI * PLUGIN_FUNCTION_A)(const char *i_arg); - typedef void (WINAPI * PLUGIN_FUNCTION_W)(const wchar_t *i_arg); - switch (m_type) - { - case Type_A: - reinterpret_cast(m_func)(to_string(m_funcParam).c_str()); - break; - case Type_W: - reinterpret_cast(m_func)(to_wstring(m_funcParam).c_str()); - break; - } - } #undef to_string #undef to_wstring - }; +}; - static void plugInThread(void *i_plugin) - { - PlugIn *plugin = static_cast(i_plugin); - plugin->exec(); - delete plugin; - } +static void plugInThread(void *i_plugin) +{ + PlugIn *plugin = static_cast(i_plugin); + plugin->exec(); + delete plugin; +} } void Engine::funcPlugIn(FunctionParam *i_param, - const StrExprArg &i_dllName, - const StrExprArg &i_funcName, - const StrExprArg &i_funcParam, - BooleanType i_doesCreateThread) -{ - if (!i_param->m_isPressed) - return; - - shu::PlugIn *plugin = new shu::PlugIn(); - if (!plugin->load(i_dllName.eval(), i_funcName.eval(), i_funcParam.eval(), m_log)) - { - delete plugin; - return; - } - if (i_doesCreateThread) - { - if (_beginthread(shu::plugInThread, 0, plugin) == -1) - { - delete plugin; - Acquire a(&m_log); - m_log << std::endl; - m_log << _T("error: &PlugIn() failed to create thread."); - } - return; - } - else - plugin->exec(); + const StrExprArg &i_dllName, + const StrExprArg &i_funcName, + const StrExprArg &i_funcParam, + BooleanType i_doesCreateThread) +{ + if (!i_param->m_isPressed) + return; + + shu::PlugIn *plugin = new shu::PlugIn(); + if (!plugin->load(i_dllName.eval(), i_funcName.eval(), i_funcParam.eval(), m_log)) { + delete plugin; + return; + } + if (i_doesCreateThread) { + if (_beginthread(shu::plugInThread, 0, plugin) == -1) { + delete plugin; + Acquire a(&m_log); + m_log << std::endl; + m_log << _T("error: &PlugIn() failed to create thread."); + } + return; + } else + plugin->exec(); } void Engine::funcMouseHook(FunctionParam *i_param, - MouseHookType i_hookType, int i_hookParam) -{ - GetCursorPos(&g_hookData->m_mousePos); - g_hookData->m_mouseHookType = i_hookType; - g_hookData->m_mouseHookParam = i_hookParam; - - switch (i_hookType) - { - case MouseHookType_WindowMove: - { - // For this type, g_hookData->m_mouseHookParam means - // target window type to move. - HWND target; - bool isMDI; - - // i_hooParam < 0 means target window to move is MDI. - if (i_hookParam < 0) - isMDI = true; - else - isMDI = false; - - // abs(i_hookParam) == 2: target is window under mouse cursor - // otherwise: target is current focus window - if (i_hookParam == 2 || i_hookParam == -2) - target = WindowFromPoint(g_hookData->m_mousePos); - else - target = i_param->m_hwnd; - - g_hookData->m_hwndMouseHookTarget = - reinterpret_cast(getToplevelWindow(target, &isMDI)); - break; - default: - g_hookData->m_hwndMouseHookTarget = NULL; - break; - } - } - return; + MouseHookType i_hookType, int i_hookParam) +{ + GetCursorPos(&g_hookData->m_mousePos); + g_hookData->m_mouseHookType = i_hookType; + g_hookData->m_mouseHookParam = i_hookParam; + + switch (i_hookType) { + case MouseHookType_WindowMove: { + // For this type, g_hookData->m_mouseHookParam means + // target window type to move. + HWND target; + bool isMDI; + + // i_hooParam < 0 means target window to move is MDI. + if (i_hookParam < 0) + isMDI = true; + else + isMDI = false; + + // abs(i_hookParam) == 2: target is window under mouse cursor + // otherwise: target is current focus window + if (i_hookParam == 2 || i_hookParam == -2) + target = WindowFromPoint(g_hookData->m_mousePos); + else + target = i_param->m_hwnd; + + g_hookData->m_hwndMouseHookTarget = + reinterpret_cast(getToplevelWindow(target, &isMDI)); + break; + default: + g_hookData->m_hwndMouseHookTarget = NULL; + break; + } + } + return; } @@ -2354,25 +2255,25 @@ void Engine::funcMouseHook(FunctionParam *i_param, class StrExpr { private: - tstringq m_symbol; + tstringq m_symbol; protected: - static const Engine *s_engine; + static const Engine *s_engine; public: - StrExpr(const tstringq &i_symbol) : m_symbol(i_symbol) {}; + StrExpr(const tstringq &i_symbol) : m_symbol(i_symbol) {}; - virtual ~StrExpr() {}; + virtual ~StrExpr() {}; - virtual StrExpr *clone() const - { - return new StrExpr(*this); - } + virtual StrExpr *clone() const { + return new StrExpr(*this); + } - virtual tstringq eval() const - { - return m_symbol; - } + virtual tstringq eval() const { + return m_symbol; + } - static void setEngine(const Engine *i_engine) { s_engine = i_engine; } + static void setEngine(const Engine *i_engine) { + s_engine = i_engine; + } }; const Engine *StrExpr::s_engine = NULL; @@ -2382,23 +2283,21 @@ const Engine *StrExpr::s_engine = NULL; class StrExprClipboard : public StrExpr { public: - StrExprClipboard(const tstringq &i_symbol) : StrExpr(i_symbol) {}; - - ~StrExprClipboard() {}; - - StrExpr *clone() const - { - return new StrExprClipboard(*this); - } - - tstringq eval() const - { - HGLOBAL g; - const _TCHAR *text = getTextFromClipboard(&g); - const tstring value(text == NULL ? _T("") : text); - closeClipboard(g); - return value; - } + StrExprClipboard(const tstringq &i_symbol) : StrExpr(i_symbol) {}; + + ~StrExprClipboard() {}; + + StrExpr *clone() const { + return new StrExprClipboard(*this); + } + + tstringq eval() const { + HGLOBAL g; + const _TCHAR *text = getTextFromClipboard(&g); + const tstring value(text == NULL ? _T("") : text); + closeClipboard(g); + return value; + } }; @@ -2407,19 +2306,17 @@ public: class StrExprWindowClassName : public StrExpr { public: - StrExprWindowClassName(const tstringq &i_symbol) : StrExpr(i_symbol) {}; + StrExprWindowClassName(const tstringq &i_symbol) : StrExpr(i_symbol) {}; - ~StrExprWindowClassName() {}; + ~StrExprWindowClassName() {}; - StrExpr *clone() const - { - return new StrExprWindowClassName(*this); - } + StrExpr *clone() const { + return new StrExprWindowClassName(*this); + } - tstringq eval() const - { - return s_engine->getCurrentWindowClassName(); - } + tstringq eval() const { + return s_engine->getCurrentWindowClassName(); + } }; @@ -2428,19 +2325,17 @@ public: class StrExprWindowTitleName : public StrExpr { public: - StrExprWindowTitleName(const tstringq &i_symbol) : StrExpr(i_symbol) {}; + StrExprWindowTitleName(const tstringq &i_symbol) : StrExpr(i_symbol) {}; - ~StrExprWindowTitleName() {}; + ~StrExprWindowTitleName() {}; - StrExpr *clone() const - { - return new StrExprWindowTitleName(*this); - } + StrExpr *clone() const { + return new StrExprWindowTitleName(*this); + } - tstringq eval() const - { - return s_engine->getCurrentWindowTitleName(); - } + tstringq eval() const { + return s_engine->getCurrentWindowTitleName(); + } }; @@ -2451,70 +2346,69 @@ public: // default constructor StrExprArg::StrExprArg() { - m_expr = new StrExpr(_T("")); + m_expr = new StrExpr(_T("")); } // copy contructor StrExprArg::StrExprArg(const StrExprArg &i_data) { - m_expr = i_data.m_expr->clone(); + m_expr = i_data.m_expr->clone(); } StrExprArg &StrExprArg::operator=(const StrExprArg &i_data) { - if (i_data.m_expr == m_expr) - return *this; + if (i_data.m_expr == m_expr) + return *this; - delete m_expr; - m_expr = i_data.m_expr->clone(); + delete m_expr; + m_expr = i_data.m_expr->clone(); - return *this; + return *this; } // initializer StrExprArg::StrExprArg(const tstringq &i_symbol, Type i_type) { - switch (i_type) - { - case Literal: - m_expr = new StrExpr(i_symbol); - break; - case Builtin: - if (i_symbol == _T("Clipboard")) - m_expr = new StrExprClipboard(i_symbol); - else if (i_symbol == _T("WindowClassName")) - m_expr = new StrExprWindowClassName(i_symbol); - else if (i_symbol == _T("WindowTitleName")) - m_expr = new StrExprWindowTitleName(i_symbol); - break; - default: - break; - } + switch (i_type) { + case Literal: + m_expr = new StrExpr(i_symbol); + break; + case Builtin: + if (i_symbol == _T("Clipboard")) + m_expr = new StrExprClipboard(i_symbol); + else if (i_symbol == _T("WindowClassName")) + m_expr = new StrExprWindowClassName(i_symbol); + else if (i_symbol == _T("WindowTitleName")) + m_expr = new StrExprWindowTitleName(i_symbol); + break; + default: + break; + } } StrExprArg::~StrExprArg() { - delete m_expr; + delete m_expr; } tstringq StrExprArg::eval() const { - return m_expr->eval(); + return m_expr->eval(); } void StrExprArg::setEngine(const Engine *i_engine) { - StrExpr::setEngine(i_engine); + StrExpr::setEngine(i_engine); } // stream output tostream &operator<<(tostream &i_ost, const StrExprArg &i_data) { - i_ost << i_data.eval(); - return i_ost; + i_ost << i_data.eval(); + return i_ost; } diff --git a/function.h b/function.h index 3fd7d7a..7f508a0 100644 --- a/function.h +++ b/function.h @@ -14,18 +14,18 @@ class FunctionParam; class FunctionData { public: - /// virtual destructor - virtual ~FunctionData() = 0; - /// - virtual void load(SettingLoader *i_sl) = 0; - /// - virtual void exec(Engine *i_engine, FunctionParam *i_param) const = 0; - /// - virtual const _TCHAR *getName() const = 0; - /// - virtual tostream &output(tostream &i_ost) const = 0; - /// - virtual FunctionData *clone() const = 0; + /// virtual destructor + virtual ~FunctionData() = 0; + /// + virtual void load(SettingLoader *i_sl) = 0; + /// + virtual void exec(Engine *i_engine, FunctionParam *i_param) const = 0; + /// + virtual const _TCHAR *getName() const = 0; + /// + virtual tostream &output(tostream &i_ost) const = 0; + /// + virtual FunctionData *clone() const = 0; }; /// stream output @@ -36,11 +36,10 @@ extern tostream &operator<<(tostream &i_ost, const FunctionData *i_data); extern FunctionData *createFunctionData(const tstring &i_name); /// -enum VKey -{ - VKey_extended = 0x100, /// - VKey_released = 0x200, /// - VKey_pressed = 0x400, /// +enum VKey { + VKey_extended = 0x100, /// + VKey_released = 0x200, /// + VKey_pressed = 0x400, /// }; /// stream output @@ -48,13 +47,12 @@ extern tostream &operator<<(tostream &i_ost, VKey i_data); /// -enum ToWindowType -{ - ToWindowType_toBegin = -2, /// - ToWindowType_toMainWindow = -2, /// - ToWindowType_toOverlappedWindow = -1, /// - ToWindowType_toItself = 0, /// - ToWindowType_toParentWindow = 1, /// +enum ToWindowType { + ToWindowType_toBegin = -2, /// + ToWindowType_toMainWindow = -2, /// + ToWindowType_toOverlappedWindow = -1, /// + ToWindowType_toItself = 0, /// + ToWindowType_toParentWindow = 1, /// }; /// stream output @@ -65,17 +63,16 @@ extern bool getTypeValue(ToWindowType *o_type, const tstring &i_name); /// -enum GravityType -{ - GravityType_C = 0, /// center - GravityType_N = 1 << 0, /// north - GravityType_E = 1 << 1, /// east - GravityType_W = 1 << 2, /// west - GravityType_S = 1 << 3, /// south - GravityType_NW = GravityType_N | GravityType_W, /// north west - GravityType_NE = GravityType_N | GravityType_E, /// north east - GravityType_SW = GravityType_S | GravityType_W, /// south west - GravityType_SE = GravityType_S | GravityType_E, /// south east +enum GravityType { + GravityType_C = 0, /// center + GravityType_N = 1 << 0, /// north + GravityType_E = 1 << 1, /// east + GravityType_W = 1 << 2, /// west + GravityType_S = 1 << 3, /// south + GravityType_NW = GravityType_N | GravityType_W, /// north west + GravityType_NE = GravityType_N | GravityType_E, /// north east + GravityType_SW = GravityType_S | GravityType_W, /// south west + GravityType_SE = GravityType_S | GravityType_E, /// south east }; /// stream output @@ -96,11 +93,10 @@ extern bool getTypeValue(MouseHookType *o_type, const tstring &i_name); /// -enum MayuDialogType -{ - MayuDialogType_investigate = 0x10000, /// - MayuDialogType_log = 0x20000, /// - MayuDialogType_mask = 0xffff0000, /// +enum MayuDialogType { + MayuDialogType_investigate = 0x10000, /// + MayuDialogType_log = 0x20000, /// + MayuDialogType_mask = 0xffff0000, /// }; /// stream output @@ -109,33 +105,31 @@ extern tostream &operator<<(tostream &i_ost, MayuDialogType i_data); // get value of MayuDialogType bool getTypeValue(MayuDialogType *o_type, const tstring &i_name); - + /// -enum ModifierLockType -{ - ModifierLockType_Lock0 = Modifier::Type_Lock0, /// - ModifierLockType_Lock1 = Modifier::Type_Lock1, /// - ModifierLockType_Lock2 = Modifier::Type_Lock2, /// - ModifierLockType_Lock3 = Modifier::Type_Lock3, /// - ModifierLockType_Lock4 = Modifier::Type_Lock4, /// - ModifierLockType_Lock5 = Modifier::Type_Lock5, /// - ModifierLockType_Lock6 = Modifier::Type_Lock6, /// - ModifierLockType_Lock7 = Modifier::Type_Lock7, /// - ModifierLockType_Lock8 = Modifier::Type_Lock8, /// - ModifierLockType_Lock9 = Modifier::Type_Lock9, /// +enum ModifierLockType { + ModifierLockType_Lock0 = Modifier::Type_Lock0, /// + ModifierLockType_Lock1 = Modifier::Type_Lock1, /// + ModifierLockType_Lock2 = Modifier::Type_Lock2, /// + ModifierLockType_Lock3 = Modifier::Type_Lock3, /// + ModifierLockType_Lock4 = Modifier::Type_Lock4, /// + ModifierLockType_Lock5 = Modifier::Type_Lock5, /// + ModifierLockType_Lock6 = Modifier::Type_Lock6, /// + ModifierLockType_Lock7 = Modifier::Type_Lock7, /// + ModifierLockType_Lock8 = Modifier::Type_Lock8, /// + ModifierLockType_Lock9 = Modifier::Type_Lock9, /// }; /// -enum ToggleType -{ - ToggleType_toggle = -1, /// - ToggleType_off = 0, /// - ToggleType_on = 1, /// +enum ToggleType { + ToggleType_toggle = -1, /// + ToggleType_off = 0, /// + ToggleType_on = 1, /// }; /// stream output extern tostream &operator<<(tostream &i_ost, ToggleType i_data); - + // get value of ShowCommandType extern bool getTypeValue(ToggleType *o_type, const tstring &i_name); @@ -148,76 +142,71 @@ extern bool getTypeValue(ModifierLockType *o_type, const tstring &i_name); /// -enum ShowCommandType -{ - ShowCommandType_hide = SW_HIDE, /// - ShowCommandType_maximize = SW_MAXIMIZE, /// - ShowCommandType_minimize = SW_MINIMIZE, /// - ShowCommandType_restore = SW_RESTORE, /// - ShowCommandType_show = SW_SHOW, /// - ShowCommandType_showDefault = SW_SHOWDEFAULT, /// - ShowCommandType_showMaximized = SW_SHOWMAXIMIZED, /// - ShowCommandType_showMinimized = SW_SHOWMINIMIZED, /// - ShowCommandType_showMinNoActive = SW_SHOWMINNOACTIVE, /// - ShowCommandType_showNA = SW_SHOWNA, /// - ShowCommandType_showNoActivate = SW_SHOWNOACTIVATE, /// - ShowCommandType_showNormal = SW_SHOWNORMAL, /// +enum ShowCommandType { + ShowCommandType_hide = SW_HIDE, /// + ShowCommandType_maximize = SW_MAXIMIZE, /// + ShowCommandType_minimize = SW_MINIMIZE, /// + ShowCommandType_restore = SW_RESTORE, /// + ShowCommandType_show = SW_SHOW, /// + ShowCommandType_showDefault = SW_SHOWDEFAULT, /// + ShowCommandType_showMaximized = SW_SHOWMAXIMIZED, /// + ShowCommandType_showMinimized = SW_SHOWMINIMIZED, /// + ShowCommandType_showMinNoActive = SW_SHOWMINNOACTIVE, /// + ShowCommandType_showNA = SW_SHOWNA, /// + ShowCommandType_showNoActivate = SW_SHOWNOACTIVATE, /// + ShowCommandType_showNormal = SW_SHOWNORMAL, /// }; /// stream output extern tostream &operator<<(tostream &i_ost, ShowCommandType i_data); - + // get value of ShowCommandType extern bool getTypeValue(ShowCommandType *o_type, const tstring &i_name); /// -enum TargetWindowType -{ - TargetWindowType_overlapped = 0, /// - TargetWindowType_mdi = 1, /// +enum TargetWindowType { + TargetWindowType_overlapped = 0, /// + TargetWindowType_mdi = 1, /// }; /// stream output extern tostream &operator<<(tostream &i_ost, TargetWindowType i_data); - + // get value of ShowCommandType extern bool getTypeValue(TargetWindowType *o_type, const tstring &i_name); /// -enum BooleanType -{ - BooleanType_false = 0, /// - BooleanType_true = 1, /// +enum BooleanType { + BooleanType_false = 0, /// + BooleanType_true = 1, /// }; /// stream output extern tostream &operator<<(tostream &i_ost, BooleanType i_data); - + // get value of ShowCommandType extern bool getTypeValue(BooleanType *o_type, const tstring &i_name); /// -enum LogicalOperatorType -{ - LogicalOperatorType_or = 0, /// - LogicalOperatorType_and = 1, /// +enum LogicalOperatorType { + LogicalOperatorType_or = 0, /// + LogicalOperatorType_and = 1, /// }; /// stream output extern tostream &operator<<(tostream &i_ost, LogicalOperatorType i_data); - + // get value of LogicalOperatorType extern bool getTypeValue(LogicalOperatorType *o_type, const tstring &i_name); /// -enum WindowMonitorFromType -{ - WindowMonitorFromType_primary = 0, /// - WindowMonitorFromType_current = 1, /// +enum WindowMonitorFromType { + WindowMonitorFromType_primary = 0, /// + WindowMonitorFromType_current = 1, /// }; // stream output @@ -229,7 +218,7 @@ extern bool getTypeValue(WindowMonitorFromType *o_type, const tstring &i_name); /// stream output extern tostream &operator<<(tostream &i_ost, - const std::list &i_data); + const std::list &i_data); /// string type expression @@ -240,20 +229,19 @@ class StrExpr; class StrExprArg { private: - StrExpr *m_expr; + StrExpr *m_expr; public: - enum Type - { - Literal, - Builtin, - }; - StrExprArg(); - StrExprArg(const StrExprArg &i_data); - StrExprArg(const tstringq &i_symbol, Type i_type); - ~StrExprArg(); - StrExprArg &operator=(const StrExprArg &i_data); - tstringq eval() const; - static void setEngine(const Engine *i_engine); + enum Type { + Literal, + Builtin, + }; + StrExprArg(); + StrExprArg(const StrExprArg &i_data); + StrExprArg(const tstringq &i_symbol, Type i_type); + ~StrExprArg(); + StrExprArg &operator=(const StrExprArg &i_data); + tstringq eval() const; + static void setEngine(const Engine *i_engine); }; diff --git a/hook.cpp b/hook.cpp index 85dfd9c..c1b3197 100644 --- a/hook.cpp +++ b/hook.cpp @@ -49,34 +49,33 @@ DllExport HookData *g_hookData; /// class HookDataArch { public: - HHOOK m_hHookGetMessage; /// - HHOOK m_hHookCallWndProc; /// + HHOOK m_hHookGetMessage; /// + HHOOK m_hHookCallWndProc; /// }; static HookDataArch *s_hookDataArch; -struct Globals -{ - HANDLE m_hHookData; /// - HANDLE m_hHookDataArch; /// - HWND m_hwndFocus; /// - HINSTANCE m_hInstDLL; /// - bool m_isInMenu; /// - UINT m_WM_MAYU_MESSAGE; /// - bool m_isImeLock; /// - bool m_isImeCompositioning; /// - HHOOK m_hHookMouseProc; /// +struct Globals { + HANDLE m_hHookData; /// + HANDLE m_hHookDataArch; /// + HWND m_hwndFocus; /// + HINSTANCE m_hInstDLL; /// + bool m_isInMenu; /// + UINT m_WM_MAYU_MESSAGE; /// + bool m_isImeLock; /// + bool m_isImeCompositioning; /// + HHOOK m_hHookMouseProc; /// #ifdef NO_DRIVER - HHOOK m_hHookKeyboardProc; /// - KEYBOARD_DETOUR m_keyboardDetour; - Engine *m_engine; + HHOOK m_hHookKeyboardProc; /// + KEYBOARD_DETOUR m_keyboardDetour; + Engine *m_engine; #endif // NO_DRIVER - DWORD m_hwndTaskTray; /// - HANDLE m_hMailslot; - bool m_isInitialized; + DWORD m_hwndTaskTray; /// + HANDLE m_hMailslot; + bool m_isInitialized; #ifndef NDEBUG - bool m_isLogging; - _TCHAR m_moduleName[GANA_MAX_PATH]; + bool m_isLogging; + _TCHAR m_moduleName[GANA_MAX_PATH]; #endif // !NDEBUG }; @@ -101,340 +100,316 @@ static bool initialize(); bool initialize() { #ifndef NDEBUG - _TCHAR path[GANA_MAX_PATH]; - GetModuleFileName(NULL, path, GANA_MAX_PATH); - _tsplitpath_s(path, NULL, 0, NULL, 0, g.m_moduleName, GANA_MAX_PATH, NULL, 0); - if (_tcsncmp(g.m_moduleName, _T("Dbgview"), sizeof(_T("Dbgview"))/sizeof(_TCHAR)) != 0 && - _tcsncmp(g.m_moduleName, _T("windbg"), sizeof(_T("windbg"))/sizeof(_TCHAR)) != 0) - { - g.m_isLogging = true; - } + _TCHAR path[GANA_MAX_PATH]; + GetModuleFileName(NULL, path, GANA_MAX_PATH); + _tsplitpath_s(path, NULL, 0, NULL, 0, g.m_moduleName, GANA_MAX_PATH, NULL, 0); + if (_tcsncmp(g.m_moduleName, _T("Dbgview"), sizeof(_T("Dbgview"))/sizeof(_TCHAR)) != 0 && + _tcsncmp(g.m_moduleName, _T("windbg"), sizeof(_T("windbg"))/sizeof(_TCHAR)) != 0) { + g.m_isLogging = true; + } #endif // !NDEBUG #ifdef USE_MAILSLOT - g.m_hMailslot = - CreateFile(NOTIFY_MAILSLOT_NAME, GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - (SECURITY_ATTRIBUTES *)NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); - if (g.m_hMailslot == INVALID_HANDLE_VALUE) - { - HOOK_RPT2("MAYU: %S create mailslot failed(0x%08x)\r\n", g.m_moduleName, GetLastError()); - } - else - { - HOOK_RPT1("MAYU: %S create mailslot successed\r\n", g.m_moduleName); - } + g.m_hMailslot = + CreateFile(NOTIFY_MAILSLOT_NAME, GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + (SECURITY_ATTRIBUTES *)NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); + if (g.m_hMailslot == INVALID_HANDLE_VALUE) { + HOOK_RPT2("MAYU: %S create mailslot failed(0x%08x)\r\n", g.m_moduleName, GetLastError()); + } else { + HOOK_RPT1("MAYU: %S create mailslot successed\r\n", g.m_moduleName); + } #endif //USE_MAILSLOT - if (!mapHookData()) - return false; - _tsetlocale(LC_ALL, _T("")); - g.m_WM_MAYU_MESSAGE = - RegisterWindowMessage(addSessionId(WM_MAYU_MESSAGE_NAME).c_str()); - g.m_hwndTaskTray = g_hookData->m_hwndTaskTray; - g.m_isInitialized = true; - return true; + if (!mapHookData()) + return false; + _tsetlocale(LC_ALL, _T("")); + g.m_WM_MAYU_MESSAGE = + RegisterWindowMessage(addSessionId(WM_MAYU_MESSAGE_NAME).c_str()); + g.m_hwndTaskTray = g_hookData->m_hwndTaskTray; + g.m_isInitialized = true; + return true; } /// EntryPoint BOOL WINAPI DllMain(HINSTANCE i_hInstDLL, DWORD i_fdwReason, - LPVOID /* i_lpvReserved */) + LPVOID /* i_lpvReserved */) { - switch (i_fdwReason) - { - case DLL_PROCESS_ATTACH: - { + switch (i_fdwReason) { + case DLL_PROCESS_ATTACH: { #ifndef NDEBUG - g.m_isLogging = false; + g.m_isLogging = false; #endif // !NDEBUG - g.m_isInitialized = false; - g.m_hInstDLL = i_hInstDLL; - break; - } - case DLL_THREAD_ATTACH: - break; - case DLL_PROCESS_DETACH: - notifyThreadDetach(); - unmapHookData(); + g.m_isInitialized = false; + g.m_hInstDLL = i_hInstDLL; + break; + } + case DLL_THREAD_ATTACH: + break; + case DLL_PROCESS_DETACH: + notifyThreadDetach(); + unmapHookData(); #ifdef USE_MAILSLOT - if (g.m_hMailslot != INVALID_HANDLE_VALUE) - { - CloseHandle(g.m_hMailslot); - g.m_hMailslot = INVALID_HANDLE_VALUE; - } + if (g.m_hMailslot != INVALID_HANDLE_VALUE) { + CloseHandle(g.m_hMailslot); + g.m_hMailslot = INVALID_HANDLE_VALUE; + } #endif //USE_MAILSLOT - break; - case DLL_THREAD_DETACH: - notifyThreadDetach(); - break; - default: - break; - } - return TRUE; + break; + case DLL_THREAD_DETACH: + notifyThreadDetach(); + break; + default: + break; + } + return TRUE; } /// map hook data static bool mapHookData() { - g.m_hHookData = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, - 0, sizeof(HookData), - addSessionId(HOOK_DATA_NAME).c_str()); - if (!g.m_hHookData) - { - unmapHookData(); - return false; - } - - g_hookData = - (HookData *)MapViewOfFile(g.m_hHookData, FILE_MAP_READ | FILE_MAP_WRITE, - 0, 0, sizeof(HookData)); - if (!g_hookData) - { - unmapHookData(); - return false; - } - - g.m_hHookDataArch = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, - 0, sizeof(HookDataArch), - addSessionId(HOOK_DATA_NAME_ARCH).c_str()); - if (!g.m_hHookDataArch) - { - unmapHookData(); - return false; - } - - s_hookDataArch = - (HookDataArch *)MapViewOfFile(g.m_hHookDataArch, FILE_MAP_READ | FILE_MAP_WRITE, - 0, 0, sizeof(HookDataArch)); - if (!s_hookDataArch) - { - unmapHookData(); - return false; - } - - return true; + g.m_hHookData = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, + 0, sizeof(HookData), + addSessionId(HOOK_DATA_NAME).c_str()); + if (!g.m_hHookData) { + unmapHookData(); + return false; + } + + g_hookData = + (HookData *)MapViewOfFile(g.m_hHookData, FILE_MAP_READ | FILE_MAP_WRITE, + 0, 0, sizeof(HookData)); + if (!g_hookData) { + unmapHookData(); + return false; + } + + g.m_hHookDataArch = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, + 0, sizeof(HookDataArch), + addSessionId(HOOK_DATA_NAME_ARCH).c_str()); + if (!g.m_hHookDataArch) { + unmapHookData(); + return false; + } + + s_hookDataArch = + (HookDataArch *)MapViewOfFile(g.m_hHookDataArch, FILE_MAP_READ | FILE_MAP_WRITE, + 0, 0, sizeof(HookDataArch)); + if (!s_hookDataArch) { + unmapHookData(); + return false; + } + + return true; } /// unmap hook data static void unmapHookData() { - if (g_hookData) - UnmapViewOfFile(g_hookData); - g_hookData = NULL; - if (g.m_hHookData) - CloseHandle(g.m_hHookData); - g.m_hHookData = NULL; - if (s_hookDataArch) - UnmapViewOfFile(s_hookDataArch); - s_hookDataArch = NULL; - if (g.m_hHookDataArch) - CloseHandle(g.m_hHookDataArch); - g.m_hHookDataArch = NULL; + if (g_hookData) + UnmapViewOfFile(g_hookData); + g_hookData = NULL; + if (g.m_hHookData) + CloseHandle(g.m_hHookData); + g.m_hHookData = NULL; + if (s_hookDataArch) + UnmapViewOfFile(s_hookDataArch); + s_hookDataArch = NULL; + if (g.m_hHookDataArch) + CloseHandle(g.m_hHookDataArch); + g.m_hHookDataArch = NULL; } /// notify DllExport bool notify(void *i_data, size_t i_dataSize) { - COPYDATASTRUCT cd; + COPYDATASTRUCT cd; #ifdef MAYU64 - DWORD_PTR result; + DWORD_PTR result; #else // MAYU64 - DWORD result; + DWORD result; #endif // MAYU64 #ifdef USE_MAILSLOT - DWORD len; - if (g.m_hMailslot != INVALID_HANDLE_VALUE) - { - BOOL ret; - ret = WriteFile(g.m_hMailslot, i_data, i_dataSize, &len, NULL); + DWORD len; + if (g.m_hMailslot != INVALID_HANDLE_VALUE) { + BOOL ret; + ret = WriteFile(g.m_hMailslot, i_data, i_dataSize, &len, NULL); #ifndef NDEBUG - if (ret == 0) - { - HOOK_RPT2("MAYU: %S WriteFile to mailslot failed(0x%08x)\r\n", g.m_moduleName, GetLastError()); - } - else - { - HOOK_RPT1("MAYU: %S WriteFile to mailslot successed\r\n", g.m_moduleName); - } + if (ret == 0) { + HOOK_RPT2("MAYU: %S WriteFile to mailslot failed(0x%08x)\r\n", g.m_moduleName, GetLastError()); + } else { + HOOK_RPT1("MAYU: %S WriteFile to mailslot successed\r\n", g.m_moduleName); + } #endif // !NDEBUG - } + } #else // !USE_MAILSLOT - cd.dwData = reinterpret_cast(i_data)->m_type; - cd.cbData = i_dataSize; - cd.lpData = i_data; - if (g.m_hwndTaskTray == 0) - return false; - if (!SendMessageTimeout(reinterpret_cast(g.m_hwndTaskTray), - WM_COPYDATA, NULL, reinterpret_cast(&cd), - SMTO_ABORTIFHUNG | SMTO_NORMAL, 5000, &result)) - { - _RPT0(_CRT_WARN, "MAYU: SendMessageTimeout() timeouted\r\n"); - return false; - } + cd.dwData = reinterpret_cast(i_data)->m_type; + cd.cbData = i_dataSize; + cd.lpData = i_data; + if (g.m_hwndTaskTray == 0) + return false; + if (!SendMessageTimeout(reinterpret_cast(g.m_hwndTaskTray), + WM_COPYDATA, NULL, reinterpret_cast(&cd), + SMTO_ABORTIFHUNG | SMTO_NORMAL, 5000, &result)) { + _RPT0(_CRT_WARN, "MAYU: SendMessageTimeout() timeouted\r\n"); + return false; + } #endif // !USE_MAILSLOT - return true; + return true; } /// get class name and title name -static void getClassNameTitleName(HWND i_hwnd, bool i_isInMenu, - tstringi *o_className, - tstring *o_titleName) +static void getClassNameTitleName(HWND i_hwnd, bool i_isInMenu, + tstringi *o_className, + tstring *o_titleName) { - tstringi &className = *o_className; - tstring &titleName = *o_titleName; - - bool isTheFirstTime = true; - - if (i_isInMenu) - { - className = titleName = _T("MENU"); - isTheFirstTime = false; - } - - while (true) - { - _TCHAR buf[MAX(GANA_MAX_PATH, GANA_MAX_ATOM_LENGTH)]; - - // get class name - if (i_hwnd) - GetClassName(i_hwnd, buf, NUMBER_OF(buf)); - else - GetModuleFileName(GetModuleHandle(NULL), buf, NUMBER_OF(buf)); - buf[NUMBER_OF(buf) - 1] = _T('\0'); - if (isTheFirstTime) - className = buf; - else - className = tstringi(buf) + _T(":") + className; - - // get title name - if (i_hwnd) - { - GetWindowText(i_hwnd, buf, NUMBER_OF(buf)); - buf[NUMBER_OF(buf) - 1] = _T('\0'); - for (_TCHAR *b = buf; *b; ++ b) - if (_istlead(*b) && b[1]) - b ++; - else if (_istcntrl(*b)) - *b = _T('?'); - } - if (isTheFirstTime) - titleName = buf; - else - titleName = tstring(buf) + _T(":") + titleName; - - // next loop or exit - if (!i_hwnd) - break; - i_hwnd = GetParent(i_hwnd); - isTheFirstTime = false; - } + tstringi &className = *o_className; + tstring &titleName = *o_titleName; + + bool isTheFirstTime = true; + + if (i_isInMenu) { + className = titleName = _T("MENU"); + isTheFirstTime = false; + } + + while (true) { + _TCHAR buf[MAX(GANA_MAX_PATH, GANA_MAX_ATOM_LENGTH)]; + + // get class name + if (i_hwnd) + GetClassName(i_hwnd, buf, NUMBER_OF(buf)); + else + GetModuleFileName(GetModuleHandle(NULL), buf, NUMBER_OF(buf)); + buf[NUMBER_OF(buf) - 1] = _T('\0'); + if (isTheFirstTime) + className = buf; + else + className = tstringi(buf) + _T(":") + className; + + // get title name + if (i_hwnd) { + GetWindowText(i_hwnd, buf, NUMBER_OF(buf)); + buf[NUMBER_OF(buf) - 1] = _T('\0'); + for (_TCHAR *b = buf; *b; ++ b) + if (_istlead(*b) && b[1]) + b ++; + else if (_istcntrl(*b)) + *b = _T('?'); + } + if (isTheFirstTime) + titleName = buf; + else + titleName = tstring(buf) + _T(":") + titleName; + + // next loop or exit + if (!i_hwnd) + break; + i_hwnd = GetParent(i_hwnd); + isTheFirstTime = false; + } } /// update show static void updateShow(HWND i_hwnd, NotifyShow::Show i_show) { - bool isMDI = false; + bool isMDI = false; - if (!i_hwnd) - return; + if (!i_hwnd) + return; #ifdef MAYU64 - LONG_PTR style = GetWindowLongPtr(i_hwnd, GWL_STYLE); + LONG_PTR style = GetWindowLongPtr(i_hwnd, GWL_STYLE); #else - LONG style = GetWindowLong(i_hwnd, GWL_STYLE); + LONG style = GetWindowLong(i_hwnd, GWL_STYLE); #endif - if (!(style & WS_MAXIMIZEBOX) && !(style & WS_MAXIMIZEBOX)) - return; // ignore window that has neither maximize or minimize button + if (!(style & WS_MAXIMIZEBOX) && !(style & WS_MAXIMIZEBOX)) + return; // ignore window that has neither maximize or minimize button - if (style & WS_CHILD) - { + if (style & WS_CHILD) { #ifdef MAYU64 - LONG_PTR exStyle = GetWindowLongPtr(i_hwnd, GWL_EXSTYLE); + LONG_PTR exStyle = GetWindowLongPtr(i_hwnd, GWL_EXSTYLE); #else - LONG exStyle = GetWindowLong(i_hwnd, GWL_EXSTYLE); + LONG exStyle = GetWindowLong(i_hwnd, GWL_EXSTYLE); #endif - if (exStyle & WS_EX_MDICHILD) - { - isMDI = true; - } - else - return; // ignore non-MDI child window case - } - - notifyShow(i_show, isMDI); + if (exStyle & WS_EX_MDICHILD) { + isMDI = true; + } else + return; // ignore non-MDI child window case + } + + notifyShow(i_show, isMDI); } /// notify WM_Targetted static void notifyName(HWND i_hwnd, Notify::Type i_type = Notify::Type_name) { - tstringi className; - tstring titleName; - getClassNameTitleName(i_hwnd, g.m_isInMenu, &className, &titleName); - - NotifySetFocus *nfc = new NotifySetFocus; - nfc->m_type = i_type; - nfc->m_threadId = GetCurrentThreadId(); - nfc->m_hwnd = reinterpret_cast(i_hwnd); - tcslcpy(nfc->m_className, className.c_str(), NUMBER_OF(nfc->m_className)); - tcslcpy(nfc->m_titleName, titleName.c_str(), NUMBER_OF(nfc->m_titleName)); - - notify(nfc, sizeof(*nfc)); - delete nfc; + tstringi className; + tstring titleName; + getClassNameTitleName(i_hwnd, g.m_isInMenu, &className, &titleName); + + NotifySetFocus *nfc = new NotifySetFocus; + nfc->m_type = i_type; + nfc->m_threadId = GetCurrentThreadId(); + nfc->m_hwnd = reinterpret_cast(i_hwnd); + tcslcpy(nfc->m_className, className.c_str(), NUMBER_OF(nfc->m_className)); + tcslcpy(nfc->m_titleName, titleName.c_str(), NUMBER_OF(nfc->m_titleName)); + + notify(nfc, sizeof(*nfc)); + delete nfc; } /// notify WM_SETFOCUS static void notifySetFocus(bool i_doesForce = false) { - HWND hwnd = GetFocus(); - if (i_doesForce || hwnd != g.m_hwndFocus) - { - g.m_hwndFocus = hwnd; - notifyName(hwnd, Notify::Type_setFocus); - } + HWND hwnd = GetFocus(); + if (i_doesForce || hwnd != g.m_hwndFocus) { + g.m_hwndFocus = hwnd; + notifyName(hwnd, Notify::Type_setFocus); + } } /// notify sync static void notifySync() { - Notify n; - n.m_type = Notify::Type_sync; - notify(&n, sizeof(n)); + Notify n; + n.m_type = Notify::Type_sync; + notify(&n, sizeof(n)); } /// notify DLL_THREAD_DETACH static void notifyThreadDetach() { - NotifyThreadDetach ntd; - ntd.m_type = Notify::Type_threadDetach; - ntd.m_threadId = GetCurrentThreadId(); - notify(&ntd, sizeof(ntd)); + NotifyThreadDetach ntd; + ntd.m_type = Notify::Type_threadDetach; + ntd.m_threadId = GetCurrentThreadId(); + notify(&ntd, sizeof(ntd)); } /// notify WM_COMMAND, WM_SYSCOMMAND static void notifyCommand( - HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam) + HWND i_hwnd, UINT i_message, WPARAM i_wParam, LPARAM i_lParam) { #ifndef _WIN64 - if (g_hookData->m_doesNotifyCommand) - { - NotifyCommand ntc; - ntc.m_type = Notify::Type_command; - ntc.m_hwnd = i_hwnd; - ntc.m_message = i_message; - ntc.m_wParam = i_wParam; - ntc.m_lParam = i_lParam; - notify(&ntc, sizeof(ntc)); - } + if (g_hookData->m_doesNotifyCommand) { + NotifyCommand ntc; + ntc.m_type = Notify::Type_command; + ntc.m_hwnd = i_hwnd; + ntc.m_message = i_message; + ntc.m_wParam = i_wParam; + ntc.m_lParam = i_lParam; + notify(&ntc, sizeof(ntc)); + } #endif } @@ -442,430 +417,411 @@ static void notifyCommand( /// notify show of current window static void notifyShow(NotifyShow::Show i_show, bool i_isMDI) { - NotifyShow ns; - ns.m_type = Notify::Type_show; - ns.m_show = i_show; - ns.m_isMDI = i_isMDI; - notify(&ns, sizeof(ns)); + NotifyShow ns; + ns.m_type = Notify::Type_show; + ns.m_show = i_show; + ns.m_isMDI = i_isMDI; + notify(&ns, sizeof(ns)); } /// notify log static void notifyLog(_TCHAR *i_msg) { - NotifyLog nl; - nl.m_type = Notify::Type_log; - tcslcpy(nl.m_msg, i_msg, NUMBER_OF(nl.m_msg)); - notify(&nl, sizeof(nl)); + NotifyLog nl; + nl.m_type = Notify::Type_log; + tcslcpy(nl.m_msg, i_msg, NUMBER_OF(nl.m_msg)); + notify(&nl, sizeof(nl)); } /// &Recenter static void funcRecenter(HWND i_hwnd) { - _TCHAR buf[MAX(GANA_MAX_PATH, GANA_MAX_ATOM_LENGTH)]; - GetClassName(i_hwnd, buf, NUMBER_OF(buf)); - bool isEdit; - if (_tcsicmp(buf, _T("Edit")) == 0) - isEdit = true; - else if (_tcsnicmp(buf, _T("RichEdit"), 8) == 0) - isEdit = false; - else - return; // this function only works for Edit control + _TCHAR buf[MAX(GANA_MAX_PATH, GANA_MAX_ATOM_LENGTH)]; + GetClassName(i_hwnd, buf, NUMBER_OF(buf)); + bool isEdit; + if (_tcsicmp(buf, _T("Edit")) == 0) + isEdit = true; + else if (_tcsnicmp(buf, _T("RichEdit"), 8) == 0) + isEdit = false; + else + return; // this function only works for Edit control #ifdef MAYU64 - LONG_PTR style = GetWindowLongPtr(i_hwnd, GWL_STYLE); + LONG_PTR style = GetWindowLongPtr(i_hwnd, GWL_STYLE); #else - LONG style = GetWindowLong(i_hwnd, GWL_STYLE); + LONG style = GetWindowLong(i_hwnd, GWL_STYLE); #endif - if (!(style & ES_MULTILINE)) - return; // this function only works for multi line Edit control - - RECT rc; - GetClientRect(i_hwnd, &rc); - POINTL p = { (rc.right + rc.left) / 2, (rc.top + rc.bottom) / 2 }; - int line; - if (isEdit) - { - line = SendMessage(i_hwnd, EM_CHARFROMPOS, 0, MAKELPARAM(p.x, p.y)); - line = HIWORD(line); - } - else - { - int ci = SendMessage(i_hwnd, EM_CHARFROMPOS, 0, (LPARAM)&p); - line = SendMessage(i_hwnd, EM_EXLINEFROMCHAR, 0, ci); - } - int caretLine = SendMessage(i_hwnd, EM_LINEFROMCHAR, -1, 0); - SendMessage(i_hwnd, EM_LINESCROLL, 0, caretLine - line); + if (!(style & ES_MULTILINE)) + return; // this function only works for multi line Edit control + + RECT rc; + GetClientRect(i_hwnd, &rc); + POINTL p = { (rc.right + rc.left) / 2, (rc.top + rc.bottom) / 2 }; + int line; + if (isEdit) { + line = SendMessage(i_hwnd, EM_CHARFROMPOS, 0, MAKELPARAM(p.x, p.y)); + line = HIWORD(line); + } else { + int ci = SendMessage(i_hwnd, EM_CHARFROMPOS, 0, (LPARAM)&p); + line = SendMessage(i_hwnd, EM_EXLINEFROMCHAR, 0, ci); + } + int caretLine = SendMessage(i_hwnd, EM_LINEFROMCHAR, -1, 0); + SendMessage(i_hwnd, EM_LINESCROLL, 0, caretLine - line); } // &SetImeStatus static void funcSetImeStatus(HWND i_hwnd, int i_status) { - HIMC hIMC; + HIMC hIMC; - hIMC = ImmGetContext(i_hwnd); - if (hIMC == INVALID_HANDLE_VALUE) - return; + hIMC = ImmGetContext(i_hwnd); + if (hIMC == INVALID_HANDLE_VALUE) + return; - if (i_status < 0) - i_status = !ImmGetOpenStatus(hIMC); + if (i_status < 0) + i_status = !ImmGetOpenStatus(hIMC); - ImmSetOpenStatus(hIMC, i_status); - ImmReleaseContext(i_hwnd, hIMC); + ImmSetOpenStatus(hIMC, i_status); + ImmReleaseContext(i_hwnd, hIMC); } // &SetImeString static void funcSetImeString(HWND i_hwnd, int i_size) { - _TCHAR *buf = new _TCHAR(i_size); - DWORD len = 0; - _TCHAR ImeDesc[GANA_MAX_ATOM_LENGTH]; - UINT ImeDescLen; - DWORD error; - DWORD denom = 1; - HANDLE hPipe - = CreateFile(addSessionId(HOOK_PIPE_NAME).c_str(), GENERIC_READ, - FILE_SHARE_READ, (SECURITY_ATTRIBUTES *)NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); - error = ReadFile(hPipe, buf, i_size, &len, NULL); - CloseHandle(hPipe); - - ImeDescLen = ImmGetDescription(GetKeyboardLayout(0), - ImeDesc, sizeof(ImeDesc)); - if (_tcsncmp(ImeDesc, _T("SKKIME"), ImeDescLen) > 0) - denom = sizeof(_TCHAR); - - HIMC hIMC = ImmGetContext(i_hwnd); - if (hIMC == INVALID_HANDLE_VALUE) - return; - - int status = ImmGetOpenStatus(hIMC); - ImmSetCompositionString(hIMC, SCS_SETSTR, buf, len / denom, NULL, 0); - delete buf; - ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_COMPLETE, 0); - if (!status) - ImmSetOpenStatus(hIMC, status); - ImmReleaseContext(i_hwnd, hIMC); + _TCHAR *buf = new _TCHAR(i_size); + DWORD len = 0; + _TCHAR ImeDesc[GANA_MAX_ATOM_LENGTH]; + UINT ImeDescLen; + DWORD error; + DWORD denom = 1; + HANDLE hPipe + = CreateFile(addSessionId(HOOK_PIPE_NAME).c_str(), GENERIC_READ, + FILE_SHARE_READ, (SECURITY_ATTRIBUTES *)NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); + error = ReadFile(hPipe, buf, i_size, &len, NULL); + CloseHandle(hPipe); + + ImeDescLen = ImmGetDescription(GetKeyboardLayout(0), + ImeDesc, sizeof(ImeDesc)); + if (_tcsncmp(ImeDesc, _T("SKKIME"), ImeDescLen) > 0) + denom = sizeof(_TCHAR); + + HIMC hIMC = ImmGetContext(i_hwnd); + if (hIMC == INVALID_HANDLE_VALUE) + return; + + int status = ImmGetOpenStatus(hIMC); + ImmSetCompositionString(hIMC, SCS_SETSTR, buf, len / denom, NULL, 0); + delete buf; + ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_COMPLETE, 0); + if (!status) + ImmSetOpenStatus(hIMC, status); + ImmReleaseContext(i_hwnd, hIMC); } /// notify lock state -/*DllExport*/ void notifyLockState(int i_cause) +/*DllExport*/ +void notifyLockState(int i_cause) { - NotifyLockState n; - n.m_type = Notify::Type_lockState; - n.m_isNumLockToggled = !!(GetKeyState(VK_NUMLOCK) & 1); - n.m_isCapsLockToggled = !!(GetKeyState(VK_CAPITAL) & 1); - n.m_isScrollLockToggled = !!(GetKeyState(VK_SCROLL) & 1); - n.m_isKanaLockToggled = !!(GetKeyState(VK_KANA) & 1); - n.m_isImeLockToggled = g.m_isImeLock; - n.m_isImeCompToggled = g.m_isImeCompositioning; - n.m_debugParam = i_cause; - notify(&n, sizeof(n)); + NotifyLockState n; + n.m_type = Notify::Type_lockState; + n.m_isNumLockToggled = !!(GetKeyState(VK_NUMLOCK) & 1); + n.m_isCapsLockToggled = !!(GetKeyState(VK_CAPITAL) & 1); + n.m_isScrollLockToggled = !!(GetKeyState(VK_SCROLL) & 1); + n.m_isKanaLockToggled = !!(GetKeyState(VK_KANA) & 1); + n.m_isImeLockToggled = g.m_isImeLock; + n.m_isImeCompToggled = g.m_isImeCompositioning; + n.m_debugParam = i_cause; + notify(&n, sizeof(n)); } DllExport void notifyLockState() { - notifyLockState(9); + notifyLockState(9); } /// hook of GetMessage LRESULT CALLBACK getMessageProc(int i_nCode, WPARAM i_wParam, LPARAM i_lParam) { - if (!g.m_isInitialized) - initialize(); - - if (!g_hookData) - return 0; - - MSG &msg = (*(MSG *)i_lParam); - - if (i_wParam != PM_REMOVE) - goto finally; - - switch (msg.message) - { - case WM_COMMAND: - case WM_SYSCOMMAND: - notifyCommand(msg.hwnd, msg.message, msg.wParam, msg.lParam); - break; - case WM_KEYDOWN: - case WM_KEYUP: - case WM_SYSKEYDOWN: - case WM_SYSKEYUP: - { - if (HIMC hIMC = ImmGetContext(msg.hwnd)) - { - bool prev = g.m_isImeLock; - g.m_isImeLock = !!ImmGetOpenStatus(hIMC); - ImmReleaseContext(msg.hwnd, hIMC); - if (prev != g.m_isImeLock) { - notifyLockState(1); + if (!g.m_isInitialized) + initialize(); + + if (!g_hookData) + return 0; + + MSG &msg = (*(MSG *)i_lParam); + + if (i_wParam != PM_REMOVE) + goto finally; + + switch (msg.message) { + case WM_COMMAND: + case WM_SYSCOMMAND: + notifyCommand(msg.hwnd, msg.message, msg.wParam, msg.lParam); + break; + case WM_KEYDOWN: + case WM_KEYUP: + case WM_SYSKEYDOWN: + case WM_SYSKEYUP: { + if (HIMC hIMC = ImmGetContext(msg.hwnd)) { + bool prev = g.m_isImeLock; + g.m_isImeLock = !!ImmGetOpenStatus(hIMC); + ImmReleaseContext(msg.hwnd, hIMC); + if (prev != g.m_isImeLock) { + notifyLockState(1); + } + } + int nVirtKey = (int)msg.wParam; + // int repeatCount = (msg.lParam & 0xffff); + BYTE scanCode = (BYTE)((msg.lParam >> 16) & 0xff); + bool isExtended = !!(msg.lParam & (1 << 24)); + // bool isAltDown = !!(msg.lParam & (1 << 29)); + // bool isKeyup = !!(msg.lParam & (1 << 31)); + + if (nVirtKey == VK_CAPITAL || + nVirtKey == VK_NUMLOCK || + nVirtKey == VK_KANA || + nVirtKey == VK_SCROLL) + notifyLockState(2); + else if (scanCode == g_hookData->m_syncKey && + isExtended == g_hookData->m_syncKeyIsExtended) + notifySync(); + break; } - } - int nVirtKey = (int)msg.wParam; - // int repeatCount = (msg.lParam & 0xffff); - BYTE scanCode = (BYTE)((msg.lParam >> 16) & 0xff); - bool isExtended = !!(msg.lParam & (1 << 24)); - // bool isAltDown = !!(msg.lParam & (1 << 29)); - // bool isKeyup = !!(msg.lParam & (1 << 31)); - - if (nVirtKey == VK_CAPITAL || - nVirtKey == VK_NUMLOCK || - nVirtKey == VK_KANA || - nVirtKey == VK_SCROLL) - notifyLockState(2); - else if (scanCode == g_hookData->m_syncKey && - isExtended == g_hookData->m_syncKeyIsExtended) - notifySync(); - break; - } - case WM_IME_STARTCOMPOSITION: - g.m_isImeCompositioning = true; - notifyLockState(3); - break; - case WM_IME_ENDCOMPOSITION: - g.m_isImeCompositioning = false; - notifyLockState(4); - break; - default: - if (i_wParam == PM_REMOVE && msg.message == g.m_WM_MAYU_MESSAGE) - { - switch (msg.wParam) - { - case MayuMessage_notifyName: - notifyName(msg.hwnd); - break; - case MayuMessage_funcRecenter: - funcRecenter(msg.hwnd); - break; - case MayuMessage_funcSetImeStatus: - funcSetImeStatus(msg.hwnd, msg.lParam); - break; - case MayuMessage_funcSetImeString: - funcSetImeString(msg.hwnd, msg.lParam); - break; + case WM_IME_STARTCOMPOSITION: + g.m_isImeCompositioning = true; + notifyLockState(3); + break; + case WM_IME_ENDCOMPOSITION: + g.m_isImeCompositioning = false; + notifyLockState(4); + break; + default: + if (i_wParam == PM_REMOVE && msg.message == g.m_WM_MAYU_MESSAGE) { + switch (msg.wParam) { + case MayuMessage_notifyName: + notifyName(msg.hwnd); + break; + case MayuMessage_funcRecenter: + funcRecenter(msg.hwnd); + break; + case MayuMessage_funcSetImeStatus: + funcSetImeStatus(msg.hwnd, msg.lParam); + break; + case MayuMessage_funcSetImeString: + funcSetImeString(msg.hwnd, msg.lParam); + break; + } + } + break; } - } - break; - } - finally: - return CallNextHookEx(s_hookDataArch->m_hHookGetMessage, - i_nCode, i_wParam, i_lParam); +finally: + return CallNextHookEx(s_hookDataArch->m_hHookGetMessage, + i_nCode, i_wParam, i_lParam); } /// hook of SendMessage LRESULT CALLBACK callWndProc(int i_nCode, WPARAM i_wParam, LPARAM i_lParam) { - if (!g.m_isInitialized) - initialize(); - - if (!g_hookData) - return 0; - - CWPSTRUCT &cwps = *(CWPSTRUCT *)i_lParam; - - if (0 <= i_nCode) - { - switch (cwps.message) - { - case WM_ACTIVATEAPP: - case WM_NCACTIVATE: - if (i_wParam) - notifySetFocus(); - break; - case WM_SYSCOMMAND: - switch (cwps.wParam) - { - case SC_MAXIMIZE: - case SC_MAXIMIZE2: - updateShow(cwps.hwnd, NotifyShow::Show_Maximized); - break; - case SC_MINIMIZE: - case SC_MINIMIZE2: - updateShow(cwps.hwnd, NotifyShow::Show_Minimized); - break; - case SC_RESTORE: - case SC_RESTORE2: - updateShow(cwps.hwnd, NotifyShow::Show_Normal); - break; - default: - break; - } - /* through below */ - case WM_COMMAND: - notifyCommand(cwps.hwnd, cwps.message, cwps.wParam, cwps.lParam); - break; - case WM_SIZE: - switch (cwps.wParam) - { - case SIZE_MAXIMIZED: - updateShow(cwps.hwnd, NotifyShow::Show_Maximized); - break; - case SIZE_MINIMIZED: - updateShow(cwps.hwnd, NotifyShow::Show_Minimized); - break; - case SIZE_RESTORED: - updateShow(cwps.hwnd, NotifyShow::Show_Normal); - break; - default: - break; - } - break; - case WM_MOUSEACTIVATE: - notifySetFocus(); - break; - case WM_ACTIVATE: - if (LOWORD(cwps.wParam) != WA_INACTIVE) - { - notifySetFocus(); - if (HIWORD(cwps.wParam)) // check minimized flag - { - // minimized flag on - notifyShow(NotifyShow::Show_Minimized, false); - //notifyShow(NotifyShow::Show_Normal, true); - } + if (!g.m_isInitialized) + initialize(); + + if (!g_hookData) + return 0; + + CWPSTRUCT &cwps = *(CWPSTRUCT *)i_lParam; + + if (0 <= i_nCode) { + switch (cwps.message) { + case WM_ACTIVATEAPP: + case WM_NCACTIVATE: + if (i_wParam) + notifySetFocus(); + break; + case WM_SYSCOMMAND: + switch (cwps.wParam) { + case SC_MAXIMIZE: + case SC_MAXIMIZE2: + updateShow(cwps.hwnd, NotifyShow::Show_Maximized); + break; + case SC_MINIMIZE: + case SC_MINIMIZE2: + updateShow(cwps.hwnd, NotifyShow::Show_Minimized); + break; + case SC_RESTORE: + case SC_RESTORE2: + updateShow(cwps.hwnd, NotifyShow::Show_Normal); + break; + default: + break; + } + /* through below */ + case WM_COMMAND: + notifyCommand(cwps.hwnd, cwps.message, cwps.wParam, cwps.lParam); + break; + case WM_SIZE: + switch (cwps.wParam) { + case SIZE_MAXIMIZED: + updateShow(cwps.hwnd, NotifyShow::Show_Maximized); + break; + case SIZE_MINIMIZED: + updateShow(cwps.hwnd, NotifyShow::Show_Minimized); + break; + case SIZE_RESTORED: + updateShow(cwps.hwnd, NotifyShow::Show_Normal); + break; + default: + break; + } + break; + case WM_MOUSEACTIVATE: + notifySetFocus(); + break; + case WM_ACTIVATE: + if (LOWORD(cwps.wParam) != WA_INACTIVE) { + notifySetFocus(); + if (HIWORD(cwps.wParam)) { // check minimized flag + // minimized flag on + notifyShow(NotifyShow::Show_Minimized, false); + //notifyShow(NotifyShow::Show_Normal, true); + } + } + break; + case WM_ENTERMENULOOP: + g.m_isInMenu = true; + notifySetFocus(true); + break; + case WM_EXITMENULOOP: + g.m_isInMenu = false; + notifySetFocus(true); + break; + case WM_SETFOCUS: + g.m_isInMenu = false; + // for kana + if (g_hookData->m_correctKanaLockHandling) { + if (HIMC hIMC = ImmGetContext(cwps.hwnd)) { + bool status = !!ImmGetOpenStatus(hIMC); + // this code set the VK_KANA state correctly. + ImmSetOpenStatus(hIMC, !status); + ImmSetOpenStatus(hIMC, status); + ImmReleaseContext(cwps.hwnd, hIMC); + } + } + notifySetFocus(); + notifyLockState(5); + break; + case WM_IME_STARTCOMPOSITION: + g.m_isImeCompositioning = true; + notifyLockState(6); + break; + case WM_IME_ENDCOMPOSITION: + g.m_isImeCompositioning = false; + notifyLockState(7); + break; + case WM_IME_NOTIFY: + if (cwps.wParam == IMN_SETOPENSTATUS) + if (HIMC hIMC = ImmGetContext(cwps.hwnd)) { + g.m_isImeLock = !!ImmGetOpenStatus(hIMC); + ImmReleaseContext(cwps.hwnd, hIMC); + notifyLockState(8); + } + break; + } } - break; - case WM_ENTERMENULOOP: - g.m_isInMenu = true; - notifySetFocus(true); - break; - case WM_EXITMENULOOP: - g.m_isInMenu = false; - notifySetFocus(true); - break; - case WM_SETFOCUS: - g.m_isInMenu = false; - // for kana - if (g_hookData->m_correctKanaLockHandling) { - if (HIMC hIMC = ImmGetContext(cwps.hwnd)) { - bool status = !!ImmGetOpenStatus(hIMC); - // this code set the VK_KANA state correctly. - ImmSetOpenStatus(hIMC, !status); - ImmSetOpenStatus(hIMC, status); - ImmReleaseContext(cwps.hwnd, hIMC); - } - } - notifySetFocus(); - notifyLockState(5); - break; - case WM_IME_STARTCOMPOSITION: - g.m_isImeCompositioning = true; - notifyLockState(6); - break; - case WM_IME_ENDCOMPOSITION: - g.m_isImeCompositioning = false; - notifyLockState(7); - break; - case WM_IME_NOTIFY: - if (cwps.wParam == IMN_SETOPENSTATUS) - if (HIMC hIMC = ImmGetContext(cwps.hwnd)) - { - g.m_isImeLock = !!ImmGetOpenStatus(hIMC); - ImmReleaseContext(cwps.hwnd, hIMC); - notifyLockState(8); - } - break; - } - } - return CallNextHookEx(s_hookDataArch->m_hHookCallWndProc, i_nCode, - i_wParam, i_lParam); + return CallNextHookEx(s_hookDataArch->m_hHookCallWndProc, i_nCode, + i_wParam, i_lParam); } static LRESULT CALLBACK lowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) { - MSLLHOOKSTRUCT *pMsll = (MSLLHOOKSTRUCT*)lParam; - LONG dx = pMsll->pt.x - g_hookData->m_mousePos.x; - LONG dy = pMsll->pt.y - g_hookData->m_mousePos.y; - HWND target = reinterpret_cast(g_hookData->m_hwndMouseHookTarget); - - if (!g.m_isInitialized) - initialize(); - - if (!g_hookData || nCode < 0 || wParam != WM_MOUSEMOVE) - goto through; - - switch (g_hookData->m_mouseHookType) - { - case MouseHookType_Wheel: - // For this type, g_hookData->m_mouseHookParam means - // translate rate mouse move to wheel. - mouse_event(MOUSEEVENTF_WHEEL, 0, 0, - g_hookData->m_mouseHookParam * dy, 0); - return 1; - break; - case MouseHookType_WindowMove: - { - RECT curRect; - - if (!GetWindowRect(target, &curRect)) - goto through; - - // g_hookData->m_mouseHookParam < 0 means - // target window to move is MDI. - if (g_hookData->m_mouseHookParam < 0) - { - HWND parent = GetParent(target); - POINT p = {curRect.left, curRect.top}; - - if (parent == NULL || !ScreenToClient(parent, &p)) - goto through; - - curRect.left = p.x; - curRect.top = p.y; - } - - SetWindowPos(target, NULL, - curRect.left + dx, - curRect.top + dy, - 0, 0, - SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | - SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER); - g_hookData->m_mousePos = pMsll->pt; - goto through; - break; - } - case MouseHookType_None: - default: - goto through; - break; - } - - through: - return CallNextHookEx(g.m_hHookMouseProc, - nCode, wParam, lParam); + MSLLHOOKSTRUCT *pMsll = (MSLLHOOKSTRUCT*)lParam; + LONG dx = pMsll->pt.x - g_hookData->m_mousePos.x; + LONG dy = pMsll->pt.y - g_hookData->m_mousePos.y; + HWND target = reinterpret_cast(g_hookData->m_hwndMouseHookTarget); + + if (!g.m_isInitialized) + initialize(); + + if (!g_hookData || nCode < 0 || wParam != WM_MOUSEMOVE) + goto through; + + switch (g_hookData->m_mouseHookType) { + case MouseHookType_Wheel: + // For this type, g_hookData->m_mouseHookParam means + // translate rate mouse move to wheel. + mouse_event(MOUSEEVENTF_WHEEL, 0, 0, + g_hookData->m_mouseHookParam * dy, 0); + return 1; + break; + case MouseHookType_WindowMove: { + RECT curRect; + + if (!GetWindowRect(target, &curRect)) + goto through; + + // g_hookData->m_mouseHookParam < 0 means + // target window to move is MDI. + if (g_hookData->m_mouseHookParam < 0) { + HWND parent = GetParent(target); + POINT p = {curRect.left, curRect.top}; + + if (parent == NULL || !ScreenToClient(parent, &p)) + goto through; + + curRect.left = p.x; + curRect.top = p.y; + } + + SetWindowPos(target, NULL, + curRect.left + dx, + curRect.top + dy, + 0, 0, + SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | + SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER); + g_hookData->m_mousePos = pMsll->pt; + goto through; + break; + } + case MouseHookType_None: + default: + goto through; + break; + } + +through: + return CallNextHookEx(g.m_hHookMouseProc, + nCode, wParam, lParam); } #ifdef NO_DRIVER static LRESULT CALLBACK lowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) { - KBDLLHOOKSTRUCT *pKbll = (KBDLLHOOKSTRUCT*)lParam; - - if (!g.m_isInitialized) - initialize(); - - if (!g_hookData || nCode < 0) - goto through; - - if (g.m_keyboardDetour && g.m_engine) - { - unsigned int result; - result = g.m_keyboardDetour(g.m_engine, pKbll); - if (result) - { - return 1; - } - } - through: - return CallNextHookEx(g.m_hHookKeyboardProc, - nCode, wParam, lParam); + KBDLLHOOKSTRUCT *pKbll = (KBDLLHOOKSTRUCT*)lParam; + + if (!g.m_isInitialized) + initialize(); + + if (!g_hookData || nCode < 0) + goto through; + + if (g.m_keyboardDetour && g.m_engine) { + unsigned int result; + result = g.m_keyboardDetour(g.m_engine, pKbll); + if (result) { + return 1; + } + } +through: + return CallNextHookEx(g.m_hHookKeyboardProc, + nCode, wParam, lParam); } #endif // NO_DRIVER @@ -873,50 +829,49 @@ static LRESULT CALLBACK lowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lP /// install hooks DllExport int installHooks(KEYBOARD_DETOUR i_keyboardDetour, Engine *i_engine) { - if (!g.m_isInitialized) - initialize(); - - g.m_hwndTaskTray = g_hookData->m_hwndTaskTray; - s_hookDataArch->m_hHookGetMessage = - SetWindowsHookEx(WH_GETMESSAGE, (HOOKPROC)getMessageProc, - g.m_hInstDLL, 0); - s_hookDataArch->m_hHookCallWndProc = - SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)callWndProc, g.m_hInstDLL, 0); - g_hookData->m_mouseHookType = MouseHookType_None; - if (i_engine != NULL) - { + if (!g.m_isInitialized) + initialize(); + + g.m_hwndTaskTray = g_hookData->m_hwndTaskTray; + s_hookDataArch->m_hHookGetMessage = + SetWindowsHookEx(WH_GETMESSAGE, (HOOKPROC)getMessageProc, + g.m_hInstDLL, 0); + s_hookDataArch->m_hHookCallWndProc = + SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)callWndProc, g.m_hInstDLL, 0); + g_hookData->m_mouseHookType = MouseHookType_None; + if (i_engine != NULL) { #ifdef NO_DRIVER - g.m_keyboardDetour = i_keyboardDetour; - g.m_engine = i_engine; - g.m_hHookKeyboardProc = - SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)lowLevelKeyboardProc, - g.m_hInstDLL, 0); + g.m_keyboardDetour = i_keyboardDetour; + g.m_engine = i_engine; + g.m_hHookKeyboardProc = + SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)lowLevelKeyboardProc, + g.m_hInstDLL, 0); #endif // NO_DRIVER - g.m_hHookMouseProc = - SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)lowLevelMouseProc, - g.m_hInstDLL, 0); - } - return 0; + g.m_hHookMouseProc = + SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)lowLevelMouseProc, + g.m_hInstDLL, 0); + } + return 0; } /// uninstall hooks DllExport int uninstallHooks() { - if (s_hookDataArch->m_hHookGetMessage) - UnhookWindowsHookEx(s_hookDataArch->m_hHookGetMessage); - s_hookDataArch->m_hHookGetMessage = NULL; - if (s_hookDataArch->m_hHookCallWndProc) - UnhookWindowsHookEx(s_hookDataArch->m_hHookCallWndProc); - s_hookDataArch->m_hHookCallWndProc = NULL; - if (g.m_hHookMouseProc) - UnhookWindowsHookEx(g.m_hHookMouseProc); - g.m_hHookMouseProc = NULL; + if (s_hookDataArch->m_hHookGetMessage) + UnhookWindowsHookEx(s_hookDataArch->m_hHookGetMessage); + s_hookDataArch->m_hHookGetMessage = NULL; + if (s_hookDataArch->m_hHookCallWndProc) + UnhookWindowsHookEx(s_hookDataArch->m_hHookCallWndProc); + s_hookDataArch->m_hHookCallWndProc = NULL; + if (g.m_hHookMouseProc) + UnhookWindowsHookEx(g.m_hHookMouseProc); + g.m_hHookMouseProc = NULL; #ifdef NO_DRIVER - if (g.m_hHookKeyboardProc) - UnhookWindowsHookEx(g.m_hHookKeyboardProc); - g.m_hHookKeyboardProc = NULL; + if (g.m_hHookKeyboardProc) + UnhookWindowsHookEx(g.m_hHookKeyboardProc); + g.m_hHookKeyboardProc = NULL; #endif // NO_DRIVER - g.m_hwndTaskTray = 0; - return 0; + g.m_hwndTaskTray = 0; + return 0; } diff --git a/hook.h b/hook.h index a3e1401..28d7e6e 100644 --- a/hook.h +++ b/hook.h @@ -23,108 +23,96 @@ _T("\\\\.\\mailslot\\GANAware\\mayu\\{330F7914-EB5B-49be-ACCE-D2B8DF585B32}") _T # define WM_MAYU_MESSAGE_NAME _T("GANAware\\mayu\\WM_MAYU_MESSAGE") /// -enum MayuMessage -{ - MayuMessage_notifyName, - MayuMessage_funcRecenter, - MayuMessage_funcSetImeStatus, - MayuMessage_funcSetImeString, +enum MayuMessage { + MayuMessage_notifyName, + MayuMessage_funcRecenter, + MayuMessage_funcSetImeStatus, + MayuMessage_funcSetImeString, }; /// -struct Notify -{ - /// - enum Type - { - Type_setFocus, /// NotifySetFocus - Type_name, /// NotifySetFocus - Type_lockState, /// NotifyLockState - Type_sync, /// Notify - Type_threadDetach, /// NotifyThreadDetach - Type_command, /// NotifyThreadDetach - Type_show, /// NotifyShow - Type_log, /// NotifyLog - }; - Type m_type; /// - DWORD m_debugParam; /// (for debug) +struct Notify { + /// + enum Type { + Type_setFocus, /// NotifySetFocus + Type_name, /// NotifySetFocus + Type_lockState, /// NotifyLockState + Type_sync, /// Notify + Type_threadDetach, /// NotifyThreadDetach + Type_command, /// NotifyThreadDetach + Type_show, /// NotifyShow + Type_log, /// NotifyLog + }; + Type m_type; /// + DWORD m_debugParam; /// (for debug) }; /// -struct NotifySetFocus : public Notify -{ - DWORD m_threadId; /// - DWORD m_hwnd; /// - _TCHAR m_className[GANA_MAX_PATH]; /// - _TCHAR m_titleName[GANA_MAX_PATH]; /// +struct NotifySetFocus : public Notify { + DWORD m_threadId; /// + DWORD m_hwnd; /// + _TCHAR m_className[GANA_MAX_PATH]; /// + _TCHAR m_titleName[GANA_MAX_PATH]; /// }; /// -struct NotifyLockState : public Notify -{ - bool m_isNumLockToggled; /// - bool m_isCapsLockToggled; /// - bool m_isScrollLockToggled; /// - bool m_isKanaLockToggled; /// - bool m_isImeLockToggled; /// - bool m_isImeCompToggled; /// +struct NotifyLockState : public Notify { + bool m_isNumLockToggled; /// + bool m_isCapsLockToggled; /// + bool m_isScrollLockToggled; /// + bool m_isKanaLockToggled; /// + bool m_isImeLockToggled; /// + bool m_isImeCompToggled; /// }; /// -struct NotifyThreadDetach : public Notify -{ - DWORD m_threadId; /// +struct NotifyThreadDetach : public Notify { + DWORD m_threadId; /// }; /// -struct NotifyCommand : public Notify -{ - HWND m_hwnd; /// - UINT m_message; /// - WPARAM m_wParam; /// - LPARAM m_lParam; /// +struct NotifyCommand : public Notify { + HWND m_hwnd; /// + UINT m_message; /// + WPARAM m_wParam; /// + LPARAM m_lParam; /// }; -enum -{ - NOTIFY_MESSAGE_SIZE = sizeof(NotifySetFocus), /// +enum { + NOTIFY_MESSAGE_SIZE = sizeof(NotifySetFocus), /// }; /// -struct NotifyShow : public Notify -{ - /// - enum Show - { - Show_Normal, - Show_Maximized, - Show_Minimized, - }; - Show m_show; /// - bool m_isMDI; /// +struct NotifyShow : public Notify { + /// + enum Show { + Show_Normal, + Show_Maximized, + Show_Minimized, + }; + Show m_show; /// + bool m_isMDI; /// }; /// -struct NotifyLog : public Notify -{ - _TCHAR m_msg[GANA_MAX_PATH]; /// +struct NotifyLog : public Notify { + _TCHAR m_msg[GANA_MAX_PATH]; /// }; /// -enum MouseHookType -{ - MouseHookType_None = 0, /// none - MouseHookType_Wheel = 1 << 0, /// wheel - MouseHookType_WindowMove = 1 << 1, /// window move +enum MouseHookType { + MouseHookType_None = 0, /// none + MouseHookType_Wheel = 1 << 0, /// wheel + MouseHookType_WindowMove = 1 << 1, /// window move }; #ifdef NO_DRIVER @@ -136,15 +124,15 @@ typedef unsigned int (WINAPI *KEYBOARD_DETOUR)(Engine *i_engine, KBDLLHOOKSTRUCT class HookData { public: - USHORT m_syncKey; /// - bool m_syncKeyIsExtended; /// - bool m_doesNotifyCommand; /// - DWORD m_hwndTaskTray; /// - bool m_correctKanaLockHandling; /// does use KL- ? - MouseHookType m_mouseHookType; /// - int m_mouseHookParam; /// - DWORD m_hwndMouseHookTarget; /// - POINT m_mousePos; /// + USHORT m_syncKey; /// + bool m_syncKeyIsExtended; /// + bool m_doesNotifyCommand; /// + DWORD m_hwndTaskTray; /// + bool m_correctKanaLockHandling; /// does use KL- ? + MouseHookType m_mouseHookType; /// + int m_mouseHookParam; /// + DWORD m_hwndMouseHookTarget; /// + POINT m_mousePos; /// }; diff --git a/keyboard.cpp b/keyboard.cpp index d4089a1..c7aa8e4 100644 --- a/keyboard.cpp +++ b/keyboard.cpp @@ -14,60 +14,60 @@ // add a name or an alias of key void Key::addName(const tstringi &i_name) { - m_names.push_back(i_name); + m_names.push_back(i_name); } // add a scan code void Key::addScanCode(const ScanCode &i_sc) { - ASSERT(m_scanCodesSize < MAX_SCAN_CODES_SIZE); - m_scanCodes[m_scanCodesSize ++] = i_sc; + ASSERT(m_scanCodesSize < MAX_SCAN_CODES_SIZE); + m_scanCodes[m_scanCodesSize ++] = i_sc; } // initializer Key &Key::initialize() { - m_names.clear(); - m_isPressed = false; - m_isPressedOnWin32 = false; - m_isPressedByAssign = false; - m_scanCodesSize = 0; - return *this; + m_names.clear(); + m_isPressed = false; + m_isPressedOnWin32 = false; + m_isPressedByAssign = false; + m_scanCodesSize = 0; + return *this; } // equation by name bool Key::operator==(const tstringi &i_name) const { - return std::find(m_names.begin(), m_names.end(), i_name) != m_names.end(); + return std::find(m_names.begin(), m_names.end(), i_name) != m_names.end(); } - + // is the scan code of this key ? bool Key::isSameScanCode(const Key &i_key) const { - if (m_scanCodesSize != i_key.m_scanCodesSize) - return false; - return isPrefixScanCode(i_key); + if (m_scanCodesSize != i_key.m_scanCodesSize) + return false; + return isPrefixScanCode(i_key); } // is the key's scan code the prefix of this key's scan code ? bool Key::isPrefixScanCode(const Key &i_key) const { - for (size_t i = 0; i < i_key.m_scanCodesSize; ++ i) - if (m_scanCodes[i] != i_key.m_scanCodes[i]) - return false; - return true; + for (size_t i = 0; i < i_key.m_scanCodesSize; ++ i) + if (m_scanCodes[i] != i_key.m_scanCodes[i]) + return false; + return true; } // stream output tostream &operator<<(tostream &i_ost, const Key &i_mk) { - return i_ost << i_mk.getName(); + return i_ost << i_mk.getName(); } @@ -76,144 +76,139 @@ tostream &operator<<(tostream &i_ost, const Key &i_mk) Modifier::Modifier() - : m_modifiers(0), - m_dontcares(0) + : m_modifiers(0), + m_dontcares(0) { - ASSERT(Type_end <= (sizeof(MODIFIERS) * 8)); - static const Type defaultDontCare[] = - { - Type_Up, Type_Down, Type_Repeat, - Type_ImeLock, Type_ImeComp, Type_NumLock, Type_CapsLock, Type_ScrollLock, - Type_KanaLock, - Type_Maximized, Type_Minimized, Type_MdiMaximized, Type_MdiMinimized, - Type_Touchpad, Type_TouchpadSticky, - Type_Lock0, Type_Lock1, Type_Lock2, Type_Lock3, Type_Lock4, - Type_Lock5, Type_Lock6, Type_Lock7, Type_Lock8, Type_Lock9, - }; - for (size_t i = 0; i < NUMBER_OF(defaultDontCare); ++ i) - dontcare(defaultDontCare[i]); + ASSERT(Type_end <= (sizeof(MODIFIERS) * 8)); + static const Type defaultDontCare[] = { + Type_Up, Type_Down, Type_Repeat, + Type_ImeLock, Type_ImeComp, Type_NumLock, Type_CapsLock, Type_ScrollLock, + Type_KanaLock, + Type_Maximized, Type_Minimized, Type_MdiMaximized, Type_MdiMinimized, + Type_Touchpad, Type_TouchpadSticky, + Type_Lock0, Type_Lock1, Type_Lock2, Type_Lock3, Type_Lock4, + Type_Lock5, Type_Lock6, Type_Lock7, Type_Lock8, Type_Lock9, + }; + for (size_t i = 0; i < NUMBER_OF(defaultDontCare); ++ i) + dontcare(defaultDontCare[i]); } // add m's modifiers where this dontcare void Modifier::add(const Modifier &i_m) { - for (int i = 0; i < Type_end; ++ i) - { - if (isDontcare(static_cast(i))) - if (!i_m.isDontcare(static_cast(i))) - if (i_m.isPressed(static_cast(i))) - press(static_cast(i)); - else - release(static_cast(i)); - } + for (int i = 0; i < Type_end; ++ i) { + if (isDontcare(static_cast(i))) + if (!i_m.isDontcare(static_cast(i))) + if (i_m.isPressed(static_cast(i))) + press(static_cast(i)); + else + release(static_cast(i)); + } } // stream output tostream &operator<<(tostream &i_ost, const Modifier &i_m) { - struct Mods - { - Modifier::Type m_mt; - const _TCHAR *m_symbol; - }; - - const static Mods mods[] = - { - { Modifier::Type_Up, _T("U-") }, { Modifier::Type_Down, _T("D-") }, - { Modifier::Type_Shift, _T("S-") }, { Modifier::Type_Alt, _T("A-") }, - { Modifier::Type_Control, _T("C-") }, { Modifier::Type_Windows, _T("W-") }, - { Modifier::Type_Repeat, _T("R-") }, - { Modifier::Type_ImeLock, _T("IL-") }, - { Modifier::Type_ImeComp, _T("IC-") }, - { Modifier::Type_ImeComp, _T("I-") }, - { Modifier::Type_NumLock, _T("NL-") }, - { Modifier::Type_CapsLock, _T("CL-") }, - { Modifier::Type_ScrollLock, _T("SL-") }, - { Modifier::Type_KanaLock, _T("KL-") }, - { Modifier::Type_Maximized, _T("MAX-") }, - { Modifier::Type_Minimized, _T("MIN-") }, - { Modifier::Type_MdiMaximized, _T("MMAX-") }, - { Modifier::Type_MdiMinimized, _T("MMIN-") }, - { Modifier::Type_Touchpad, _T("T-") }, - { Modifier::Type_TouchpadSticky, _T("TS-") }, - { Modifier::Type_Mod0, _T("M0-") }, { Modifier::Type_Mod1, _T("M1-") }, - { Modifier::Type_Mod2, _T("M2-") }, { Modifier::Type_Mod3, _T("M3-") }, - { Modifier::Type_Mod4, _T("M4-") }, { Modifier::Type_Mod5, _T("M5-") }, - { Modifier::Type_Mod6, _T("M6-") }, { Modifier::Type_Mod7, _T("M7-") }, - { Modifier::Type_Mod8, _T("M8-") }, { Modifier::Type_Mod9, _T("M9-") }, - { Modifier::Type_Lock0, _T("L0-") }, { Modifier::Type_Lock1, _T("L1-") }, - { Modifier::Type_Lock2, _T("L2-") }, { Modifier::Type_Lock3, _T("L3-") }, - { Modifier::Type_Lock4, _T("L4-") }, { Modifier::Type_Lock5, _T("L5-") }, - { Modifier::Type_Lock6, _T("L6-") }, { Modifier::Type_Lock7, _T("L7-") }, - { Modifier::Type_Lock8, _T("L8-") }, { Modifier::Type_Lock9, _T("L9-") }, - }; - - for (size_t i = 0; i < NUMBER_OF(mods); ++ i) - if (!i_m.isDontcare(mods[i].m_mt) && i_m.isPressed(mods[i].m_mt)) - i_ost << mods[i].m_symbol; + struct Mods { + Modifier::Type m_mt; + const _TCHAR *m_symbol; + }; + + const static Mods mods[] = { + { Modifier::Type_Up, _T("U-") }, { Modifier::Type_Down, _T("D-") }, + { Modifier::Type_Shift, _T("S-") }, { Modifier::Type_Alt, _T("A-") }, + { Modifier::Type_Control, _T("C-") }, { Modifier::Type_Windows, _T("W-") }, + { Modifier::Type_Repeat, _T("R-") }, + { Modifier::Type_ImeLock, _T("IL-") }, + { Modifier::Type_ImeComp, _T("IC-") }, + { Modifier::Type_ImeComp, _T("I-") }, + { Modifier::Type_NumLock, _T("NL-") }, + { Modifier::Type_CapsLock, _T("CL-") }, + { Modifier::Type_ScrollLock, _T("SL-") }, + { Modifier::Type_KanaLock, _T("KL-") }, + { Modifier::Type_Maximized, _T("MAX-") }, + { Modifier::Type_Minimized, _T("MIN-") }, + { Modifier::Type_MdiMaximized, _T("MMAX-") }, + { Modifier::Type_MdiMinimized, _T("MMIN-") }, + { Modifier::Type_Touchpad, _T("T-") }, + { Modifier::Type_TouchpadSticky, _T("TS-") }, + { Modifier::Type_Mod0, _T("M0-") }, { Modifier::Type_Mod1, _T("M1-") }, + { Modifier::Type_Mod2, _T("M2-") }, { Modifier::Type_Mod3, _T("M3-") }, + { Modifier::Type_Mod4, _T("M4-") }, { Modifier::Type_Mod5, _T("M5-") }, + { Modifier::Type_Mod6, _T("M6-") }, { Modifier::Type_Mod7, _T("M7-") }, + { Modifier::Type_Mod8, _T("M8-") }, { Modifier::Type_Mod9, _T("M9-") }, + { Modifier::Type_Lock0, _T("L0-") }, { Modifier::Type_Lock1, _T("L1-") }, + { Modifier::Type_Lock2, _T("L2-") }, { Modifier::Type_Lock3, _T("L3-") }, + { Modifier::Type_Lock4, _T("L4-") }, { Modifier::Type_Lock5, _T("L5-") }, + { Modifier::Type_Lock6, _T("L6-") }, { Modifier::Type_Lock7, _T("L7-") }, + { Modifier::Type_Lock8, _T("L8-") }, { Modifier::Type_Lock9, _T("L9-") }, + }; + + for (size_t i = 0; i < NUMBER_OF(mods); ++ i) + if (!i_m.isDontcare(mods[i].m_mt) && i_m.isPressed(mods[i].m_mt)) + i_ost << mods[i].m_symbol; #if 0 - else if (!i_m.isDontcare(mods[i].m_mt) && i_m.isPressed(mods[i].m_mt)) - i_ost << _T("~") << mods[i].m_symbol; - else - i_ost << _T("*") << mods[i].m_symbol; + else if (!i_m.isDontcare(mods[i].m_mt) && i_m.isPressed(mods[i].m_mt)) + i_ost << _T("~") << mods[i].m_symbol; + else + i_ost << _T("*") << mods[i].m_symbol; #endif - return i_ost; + return i_ost; } /// stream output tostream &operator<<(tostream &i_ost, Modifier::Type i_type) { - const _TCHAR *modNames[] = - { - _T("Shift"), - _T("Alt"), - _T("Control"), - _T("Windows"), - _T("Up"), - _T("Down"), - _T("Repeat"), - _T("ImeLock"), - _T("ImeComp"), - _T("NumLock"), - _T("CapsLock"), - _T("ScrollLock"), - _T("KanaLock"), - _T("Maximized"), - _T("Minimized"), - _T("MdiMaximized"), - _T("MdiMinimized"), - _T("Touchpad"), - _T("TouchpadSticky"), - _T("Mod0"), - _T("Mod1"), - _T("Mod2"), - _T("Mod3"), - _T("Mod4"), - _T("Mod5"), - _T("Mod6"), - _T("Mod7"), - _T("Mod8"), - _T("Mod9"), - _T("Lock0"), - _T("Lock1"), - _T("Lock2"), - _T("Lock3"), - _T("Lock4"), - _T("Lock5"), - _T("Lock6"), - _T("Lock7"), - _T("Lock8"), - _T("Lock9"), - }; - - int i = static_cast(i_type); - if (0 <= i && i < NUMBER_OF(modNames)) - i_ost << modNames[i]; - - return i_ost; + const _TCHAR *modNames[] = { + _T("Shift"), + _T("Alt"), + _T("Control"), + _T("Windows"), + _T("Up"), + _T("Down"), + _T("Repeat"), + _T("ImeLock"), + _T("ImeComp"), + _T("NumLock"), + _T("CapsLock"), + _T("ScrollLock"), + _T("KanaLock"), + _T("Maximized"), + _T("Minimized"), + _T("MdiMaximized"), + _T("MdiMinimized"), + _T("Touchpad"), + _T("TouchpadSticky"), + _T("Mod0"), + _T("Mod1"), + _T("Mod2"), + _T("Mod3"), + _T("Mod4"), + _T("Mod5"), + _T("Mod6"), + _T("Mod7"), + _T("Mod8"), + _T("Mod9"), + _T("Lock0"), + _T("Lock1"), + _T("Lock2"), + _T("Lock3"), + _T("Lock4"), + _T("Lock5"), + _T("Lock6"), + _T("Lock7"), + _T("Lock8"), + _T("Lock9"), + }; + + int i = static_cast(i_type); + if (0 <= i && i < NUMBER_OF(modNames)) + i_ost << modNames[i]; + + return i_ost; } @@ -224,9 +219,9 @@ tostream &operator<<(tostream &i_ost, Modifier::Type i_type) // stream output tostream &operator<<(tostream &i_ost, const ModifiedKey &i_mk) { - if (i_mk.m_key) - i_ost << i_mk.m_modifier << *i_mk.m_key; - return i_ost; + if (i_mk.m_key) + i_ost << i_mk.m_modifier << *i_mk.m_key; + return i_ost; } @@ -235,46 +230,42 @@ tostream &operator<<(tostream &i_ost, const ModifiedKey &i_mk) Keyboard::KeyIterator::KeyIterator(Keys *i_hashedKeys, size_t i_hashedKeysSize) - : m_hashedKeys(i_hashedKeys), - m_hashedKeysSize(i_hashedKeysSize), - m_i((*m_hashedKeys).begin()) + : m_hashedKeys(i_hashedKeys), + m_hashedKeysSize(i_hashedKeysSize), + m_i((*m_hashedKeys).begin()) { - if ((*m_hashedKeys).empty()) - { - do - { - -- m_hashedKeysSize; - ++ m_hashedKeys; - } while (0 < m_hashedKeysSize && (*m_hashedKeys).empty()); - if (0 < m_hashedKeysSize) - m_i = (*m_hashedKeys).begin(); - } + if ((*m_hashedKeys).empty()) { + do { + -- m_hashedKeysSize; + ++ m_hashedKeys; + } while (0 < m_hashedKeysSize && (*m_hashedKeys).empty()); + if (0 < m_hashedKeysSize) + m_i = (*m_hashedKeys).begin(); + } } void Keyboard::KeyIterator::next() { - if (m_hashedKeysSize == 0) - return; - ++ m_i; - if (m_i == (*m_hashedKeys).end()) - { - do - { - -- m_hashedKeysSize; - ++ m_hashedKeys; - } while (0 < m_hashedKeysSize && (*m_hashedKeys).empty()); - if (0 < m_hashedKeysSize) - m_i = (*m_hashedKeys).begin(); - } + if (m_hashedKeysSize == 0) + return; + ++ m_i; + if (m_i == (*m_hashedKeys).end()) { + do { + -- m_hashedKeysSize; + ++ m_hashedKeys; + } while (0 < m_hashedKeysSize && (*m_hashedKeys).empty()); + if (0 < m_hashedKeysSize) + m_i = (*m_hashedKeys).begin(); + } } Key *Keyboard::KeyIterator::operator *() { - if (m_hashedKeysSize == 0) - return NULL; - return &*m_i; + if (m_hashedKeysSize == 0) + return NULL; + return &*m_i; } @@ -284,95 +275,94 @@ Key *Keyboard::KeyIterator::operator *() Keyboard::Keys &Keyboard::getKeys(const Key &i_key) { - ASSERT(1 <= i_key.getScanCodesSize()); - return m_hashedKeys[i_key.getScanCodes()->m_scan % HASHED_KEYS_SIZE]; + ASSERT(1 <= i_key.getScanCodesSize()); + return m_hashedKeys[i_key.getScanCodes()->m_scan % HASHED_KEYS_SIZE]; } // add a key void Keyboard::addKey(const Key &i_key) { - getKeys(i_key).push_front(i_key); + getKeys(i_key).push_front(i_key); } // add a key name alias void Keyboard::addAlias(const tstringi &i_aliasName, Key *i_key) { - m_aliases.insert(Aliases::value_type(i_aliasName, i_key)); + m_aliases.insert(Aliases::value_type(i_aliasName, i_key)); } // add substitute void Keyboard::addSubstitute(const ModifiedKey &i_mkeyFrom, - const ModifiedKey &i_mkeyTo) + const ModifiedKey &i_mkeyTo) { - m_substitutes.push_front(Substitute(i_mkeyFrom, i_mkeyTo)); + m_substitutes.push_front(Substitute(i_mkeyFrom, i_mkeyTo)); } // add a modifier key void Keyboard::addModifier(Modifier::Type i_mt, Key *i_key) { - ASSERT((int)i_mt < (int)Modifier::Type_BASIC); - if (std::find(m_mods[i_mt].begin(), m_mods[i_mt].end(), i_key) - != m_mods[i_mt].end()) - return; // already added - m_mods[i_mt].push_back(i_key); + ASSERT((int)i_mt < (int)Modifier::Type_BASIC); + if (std::find(m_mods[i_mt].begin(), m_mods[i_mt].end(), i_key) + != m_mods[i_mt].end()) + return; // already added + m_mods[i_mt].push_back(i_key); } // search a key Key *Keyboard::searchKey(const Key &i_key) { - Keys &keys = getKeys(i_key); - for (Keys::iterator i = keys.begin(); i != keys.end(); ++ i) - if ((*i).isSameScanCode(i_key)) - return &*i; - return NULL; + Keys &keys = getKeys(i_key); + for (Keys::iterator i = keys.begin(); i != keys.end(); ++ i) + if ((*i).isSameScanCode(i_key)) + return &*i; + return NULL; } // search a key (of which the key's scan code is the prefix) Key *Keyboard::searchPrefixKey(const Key &i_key) { - Keys &keys = getKeys(i_key); - for (Keys::iterator i = keys.begin(); i != keys.end(); ++ i) - if ((*i).isPrefixScanCode(i_key)) - return &*i; - return NULL; + Keys &keys = getKeys(i_key); + for (Keys::iterator i = keys.begin(); i != keys.end(); ++ i) + if ((*i).isPrefixScanCode(i_key)) + return &*i; + return NULL; } - + // search a key by name Key *Keyboard::searchKey(const tstringi &i_name) { - Aliases::iterator i = m_aliases.find(i_name); - if (i != m_aliases.end()) - return (*i).second; - return searchKeyByNonAliasName(i_name); + Aliases::iterator i = m_aliases.find(i_name); + if (i != m_aliases.end()) + return (*i).second; + return searchKeyByNonAliasName(i_name); } // search a key by non-alias name Key *Keyboard::searchKeyByNonAliasName(const tstringi &i_name) { - for (int j = 0; j < HASHED_KEYS_SIZE; ++ j) - { - Keys &keys = m_hashedKeys[j]; - Keys::iterator i = std::find(keys.begin(), keys.end(), i_name); - if (i != keys.end()) - return &*i; - } - return NULL; + for (int j = 0; j < HASHED_KEYS_SIZE; ++ j) { + Keys &keys = m_hashedKeys[j]; + Keys::iterator i = std::find(keys.begin(), keys.end(), i_name); + if (i != keys.end()) + return &*i; + } + return NULL; } /// search a substitute ModifiedKey Keyboard::searchSubstitute(const ModifiedKey &i_mkey) { - for (Substitutes::const_iterator - i = m_substitutes.begin(); i != m_substitutes.end(); ++ i) - if (i->m_mkeyFrom.m_key == i_mkey.m_key && - i->m_mkeyFrom.m_modifier.doesMatch(i_mkey.m_modifier)) - return i->m_mkeyTo; - return ModifiedKey(); // not found (.m_mkey is NULL) + for (Substitutes::const_iterator + i = m_substitutes.begin(); i != m_substitutes.end(); ++ i) + if (i->m_mkeyFrom.m_key == i_mkey.m_key && + i->m_mkeyFrom.m_modifier.doesMatch(i_mkey.m_modifier)) + return i->m_mkeyTo; + return ModifiedKey(); // not found (.m_mkey is NULL) } diff --git a/keyboard.h b/keyboard.h index 9965ba0..8bfc42c 100644 --- a/keyboard.h +++ b/keyboard.h @@ -17,33 +17,33 @@ class ScanCode { public: - /// - enum - { - BREAK = KEYBOARD_INPUT_DATA::BREAK, /// key release flag - E0 = KEYBOARD_INPUT_DATA::E0, /// extended key flag - E1 = KEYBOARD_INPUT_DATA::E1, /// extended key flag - E0E1 = KEYBOARD_INPUT_DATA::E0E1, /// extended key flag - }; + /// + enum { + BREAK = KEYBOARD_INPUT_DATA::BREAK, /// key release flag + E0 = KEYBOARD_INPUT_DATA::E0, /// extended key flag + E1 = KEYBOARD_INPUT_DATA::E1, /// extended key flag + E0E1 = KEYBOARD_INPUT_DATA::E0E1, /// extended key flag + }; public: - USHORT m_scan; /// - USHORT m_flags; /// + USHORT m_scan; /// + USHORT m_flags; /// public: - /// - ScanCode() : m_scan(0), m_flags(0) { } - /// - ScanCode(USHORT i_scan, USHORT i_flags) - : m_scan(i_scan), m_flags(i_flags) { } - /// - bool operator==(const ScanCode &i_sc) const - { - return (m_scan == i_sc.m_scan && - (E0E1 & m_flags) == (E0E1 & i_sc.m_flags)); - } - /// - bool operator!=(const ScanCode &i_sc) const { return !(*this == i_sc); } + /// + ScanCode() : m_scan(0), m_flags(0) { } + /// + ScanCode(USHORT i_scan, USHORT i_flags) + : m_scan(i_scan), m_flags(i_flags) { } + /// + bool operator==(const ScanCode &i_sc) const { + return (m_scan == i_sc.m_scan && + (E0E1 & m_flags) == (E0E1 & i_sc.m_flags)); + } + /// + bool operator!=(const ScanCode &i_sc) const { + return !(*this == i_sc); + } }; @@ -51,216 +51,244 @@ public: class Key { public: - enum - { - /// - MAX_SCAN_CODES_SIZE = 4, - }; + enum { + /// + MAX_SCAN_CODES_SIZE = 4, + }; private: - /// - typedef std::vector Names; + /// + typedef std::vector Names; public: - /// if this key pressed physically - bool m_isPressed; - /// if this key pressed on Win32 - bool m_isPressedOnWin32; - /// if this key pressed by assign - bool m_isPressedByAssign; + /// if this key pressed physically + bool m_isPressed; + /// if this key pressed on Win32 + bool m_isPressedOnWin32; + /// if this key pressed by assign + bool m_isPressedByAssign; private: - /// key name - Names m_names; - /// key scan code length - size_t m_scanCodesSize; - /// key scan code - ScanCode m_scanCodes[MAX_SCAN_CODES_SIZE]; + /// key name + Names m_names; + /// key scan code length + size_t m_scanCodesSize; + /// key scan code + ScanCode m_scanCodes[MAX_SCAN_CODES_SIZE]; public: - /// - Key() - : m_isPressed(false), - m_isPressedOnWin32(false), - m_isPressedByAssign(false), - m_scanCodesSize(0) - { } - - /// for Event::* only - Key(const tstringi &i_name) - : m_isPressed(false), - m_isPressedOnWin32(false), - m_isPressedByAssign(false), - m_scanCodesSize(0) - { - addName(i_name); - addScanCode(ScanCode()); - } - - /// get key name (first name) - const tstringi &getName() const { return m_names.front(); } - - /// get scan codes - const ScanCode *getScanCodes() const { return m_scanCodes; } - /// - size_t getScanCodesSize() const { return m_scanCodesSize; } - - /// add a name of key - void addName(const tstringi &i_name); - - /// add a scan code - void addScanCode(const ScanCode &i_sc); - - /// initializer - Key &initialize(); - - /// equation by name - bool operator==(const tstringi &i_name) const; - /// - bool operator!=(const tstringi &i_name) const - { return !(*this == i_name); } - - /// is the scan code of this key ? - bool isSameScanCode(const Key &i_key) const; - - /// is the i_key's scan code the prefix of this key's scan code ? - bool isPrefixScanCode(const Key &i_key) const; - - /// stream output - friend tostream &operator<<(tostream &i_ost, const Key &i_key); - - /// < - bool operator<(const Key &i_key) const - { return getName() < i_key.getName(); } + /// + Key() + : m_isPressed(false), + m_isPressedOnWin32(false), + m_isPressedByAssign(false), + m_scanCodesSize(0) { } + + /// for Event::* only + Key(const tstringi &i_name) + : m_isPressed(false), + m_isPressedOnWin32(false), + m_isPressedByAssign(false), + m_scanCodesSize(0) { + addName(i_name); + addScanCode(ScanCode()); + } + + /// get key name (first name) + const tstringi &getName() const { + return m_names.front(); + } + + /// get scan codes + const ScanCode *getScanCodes() const { + return m_scanCodes; + } + /// + size_t getScanCodesSize() const { + return m_scanCodesSize; + } + + /// add a name of key + void addName(const tstringi &i_name); + + /// add a scan code + void addScanCode(const ScanCode &i_sc); + + /// initializer + Key &initialize(); + + /// equation by name + bool operator==(const tstringi &i_name) const; + /// + bool operator!=(const tstringi &i_name) const { + return !(*this == i_name); + } + + /// is the scan code of this key ? + bool isSameScanCode(const Key &i_key) const; + + /// is the i_key's scan code the prefix of this key's scan code ? + bool isPrefixScanCode(const Key &i_key) const; + + /// stream output + friend tostream &operator<<(tostream &i_ost, const Key &i_key); + + /// < + bool operator<(const Key &i_key) const { + return getName() < i_key.getName(); + } }; /// class Modifier { - /// - typedef u_int64 MODIFIERS; - /// - MODIFIERS m_modifiers; - /// - MODIFIERS m_dontcares; - + /// + typedef u_int64 MODIFIERS; + /// + MODIFIERS m_modifiers; + /// + MODIFIERS m_dontcares; + public: - /// - enum Type - { - Type_begin = 0, /// - - Type_Shift = Type_begin, /// <BASIC_MODIFIER> - Type_Alt, /// <BASIC_MODIFIER> - Type_Control, /// <BASIC_MODIFIER> - Type_Windows, /// <BASIC_MODIFIER> - Type_BASIC, /// - - Type_Up = Type_BASIC, /// <KEYSEQ_MODIFIER> - Type_Down, /// <KEYSEQ_MODIFIER> - Type_KEYSEQ, /// - - Type_Repeat = Type_KEYSEQ, /// <ASSIGN_MODIFIER> - Type_ImeLock, /// <ASSIGN_MODIFIER> - Type_ImeComp, /// <ASSIGN_MODIFIER> - Type_NumLock, /// <ASSIGN_MODIFIER> - Type_CapsLock, /// <ASSIGN_MODIFIER> - Type_ScrollLock, /// <ASSIGN_MODIFIER> - Type_KanaLock, /// <ASSIGN_MODIFIER> - Type_Maximized, /// <ASSIGN_MODIFIER> - Type_Minimized, /// <ASSIGN_MODIFIER> - Type_MdiMaximized, /// <ASSIGN_MODIFIER> - Type_MdiMinimized, /// <ASSIGN_MODIFIER> - Type_Touchpad, /// <ASSIGN_MODIFIER> - Type_TouchpadSticky, /// <ASSIGN_MODIFIER> - Type_Mod0, /// <ASSIGN_MODIFIER> - Type_Mod1, /// <ASSIGN_MODIFIER> - Type_Mod2, /// <ASSIGN_MODIFIER> - Type_Mod3, /// <ASSIGN_MODIFIER> - Type_Mod4, /// <ASSIGN_MODIFIER> - Type_Mod5, /// <ASSIGN_MODIFIER> - Type_Mod6, /// <ASSIGN_MODIFIER> - Type_Mod7, /// <ASSIGN_MODIFIER> - Type_Mod8, /// <ASSIGN_MODIFIER> - Type_Mod9, /// <ASSIGN_MODIFIER> - Type_Lock0, /// <ASSIGN_MODIFIER> - Type_Lock1, /// <ASSIGN_MODIFIER> - Type_Lock2, /// <ASSIGN_MODIFIER> - Type_Lock3, /// <ASSIGN_MODIFIER> - Type_Lock4, /// <ASSIGN_MODIFIER> - Type_Lock5, /// <ASSIGN_MODIFIER> - Type_Lock6, /// <ASSIGN_MODIFIER> - Type_Lock7, /// <ASSIGN_MODIFIER> - Type_Lock8, /// <ASSIGN_MODIFIER> - Type_Lock9, /// <ASSIGN_MODIFIER> - Type_ASSIGN, /// - - Type_end = Type_ASSIGN /// - }; - + /// + enum Type { + Type_begin = 0, /// + + Type_Shift = Type_begin, /// <BASIC_MODIFIER> + Type_Alt, /// <BASIC_MODIFIER> + Type_Control, /// <BASIC_MODIFIER> + Type_Windows, /// <BASIC_MODIFIER> + Type_BASIC, /// + + Type_Up = Type_BASIC, /// <KEYSEQ_MODIFIER> + Type_Down, /// <KEYSEQ_MODIFIER> + Type_KEYSEQ, /// + + Type_Repeat = Type_KEYSEQ, /// <ASSIGN_MODIFIER> + Type_ImeLock, /// <ASSIGN_MODIFIER> + Type_ImeComp, /// <ASSIGN_MODIFIER> + Type_NumLock, /// <ASSIGN_MODIFIER> + Type_CapsLock, /// <ASSIGN_MODIFIER> + Type_ScrollLock, /// <ASSIGN_MODIFIER> + Type_KanaLock, /// <ASSIGN_MODIFIER> + Type_Maximized, /// <ASSIGN_MODIFIER> + Type_Minimized, /// <ASSIGN_MODIFIER> + Type_MdiMaximized, /// <ASSIGN_MODIFIER> + Type_MdiMinimized, /// <ASSIGN_MODIFIER> + Type_Touchpad, /// <ASSIGN_MODIFIER> + Type_TouchpadSticky, /// <ASSIGN_MODIFIER> + Type_Mod0, /// <ASSIGN_MODIFIER> + Type_Mod1, /// <ASSIGN_MODIFIER> + Type_Mod2, /// <ASSIGN_MODIFIER> + Type_Mod3, /// <ASSIGN_MODIFIER> + Type_Mod4, /// <ASSIGN_MODIFIER> + Type_Mod5, /// <ASSIGN_MODIFIER> + Type_Mod6, /// <ASSIGN_MODIFIER> + Type_Mod7, /// <ASSIGN_MODIFIER> + Type_Mod8, /// <ASSIGN_MODIFIER> + Type_Mod9, /// <ASSIGN_MODIFIER> + Type_Lock0, /// <ASSIGN_MODIFIER> + Type_Lock1, /// <ASSIGN_MODIFIER> + Type_Lock2, /// <ASSIGN_MODIFIER> + Type_Lock3, /// <ASSIGN_MODIFIER> + Type_Lock4, /// <ASSIGN_MODIFIER> + Type_Lock5, /// <ASSIGN_MODIFIER> + Type_Lock6, /// <ASSIGN_MODIFIER> + Type_Lock7, /// <ASSIGN_MODIFIER> + Type_Lock8, /// <ASSIGN_MODIFIER> + Type_Lock9, /// <ASSIGN_MODIFIER> + Type_ASSIGN, /// + + Type_end = Type_ASSIGN /// + }; + public: - /// - Modifier(); - /// - Modifier &on(Type i_type) { return press(i_type); } - /// - Modifier &off(Type i_type) { return release(i_type); } - /// - Modifier &press(Type i_type) - { m_modifiers |= ((MODIFIERS(1)) << i_type); return care(i_type); } - /// - Modifier &release(Type i_type) - { m_modifiers &= ~((MODIFIERS(1)) << i_type); return care(i_type); } - /// - Modifier &care(Type i_type) - { m_dontcares &= ~((MODIFIERS(1)) << i_type); return *this; } - /// - Modifier &dontcare(Type i_type) - { m_dontcares |= ((MODIFIERS(1)) << i_type); return *this; } - /// set all modifiers to dontcare - Modifier &dontcare() { m_dontcares = ~MODIFIERS(0); return *this; } - - /// - Modifier &on(Type i_type, bool i_isOn) { return press(i_type, i_isOn); } - /// - Modifier &press(Type i_type, bool i_isPressed) - { return i_isPressed ? press(i_type) : release(i_type); } - /// - Modifier &care(Type i_type, bool i_doCare) - { return i_doCare ? care(i_type) : dontcare(i_type); } - - /// - bool operator==(const Modifier &i_m) const - { return m_modifiers == i_m.m_modifiers && m_dontcares == i_m.m_dontcares; } - - /// add m's modifiers where this dontcare - void add(const Modifier &i_m); - //Modifier &operator+=(const Modifier &i_m); - - /** does match. (except dontcare modifiers) (is the m included in the *this - set ?) */ - bool doesMatch(const Modifier &i_m) const - { return ((m_modifiers | m_dontcares) == (i_m.m_modifiers | m_dontcares)); } - - /// - bool isOn(Type i_type) const { return isPressed(i_type); } - /// - bool isPressed(Type i_type) const - { return !!(m_modifiers & ((MODIFIERS(1)) << i_type)); } - /// - bool isDontcare(Type i_type) const - { return !!(m_dontcares & ((MODIFIERS(1)) << i_type)); } - - /// stream output - friend tostream &operator<<(tostream &i_ost, const Modifier &i_m); - - /// < - bool operator<(const Modifier &i_m) const - { - return m_modifiers < i_m.m_modifiers || - (m_modifiers == i_m.m_modifiers && m_dontcares < i_m.m_dontcares); - } + /// + Modifier(); + /// + Modifier &on(Type i_type) { + return press(i_type); + } + /// + Modifier &off(Type i_type) { + return release(i_type); + } + /// + Modifier &press(Type i_type) { + m_modifiers |= ((MODIFIERS(1)) << i_type); + return care(i_type); + } + /// + Modifier &release(Type i_type) { + m_modifiers &= ~((MODIFIERS(1)) << i_type); + return care(i_type); + } + /// + Modifier &care(Type i_type) { + m_dontcares &= ~((MODIFIERS(1)) << i_type); + return *this; + } + /// + Modifier &dontcare(Type i_type) { + m_dontcares |= ((MODIFIERS(1)) << i_type); + return *this; + } + /// set all modifiers to dontcare + Modifier &dontcare() { + m_dontcares = ~MODIFIERS(0); + return *this; + } + + /// + Modifier &on(Type i_type, bool i_isOn) { + return press(i_type, i_isOn); + } + /// + Modifier &press(Type i_type, bool i_isPressed) { + return i_isPressed ? press(i_type) : release(i_type); + } + /// + Modifier &care(Type i_type, bool i_doCare) { + return i_doCare ? care(i_type) : dontcare(i_type); + } + + /// + bool operator==(const Modifier &i_m) const { + return m_modifiers == i_m.m_modifiers && m_dontcares == i_m.m_dontcares; + } + + /// add m's modifiers where this dontcare + void add(const Modifier &i_m); + //Modifier &operator+=(const Modifier &i_m); + + /** does match. (except dontcare modifiers) (is the m included in the *this + set ?) */ + bool doesMatch(const Modifier &i_m) const { + return ((m_modifiers | m_dontcares) == (i_m.m_modifiers | m_dontcares)); + } + + /// + bool isOn(Type i_type) const { + return isPressed(i_type); + } + /// + bool isPressed(Type i_type) const { + return !!(m_modifiers & ((MODIFIERS(1)) << i_type)); + } + /// + bool isDontcare(Type i_type) const { + return !!(m_dontcares & ((MODIFIERS(1)) << i_type)); + } + + /// stream output + friend tostream &operator<<(tostream &i_ost, const Modifier &i_m); + + /// < + bool operator<(const Modifier &i_m) const { + return m_modifiers < i_m.m_modifiers || + (m_modifiers == i_m.m_modifiers && m_dontcares < i_m.m_dontcares); + } }; @@ -272,33 +300,34 @@ tostream &operator<<(tostream &i_ost, Modifier::Type i_type); class ModifiedKey { public: - Modifier m_modifier; /// - Key *m_key; /// - + Modifier m_modifier; /// + Key *m_key; /// + public: - /// - ModifiedKey() : m_key(NULL) { } - /// - ModifiedKey(Key *i_key) : m_key(i_key) { } - /// - ModifiedKey(const Modifier &i_modifier, Key *i_key) - : m_modifier(i_modifier), m_key(i_key) { } - /// - bool operator==(const ModifiedKey &i_mk) const - { return m_modifier == i_mk.m_modifier && m_key == i_mk.m_key; } - /// - bool operator!=(const ModifiedKey &i_mk) const - { return !operator==(i_mk); } - - /// stream output - friend tostream &operator<<(tostream &i_ost, const ModifiedKey &i_mk); - - /// < - bool operator<(const ModifiedKey &i_mk) const - { - return *m_key < *i_mk.m_key || - (!(*i_mk.m_key < *m_key) && m_modifier < i_mk.m_modifier); - } + /// + ModifiedKey() : m_key(NULL) { } + /// + ModifiedKey(Key *i_key) : m_key(i_key) { } + /// + ModifiedKey(const Modifier &i_modifier, Key *i_key) + : m_modifier(i_modifier), m_key(i_key) { } + /// + bool operator==(const ModifiedKey &i_mk) const { + return m_modifier == i_mk.m_modifier && m_key == i_mk.m_key; + } + /// + bool operator!=(const ModifiedKey &i_mk) const { + return !operator==(i_mk); + } + + /// stream output + friend tostream &operator<<(tostream &i_ost, const ModifiedKey &i_mk); + + /// < + bool operator<(const ModifiedKey &i_mk) const { + return *m_key < *i_mk.m_key || + (!(*i_mk.m_key < *m_key) && m_modifier < i_mk.m_modifier); + } }; @@ -306,109 +335,115 @@ public: class Keyboard { public: - /// keyboard modifiers (pointer into Keys) - typedef std::list Mods; + /// keyboard modifiers (pointer into Keys) + typedef std::list Mods; private: - /** keyboard keys (hashed by first scan code). - Keys must be *list* of Key. - Because *pointers* into Keys exist anywhere in this program, the address - of Key's elements must be fixed. */ - enum { - HASHED_KEYS_SIZE = 128, /// - }; - typedef std::list Keys; /// - typedef std::map Aliases; /// key name aliases - /// - class Substitute - { - public: - ModifiedKey m_mkeyFrom; - ModifiedKey m_mkeyTo; - public: - Substitute(const ModifiedKey &i_mkeyFrom, - const ModifiedKey &i_mkeyTo) - : m_mkeyFrom(i_mkeyFrom), m_mkeyTo(i_mkeyTo) - { - } - }; - typedef std::list Substitutes; /// substitutes + /** keyboard keys (hashed by first scan code). + Keys must be *list* of Key. + Because *pointers* into Keys exist anywhere in this program, the address + of Key's elements must be fixed. */ + enum { + HASHED_KEYS_SIZE = 128, /// + }; + typedef std::list Keys; /// + typedef std::map Aliases; /// key name aliases + /// + class Substitute + { + public: + ModifiedKey m_mkeyFrom; + ModifiedKey m_mkeyTo; + public: + Substitute(const ModifiedKey &i_mkeyFrom, + const ModifiedKey &i_mkeyTo) + : m_mkeyFrom(i_mkeyFrom), m_mkeyTo(i_mkeyTo) { + } + }; + typedef std::list Substitutes; /// substitutes private: - Keys m_hashedKeys[HASHED_KEYS_SIZE]; /// - Aliases m_aliases; /// - Substitutes m_substitutes; /// - Key m_syncKey; /// key used to synchronize - + Keys m_hashedKeys[HASHED_KEYS_SIZE]; /// + Aliases m_aliases; /// + Substitutes m_substitutes; /// + Key m_syncKey; /// key used to synchronize + private: - /// - Mods m_mods[Modifier::Type_BASIC]; + /// + Mods m_mods[Modifier::Type_BASIC]; public: - /// - class KeyIterator - { - /// - Keys *m_hashedKeys; - /// - size_t m_hashedKeysSize; - /// - Keys::iterator m_i; - - /// - void next(); - - public: - /// - KeyIterator(Keys *i_hashedKeys, size_t i_hashedKeysSize); - /// - Key *operator *(); - /// - void operator++() { next(); } - }; - + /// + class KeyIterator + { + /// + Keys *m_hashedKeys; + /// + size_t m_hashedKeysSize; + /// + Keys::iterator m_i; + + /// + void next(); + + public: + /// + KeyIterator(Keys *i_hashedKeys, size_t i_hashedKeysSize); + /// + Key *operator *(); + /// + void operator++() { + next(); + } + }; + private: - /// - Keys &getKeys(const Key &i_key); + /// + Keys &getKeys(const Key &i_key); public: - /// add a key - void addKey(const Key &i_key); - - /// add a key name alias - void addAlias(const tstringi &i_aliasName, Key *i_key); - - /// add substitute - void addSubstitute(const ModifiedKey &i_mkeyFrom, - const ModifiedKey &i_mkeyTo); - - /// get a sync key - Key *getSyncKey() { return &m_syncKey; } - - /// add a modifier key - void addModifier(Modifier::Type i_mt, Key * i_key); - - /// search a key - Key *searchKey(const Key &i_key); - - /// search a key (of which the key's scan code is the prefix) - Key *searchPrefixKey(const Key &i_key); - - /// search a key by name - Key *searchKey(const tstringi &i_name); - - /// search a key by non-alias name - Key *searchKeyByNonAliasName(const tstringi &i_name); - - /// search a substitute - ModifiedKey searchSubstitute(const ModifiedKey &i_mkey); - - /// get modifiers - Mods &getModifiers(Modifier::Type i_mt) { return m_mods[i_mt]; } - - /// get key iterator - KeyIterator getKeyIterator() - { return KeyIterator(&m_hashedKeys[0], HASHED_KEYS_SIZE); } + /// add a key + void addKey(const Key &i_key); + + /// add a key name alias + void addAlias(const tstringi &i_aliasName, Key *i_key); + + /// add substitute + void addSubstitute(const ModifiedKey &i_mkeyFrom, + const ModifiedKey &i_mkeyTo); + + /// get a sync key + Key *getSyncKey() { + return &m_syncKey; + } + + /// add a modifier key + void addModifier(Modifier::Type i_mt, Key * i_key); + + /// search a key + Key *searchKey(const Key &i_key); + + /// search a key (of which the key's scan code is the prefix) + Key *searchPrefixKey(const Key &i_key); + + /// search a key by name + Key *searchKey(const tstringi &i_name); + + /// search a key by non-alias name + Key *searchKeyByNonAliasName(const tstringi &i_name); + + /// search a substitute + ModifiedKey searchSubstitute(const ModifiedKey &i_mkey); + + /// get modifiers + Mods &getModifiers(Modifier::Type i_mt) { + return m_mods[i_mt]; + } + + /// get key iterator + KeyIterator getKeyIterator() { + return KeyIterator(&m_hashedKeys[0], HASHED_KEYS_SIZE); + } }; diff --git a/keymap.cpp b/keymap.cpp index 38b1346..eb1c414 100644 --- a/keymap.cpp +++ b/keymap.cpp @@ -15,88 +15,88 @@ // tostream &operator<<(tostream &i_ost, const Action &i_action) { - return i_action.output(i_ost); + return i_action.output(i_ost); } // ActionKey::ActionKey(const ModifiedKey &i_mk) - : m_modifiedKey(i_mk) + : m_modifiedKey(i_mk) { } // Action::Type ActionKey::getType() const { - return Type_key; + return Type_key; } // create clone Action *ActionKey::clone() const { - return new ActionKey(m_modifiedKey); + return new ActionKey(m_modifiedKey); } // stream output tostream &ActionKey::output(tostream &i_ost) const { - return i_ost << m_modifiedKey; + return i_ost << m_modifiedKey; } // ActionKeySeq::ActionKeySeq(KeySeq *i_keySeq) - : m_keySeq(i_keySeq) + : m_keySeq(i_keySeq) { } // Action::Type ActionKeySeq::getType() const { - return Type_keySeq; + return Type_keySeq; } // create clone Action *ActionKeySeq::clone() const { - return new ActionKeySeq(m_keySeq); + return new ActionKeySeq(m_keySeq); } // stream output tostream &ActionKeySeq::output(tostream &i_ost) const { - return i_ost << _T("$") << m_keySeq->getName(); + return i_ost << _T("$") << m_keySeq->getName(); } // ActionFunction::ActionFunction(FunctionData *i_functionData, - Modifier i_modifier) - : m_functionData(i_functionData), - m_modifier(i_modifier) + Modifier i_modifier) + : m_functionData(i_functionData), + m_modifier(i_modifier) { } // ActionFunction::~ActionFunction() { - delete m_functionData; + delete m_functionData; } // Action::Type ActionFunction::getType() const { - return Type_function; + return Type_function; } // create clone Action *ActionFunction::clone() const { - return new ActionFunction(m_functionData->clone(), m_modifier); + return new ActionFunction(m_functionData->clone(), m_modifier); } // stream output tostream &ActionFunction::output(tostream &i_ost) const { - return i_ost << m_modifier << m_functionData; + return i_ost << m_modifier << m_functionData; } @@ -106,88 +106,85 @@ tostream &ActionFunction::output(tostream &i_ost) const void KeySeq::copy() { - for (Actions::iterator i = m_actions.begin(); i != m_actions.end(); ++ i) - (*i) = (*i)->clone(); + for (Actions::iterator i = m_actions.begin(); i != m_actions.end(); ++ i) + (*i) = (*i)->clone(); } void KeySeq::clear() { - for (Actions::iterator i = m_actions.begin(); i != m_actions.end(); ++ i) - delete (*i); + for (Actions::iterator i = m_actions.begin(); i != m_actions.end(); ++ i) + delete (*i); } KeySeq::KeySeq(const tstringi &i_name) - : m_name(i_name), - m_mode(Modifier::Type_KEYSEQ) + : m_name(i_name), + m_mode(Modifier::Type_KEYSEQ) { } KeySeq::KeySeq(const KeySeq &i_ks) - : m_actions(i_ks.m_actions), - m_name(i_ks.m_name), - m_mode(i_ks.m_mode) + : m_actions(i_ks.m_actions), + m_name(i_ks.m_name), + m_mode(i_ks.m_mode) { - copy(); + copy(); } KeySeq::~KeySeq() { - clear(); + clear(); } KeySeq &KeySeq::operator=(const KeySeq &i_ks) { - if (this != &i_ks) - { - clear(); - m_actions = i_ks.m_actions; - m_mode = i_ks.m_mode; - copy(); - } - return *this; + if (this != &i_ks) { + clear(); + m_actions = i_ks.m_actions; + m_mode = i_ks.m_mode; + copy(); + } + return *this; } KeySeq &KeySeq::add(const Action &i_action) { - m_actions.push_back(i_action.clone()); - return *this; + m_actions.push_back(i_action.clone()); + return *this; } /// get the first modified key of this key sequence ModifiedKey KeySeq::getFirstModifiedKey() const { - if (0 < m_actions.size()) - { - const Action *a = m_actions.front(); - switch (a->getType()) - { - case Action::Type_key: - return reinterpret_cast(a)->m_modifiedKey; - case Action::Type_keySeq: - return reinterpret_cast(a)-> - m_keySeq->getFirstModifiedKey(); - default: - break; - } - } - return ModifiedKey(); // failed + if (0 < m_actions.size()) { + const Action *a = m_actions.front(); + switch (a->getType()) { + case Action::Type_key: + return reinterpret_cast(a)->m_modifiedKey; + case Action::Type_keySeq: + return reinterpret_cast(a)-> + m_keySeq->getFirstModifiedKey(); + default: + break; + } + } + return ModifiedKey(); // failed } // stream output tostream &operator<<(tostream &i_ost, const KeySeq &i_ks) { - for (KeySeq::Actions::const_iterator - i = i_ks.m_actions.begin(); i != i_ks.m_actions.end(); ++ i) - i_ost << **i << _T(" "); - return i_ost; + for (KeySeq::Actions::const_iterator + i = i_ks.m_actions.begin(); i != i_ks.m_actions.end(); ++ i) + i_ost << **i << _T(" "); + return i_ost; } @@ -197,328 +194,304 @@ tostream &operator<<(tostream &i_ost, const KeySeq &i_ks) Keymap::KeyAssignments &Keymap::getKeyAssignments(const ModifiedKey &i_mk) { - ASSERT(1 <= i_mk.m_key->getScanCodesSize()); - return m_hashedKeyAssignments[i_mk.m_key->getScanCodes()->m_scan % - HASHED_KEY_ASSIGNMENT_SIZE]; + ASSERT(1 <= i_mk.m_key->getScanCodesSize()); + return m_hashedKeyAssignments[i_mk.m_key->getScanCodes()->m_scan % + HASHED_KEY_ASSIGNMENT_SIZE]; } const Keymap::KeyAssignments & Keymap::getKeyAssignments(const ModifiedKey &i_mk) const { - ASSERT(1 <= i_mk.m_key->getScanCodesSize()); - return m_hashedKeyAssignments[i_mk.m_key->getScanCodes()->m_scan % - HASHED_KEY_ASSIGNMENT_SIZE]; + ASSERT(1 <= i_mk.m_key->getScanCodesSize()); + return m_hashedKeyAssignments[i_mk.m_key->getScanCodes()->m_scan % + HASHED_KEY_ASSIGNMENT_SIZE]; } Keymap::Keymap(Type i_type, - const tstringi &i_name, - const tstringi &i_windowClass, - const tstringi &i_windowTitle, - KeySeq *i_defaultKeySeq, - Keymap *i_parentKeymap) - : m_type(i_type), - m_name(i_name), - m_defaultKeySeq(i_defaultKeySeq), - m_parentKeymap(i_parentKeymap), - m_windowClass(_T(".*")), - m_windowTitle(_T(".*")) -{ - if (i_type == Type_windowAnd || i_type == Type_windowOr) - try - { - tregex::flag_type f = (tregex::normal | - tregex::icase); - if (!i_windowClass.empty()) - m_windowClass.assign(i_windowClass, f); - if (!i_windowTitle.empty()) - m_windowTitle.assign(i_windowTitle, f); - } - catch (boost::bad_expression &i_e) - { - throw ErrorMessage() << i_e.what(); - } + const tstringi &i_name, + const tstringi &i_windowClass, + const tstringi &i_windowTitle, + KeySeq *i_defaultKeySeq, + Keymap *i_parentKeymap) + : m_type(i_type), + m_name(i_name), + m_defaultKeySeq(i_defaultKeySeq), + m_parentKeymap(i_parentKeymap), + m_windowClass(_T(".*")), + m_windowTitle(_T(".*")) +{ + if (i_type == Type_windowAnd || i_type == Type_windowOr) + try { + tregex::flag_type f = (tregex::normal | + tregex::icase); + if (!i_windowClass.empty()) + m_windowClass.assign(i_windowClass, f); + if (!i_windowTitle.empty()) + m_windowTitle.assign(i_windowTitle, f); + } catch (boost::bad_expression &i_e) { + throw ErrorMessage() << i_e.what(); + } } // add a key assignment; void Keymap::addAssignment(const ModifiedKey &i_mk, KeySeq *i_keySeq) { - KeyAssignments &ka = getKeyAssignments(i_mk); - for (KeyAssignments::iterator i = ka.begin(); i != ka.end(); ++ i) - if ((*i).m_modifiedKey == i_mk) - { - (*i).m_keySeq = i_keySeq; - return; - } - ka.push_front(KeyAssignment(i_mk, i_keySeq)); + KeyAssignments &ka = getKeyAssignments(i_mk); + for (KeyAssignments::iterator i = ka.begin(); i != ka.end(); ++ i) + if ((*i).m_modifiedKey == i_mk) { + (*i).m_keySeq = i_keySeq; + return; + } + ka.push_front(KeyAssignment(i_mk, i_keySeq)); } // add modifier void Keymap::addModifier(Modifier::Type i_mt, AssignOperator i_ao, - AssignMode i_am, Key *i_key) -{ - if (i_ao == AO_new) - m_modAssignments[i_mt].clear(); - else - { - for (ModAssignments::iterator i = m_modAssignments[i_mt].begin(); - i != m_modAssignments[i_mt].end(); ++ i) - if ((*i).m_key == i_key) - { - (*i).m_assignOperator = i_ao; - (*i).m_assignMode = i_am; - return; - } - } - ModAssignment ma; - ma.m_assignOperator = i_ao; - ma.m_assignMode = i_am; - ma.m_key = i_key; - m_modAssignments[i_mt].push_back(ma); -} - - + AssignMode i_am, Key *i_key) +{ + if (i_ao == AO_new) + m_modAssignments[i_mt].clear(); + else { + for (ModAssignments::iterator i = m_modAssignments[i_mt].begin(); + i != m_modAssignments[i_mt].end(); ++ i) + if ((*i).m_key == i_key) { + (*i).m_assignOperator = i_ao; + (*i).m_assignMode = i_am; + return; + } + } + ModAssignment ma; + ma.m_assignOperator = i_ao; + ma.m_assignMode = i_am; + ma.m_key = i_key; + m_modAssignments[i_mt].push_back(ma); +} + + // search const Keymap::KeyAssignment * Keymap::searchAssignment(const ModifiedKey &i_mk) const { - const KeyAssignments &ka = getKeyAssignments(i_mk); - for (KeyAssignments::const_iterator i = ka.begin(); i != ka.end(); ++ i) - if ((*i).m_modifiedKey.m_key == i_mk.m_key && - (*i).m_modifiedKey.m_modifier.doesMatch(i_mk.m_modifier)) - return &(*i); - return NULL; + const KeyAssignments &ka = getKeyAssignments(i_mk); + for (KeyAssignments::const_iterator i = ka.begin(); i != ka.end(); ++ i) + if ((*i).m_modifiedKey.m_key == i_mk.m_key && + (*i).m_modifiedKey.m_modifier.doesMatch(i_mk.m_modifier)) + return &(*i); + return NULL; } // does same window bool Keymap::doesSameWindow(const tstringi i_className, - const tstringi &i_titleName) -{ - if (m_type == Type_keymap) - return false; - - tsmatch what; - if (boost::regex_search(i_className, what, m_windowClass)) - { - if (m_type == Type_windowAnd) - return boost::regex_search(i_titleName, what, m_windowTitle); - else // type == Type_windowOr - return true; - } - else - { - if (m_type == Type_windowAnd) - return false; - else // type == Type_windowOr - return boost::regex_search(i_titleName, what, m_windowTitle); - } + const tstringi &i_titleName) +{ + if (m_type == Type_keymap) + return false; + + tsmatch what; + if (boost::regex_search(i_className, what, m_windowClass)) { + if (m_type == Type_windowAnd) + return boost::regex_search(i_titleName, what, m_windowTitle); + else // type == Type_windowOr + return true; + } else { + if (m_type == Type_windowAnd) + return false; + else // type == Type_windowOr + return boost::regex_search(i_titleName, what, m_windowTitle); + } } // adjust modifier void Keymap::adjustModifier(Keyboard &i_keyboard) { - for (size_t i = 0; i < NUMBER_OF(m_modAssignments); ++ i) - { - ModAssignments mos; - if (m_parentKeymap) - mos = m_parentKeymap->m_modAssignments[i]; - else - { - // set default modifiers - if (i < Modifier::Type_BASIC) - { - Keyboard::Mods mods = - i_keyboard.getModifiers(static_cast(i)); - for (Keyboard::Mods::iterator j = mods.begin(); j != mods.end(); ++ j) - { - ModAssignment ma; - ma.m_assignOperator = AO_add; - ma.m_assignMode = AM_normal; - ma.m_key = *j; - mos.push_back(ma); - } - } - } - - // mod adjust - for (ModAssignments::iterator mai = m_modAssignments[i].begin(); - mai != m_modAssignments[i].end(); ++ mai) - { - ModAssignment ma = *mai; - ma.m_assignOperator = AO_new; - switch ((*mai).m_assignOperator) - { - case AO_new: - { - mos.clear(); - mos.push_back(ma); - break; - } - case AO_add: - { - mos.push_back(ma); - break; + for (size_t i = 0; i < NUMBER_OF(m_modAssignments); ++ i) { + ModAssignments mos; + if (m_parentKeymap) + mos = m_parentKeymap->m_modAssignments[i]; + else { + // set default modifiers + if (i < Modifier::Type_BASIC) { + Keyboard::Mods mods = + i_keyboard.getModifiers(static_cast(i)); + for (Keyboard::Mods::iterator j = mods.begin(); j != mods.end(); ++ j) { + ModAssignment ma; + ma.m_assignOperator = AO_add; + ma.m_assignMode = AM_normal; + ma.m_key = *j; + mos.push_back(ma); + } + } + } + + // mod adjust + for (ModAssignments::iterator mai = m_modAssignments[i].begin(); + mai != m_modAssignments[i].end(); ++ mai) { + ModAssignment ma = *mai; + ma.m_assignOperator = AO_new; + switch ((*mai).m_assignOperator) { + case AO_new: { + mos.clear(); + mos.push_back(ma); + break; + } + case AO_add: { + mos.push_back(ma); + break; + } + case AO_sub: { + for (ModAssignments::iterator j = mos.begin(); + j != mos.end(); ++ j) + if ((*j).m_key == ma.m_key) { + mos.erase(j); + break; + } + break; + } + case AO_overwrite: { + for (ModAssignments::iterator j = mos.begin(); + j != mos.end(); ++ j) + (*j).m_assignMode = (*mai).m_assignMode; + break; + } + } + } + + // erase redundant modifiers + for (ModAssignments::iterator j = mos.begin(); j != mos.end(); ++ j) { + ModAssignments::iterator k; + for (k = j, ++ k; k != mos.end(); ++ k) + if ((*k).m_key == (*j).m_key) + break; + if (k != mos.end()) { + k = j; + ++ j; + mos.erase(k); + break; + } + } + + m_modAssignments[i] = mos; } - case AO_sub: - { - for (ModAssignments::iterator j = mos.begin(); - j != mos.end(); ++ j) - if ((*j).m_key == ma.m_key) - { - mos.erase(j); - break; - } - break; - } - case AO_overwrite: - { - for (ModAssignments::iterator j = mos.begin(); - j != mos.end(); ++ j) - (*j).m_assignMode = (*mai).m_assignMode; - break; - } - } - } - - // erase redundant modifiers - for (ModAssignments::iterator j = mos.begin(); j != mos.end(); ++ j) - { - ModAssignments::iterator k; - for (k = j, ++ k; k != mos.end(); ++ k) - if ((*k).m_key == (*j).m_key) - break; - if (k != mos.end()) - { - k = j; - ++ j; - mos.erase(k); - break; - } - } - - m_modAssignments[i] = mos; - } } // describe void Keymap::describe(tostream &i_ost, DescribeParam *i_dp) const { - // Is this keymap already described ? - { - DescribeParam::DescribedKeymap::iterator - i = std::find(i_dp->m_dkeymap.begin(), i_dp->m_dkeymap.end(), this); - if (i != i_dp->m_dkeymap.end()) - return; // yes! - i_dp->m_dkeymap.push_back(this); - } - - switch (m_type) - { - case Type_keymap: - i_ost << _T("keymap ") << m_name; - break; - case Type_windowAnd: - i_ost << _T("window ") << m_name << _T(" "); - if (m_windowTitle.str() == _T(".*")) - i_ost << _T("/") << m_windowClass.str() << _T("/"); - else - i_ost << _T("( /") << m_windowClass.str() << _T("/ && /") - << m_windowTitle.str() << _T("/ )"); - break; - case Type_windowOr: - i_ost << _T("window ") << m_name << _T(" ( /") - << m_windowClass.str() << _T("/ || /") << m_windowTitle.str() - << _T("/ )"); - break; - } - if (m_parentKeymap) - i_ost << _T(" : ") << m_parentKeymap->m_name; - i_ost << _T(" = ") << *m_defaultKeySeq << std::endl; - - // describe modifiers - if (i_dp->m_doesDescribeModifiers) - { - for (int t = Modifier::Type_begin; t != Modifier::Type_end; ++ t) - { - Modifier::Type type = static_cast(t); - const Keymap::ModAssignments &ma = getModAssignments(type); - if (ma.size()) - { - i_ost << _T(" mod ") << type << _T("\t= "); - for (Keymap::ModAssignments::const_iterator - j = ma.begin(); j != ma.end(); ++ j) + // Is this keymap already described ? { - switch (j->m_assignMode) - { - case Keymap::AM_true: i_ost << _T("!"); break; - case Keymap::AM_oneShot: i_ost << _T("!!"); break; - case Keymap::AM_oneShotRepeatable: i_ost << _T("!!!"); break; - default: - break; - } - i_ost << *j->m_key << _T(" "); + DescribeParam::DescribedKeymap::iterator + i = std::find(i_dp->m_dkeymap.begin(), i_dp->m_dkeymap.end(), this); + if (i != i_dp->m_dkeymap.end()) + return; // yes! + i_dp->m_dkeymap.push_back(this); + } + + switch (m_type) { + case Type_keymap: + i_ost << _T("keymap ") << m_name; + break; + case Type_windowAnd: + i_ost << _T("window ") << m_name << _T(" "); + if (m_windowTitle.str() == _T(".*")) + i_ost << _T("/") << m_windowClass.str() << _T("/"); + else + i_ost << _T("( /") << m_windowClass.str() << _T("/ && /") + << m_windowTitle.str() << _T("/ )"); + break; + case Type_windowOr: + i_ost << _T("window ") << m_name << _T(" ( /") + << m_windowClass.str() << _T("/ || /") << m_windowTitle.str() + << _T("/ )"); + break; + } + if (m_parentKeymap) + i_ost << _T(" : ") << m_parentKeymap->m_name; + i_ost << _T(" = ") << *m_defaultKeySeq << std::endl; + + // describe modifiers + if (i_dp->m_doesDescribeModifiers) { + for (int t = Modifier::Type_begin; t != Modifier::Type_end; ++ t) { + Modifier::Type type = static_cast(t); + const Keymap::ModAssignments &ma = getModAssignments(type); + if (ma.size()) { + i_ost << _T(" mod ") << type << _T("\t= "); + for (Keymap::ModAssignments::const_iterator + j = ma.begin(); j != ma.end(); ++ j) { + switch (j->m_assignMode) { + case Keymap::AM_true: + i_ost << _T("!"); + break; + case Keymap::AM_oneShot: + i_ost << _T("!!"); + break; + case Keymap::AM_oneShotRepeatable: + i_ost << _T("!!!"); + break; + default: + break; + } + i_ost << *j->m_key << _T(" "); + } + i_ost << std::endl; + } + } + i_dp->m_doesDescribeModifiers = false; } + + typedef std::vector SortedKeyAssignments; + SortedKeyAssignments ska; + for (size_t i = 0; i < HASHED_KEY_ASSIGNMENT_SIZE; ++ i) { + const KeyAssignments &ka = m_hashedKeyAssignments[i]; + for (KeyAssignments::const_iterator j = ka.begin(); j != ka.end(); ++ j) + ska.push_back(*j); + } + std::sort(ska.begin(), ska.end()); + for (SortedKeyAssignments::iterator i = ska.begin(); i != ska.end(); ++ i) { + // Is this key assignment already described ? + DescribeParam::DescribedKeys::iterator + j = std::find(i_dp->m_dk.begin(), i_dp->m_dk.end(), i->m_modifiedKey); + if (j != i_dp->m_dk.end()) + continue; // yes! + + // check if the key is an event + Key **e; + for (e = Event::events; *e; ++ e) + if (i->m_modifiedKey.m_key == *e) + break; + if (*e) + i_ost << _T(" event ") << *i->m_modifiedKey.m_key; + else + i_ost << _T(" key ") << i->m_modifiedKey; + i_ost << _T("\t= ") << *i->m_keySeq << std::endl; + i_dp->m_dk.push_back(i->m_modifiedKey); + } + i_ost << std::endl; - } - } - i_dp->m_doesDescribeModifiers = false; - } - - typedef std::vector SortedKeyAssignments; - SortedKeyAssignments ska; - for (size_t i = 0; i < HASHED_KEY_ASSIGNMENT_SIZE; ++ i) - { - const KeyAssignments &ka = m_hashedKeyAssignments[i]; - for (KeyAssignments::const_iterator j = ka.begin(); j != ka.end(); ++ j) - ska.push_back(*j); - } - std::sort(ska.begin(), ska.end()); - for (SortedKeyAssignments::iterator i = ska.begin(); i != ska.end(); ++ i) - { - // Is this key assignment already described ? - DescribeParam::DescribedKeys::iterator - j = std::find(i_dp->m_dk.begin(), i_dp->m_dk.end(), i->m_modifiedKey); - if (j != i_dp->m_dk.end()) - continue; // yes! - - // check if the key is an event - Key **e; - for (e = Event::events; *e; ++ e) - if (i->m_modifiedKey.m_key == *e) - break; - if (*e) - i_ost << _T(" event ") << *i->m_modifiedKey.m_key; - else - i_ost << _T(" key ") << i->m_modifiedKey; - i_ost << _T("\t= ") << *i->m_keySeq << std::endl; - i_dp->m_dk.push_back(i->m_modifiedKey); - } - - i_ost << std::endl; - - if (m_parentKeymap) - m_parentKeymap->describe(i_ost, i_dp); + + if (m_parentKeymap) + m_parentKeymap->describe(i_ost, i_dp); } // set default keySeq and parent keymap if default keySeq has not been set bool Keymap::setIfNotYet(KeySeq *i_keySeq, Keymap *i_parentKeymap) { - if (m_defaultKeySeq) - return false; - m_defaultKeySeq = i_keySeq; - m_parentKeymap = i_parentKeymap; - return true; + if (m_defaultKeySeq) + return false; + m_defaultKeySeq = i_keySeq; + m_parentKeymap = i_parentKeymap; + return true; } // stream output extern tostream &operator<<(tostream &i_ost, const Keymap *i_keymap) { - return i_ost << i_keymap->getName(); + return i_ost << i_keymap->getName(); } @@ -534,43 +507,43 @@ Keymaps::Keymaps() // search by name Keymap *Keymaps::searchByName(const tstringi &i_name) { - for (KeymapList::iterator - i = m_keymapList.begin(); i != m_keymapList.end(); ++ i) - if ((*i).getName() == i_name) - return &*i; - return NULL; + for (KeymapList::iterator + i = m_keymapList.begin(); i != m_keymapList.end(); ++ i) + if ((*i).getName() == i_name) + return &*i; + return NULL; } // search window void Keymaps::searchWindow(KeymapPtrList *o_keymapPtrList, - const tstringi &i_className, - const tstringi &i_titleName) + const tstringi &i_className, + const tstringi &i_titleName) { - o_keymapPtrList->clear(); - for (KeymapList::iterator - i = m_keymapList.begin(); i != m_keymapList.end(); ++ i) - if ((*i).doesSameWindow(i_className, i_titleName)) - o_keymapPtrList->push_back(&(*i)); + o_keymapPtrList->clear(); + for (KeymapList::iterator + i = m_keymapList.begin(); i != m_keymapList.end(); ++ i) + if ((*i).doesSameWindow(i_className, i_titleName)) + o_keymapPtrList->push_back(&(*i)); } // add keymap Keymap *Keymaps::add(const Keymap &i_keymap) { - if (Keymap *k = searchByName(i_keymap.getName())) - return k; - m_keymapList.push_front(i_keymap); - return &m_keymapList.front(); + if (Keymap *k = searchByName(i_keymap.getName())) + return k; + m_keymapList.push_front(i_keymap); + return &m_keymapList.front(); } // adjust modifier void Keymaps::adjustModifier(Keyboard &i_keyboard) { - for (KeymapList::reverse_iterator i = m_keymapList.rbegin(); - i != m_keymapList.rend(); ++ i) - (*i).adjustModifier(i_keyboard); + for (KeymapList::reverse_iterator i = m_keymapList.rbegin(); + i != m_keymapList.rend(); ++ i) + (*i).adjustModifier(i_keyboard); } @@ -581,23 +554,22 @@ void Keymaps::adjustModifier(Keyboard &i_keyboard) // add a named keyseq (name can be empty) KeySeq *KeySeqs::add(const KeySeq &i_keySeq) { - if (!i_keySeq.getName().empty()) - { - KeySeq *ks = searchByName(i_keySeq.getName()); - if (ks) - return &(*ks = i_keySeq); - } - m_keySeqList.push_front(i_keySeq); - return &m_keySeqList.front(); + if (!i_keySeq.getName().empty()) { + KeySeq *ks = searchByName(i_keySeq.getName()); + if (ks) + return &(*ks = i_keySeq); + } + m_keySeqList.push_front(i_keySeq); + return &m_keySeqList.front(); } // search by name KeySeq *KeySeqs::searchByName(const tstringi &i_name) { - for (KeySeqList::iterator - i = m_keySeqList.begin(); i != m_keySeqList.end(); ++ i) - if ((*i).getName() == i_name) - return &(*i); - return NULL; + for (KeySeqList::iterator + i = m_keySeqList.begin(); i != m_keySeqList.end(); ++ i) + if ((*i).getName() == i_name) + return &(*i); + return NULL; } diff --git a/keymap.h b/keymap.h index 74eb1ca..0452e66 100644 --- a/keymap.h +++ b/keymap.h @@ -14,27 +14,26 @@ class Action { public: - /// - enum Type - { - Type_key, /// - Type_keySeq, /// - Type_function, /// - }; + /// + enum Type { + Type_key, /// + Type_keySeq, /// + Type_function, /// + }; private: - Action(const Action &i_action); - + Action(const Action &i_action); + public: - Action() { } - /// - virtual ~Action() { } - /// - virtual Type getType() const = 0; - /// create clone - virtual Action *clone() const = 0; - /// stream output - virtual tostream &output(tostream &i_ost) const = 0; + Action() { } + /// + virtual ~Action() { } + /// + virtual Type getType() const = 0; + /// create clone + virtual Action *clone() const = 0; + /// stream output + virtual tostream &output(tostream &i_ost) const = 0; }; /// @@ -44,21 +43,21 @@ tostream &operator<<(tostream &i_ost, const Action &i_action); class ActionKey : public Action { public: - /// - const ModifiedKey m_modifiedKey; + /// + const ModifiedKey m_modifiedKey; private: - ActionKey(const ActionKey &i_actionKey); - + ActionKey(const ActionKey &i_actionKey); + public: - /// - ActionKey(const ModifiedKey &i_mk); - /// - virtual Type getType() const; - /// create clone - virtual Action *clone() const; - /// stream output - virtual tostream &output(tostream &i_ost) const; + /// + ActionKey(const ModifiedKey &i_mk); + /// + virtual Type getType() const; + /// create clone + virtual Action *clone() const; + /// stream output + virtual tostream &output(tostream &i_ost) const; }; @@ -67,20 +66,20 @@ class KeySeq; class ActionKeySeq : public Action { public: - KeySeq * const m_keySeq; /// + KeySeq * const m_keySeq; /// private: - ActionKeySeq(const ActionKeySeq &i_actionKeySeq); - + ActionKeySeq(const ActionKeySeq &i_actionKeySeq); + public: - /// - ActionKeySeq(KeySeq *i_keySeq); - /// - virtual Type getType() const; - /// create clone - virtual Action *clone() const; - /// stream output - virtual tostream &output(tostream &i_ost) const; + /// + ActionKeySeq(KeySeq *i_keySeq); + /// + virtual Type getType() const; + /// create clone + virtual Action *clone() const; + /// stream output + virtual tostream &output(tostream &i_ost) const; }; @@ -88,24 +87,24 @@ public: class ActionFunction : public Action { public: - FunctionData * const m_functionData; /// function data - const Modifier m_modifier; /// modifier for &Sync + FunctionData * const m_functionData; /// function data + const Modifier m_modifier; /// modifier for &Sync private: - ActionFunction(const ActionFunction &i_actionFunction); - + ActionFunction(const ActionFunction &i_actionFunction); + public: - /// - ActionFunction(FunctionData *i_functionData, - Modifier i_modifier = Modifier()); - /// - virtual ~ActionFunction(); - /// - virtual Type getType() const; - /// create clone - virtual Action *clone() const; - /// stream output - virtual tostream &output(tostream &i_ost) const; + /// + ActionFunction(FunctionData *i_functionData, + Modifier i_modifier = Modifier()); + /// + virtual ~ActionFunction(); + /// + virtual Type getType() const; + /// create clone + virtual Action *clone() const; + /// stream output + virtual tostream &output(tostream &i_ost) const; }; @@ -113,60 +112,67 @@ public: class KeySeq { public: - typedef std::vector Actions; /// + typedef std::vector Actions; /// private: - Actions m_actions; /// - tstringi m_name; /// - Modifier::Type m_mode; /** Either Modifier::Type_KEYSEQ + Actions m_actions; /// + tstringi m_name; /// + Modifier::Type m_mode; /** Either Modifier::Type_KEYSEQ or Modifier::Type_ASSIGN */ private: - /// - void copy(); - /// - void clear(); - + /// + void copy(); + /// + void clear(); + public: - /// - KeySeq(const tstringi &i_name); - /// - KeySeq(const KeySeq &i_ks); - /// - ~KeySeq(); - - /// - const Actions &getActions() const { return m_actions; } - - /// - KeySeq &operator=(const KeySeq &i_ks); - - /// add - KeySeq &add(const Action &i_action); - - /// get the first modified key of this key sequence - ModifiedKey getFirstModifiedKey() const; - - /// - const tstringi &getName() const { return m_name; } - - /// stream output - friend tostream &operator<<(tostream &i_ost, const KeySeq &i_ks); - - /// - bool isCorrectMode(Modifier::Type i_mode) { return m_mode <= i_mode; } - - /// - void setMode(Modifier::Type i_mode) - { - if (m_mode < i_mode) - m_mode = i_mode; - ASSERT( m_mode == Modifier::Type_KEYSEQ || - m_mode == Modifier::Type_ASSIGN); - } - - /// - Modifier::Type getMode() const { return m_mode; } + /// + KeySeq(const tstringi &i_name); + /// + KeySeq(const KeySeq &i_ks); + /// + ~KeySeq(); + + /// + const Actions &getActions() const { + return m_actions; + } + + /// + KeySeq &operator=(const KeySeq &i_ks); + + /// add + KeySeq &add(const Action &i_action); + + /// get the first modified key of this key sequence + ModifiedKey getFirstModifiedKey() const; + + /// + const tstringi &getName() const { + return m_name; + } + + /// stream output + friend tostream &operator<<(tostream &i_ost, const KeySeq &i_ks); + + /// + bool isCorrectMode(Modifier::Type i_mode) { + return m_mode <= i_mode; + } + + /// + void setMode(Modifier::Type i_mode) { + if (m_mode < i_mode) + m_mode = i_mode; + ASSERT( m_mode == Modifier::Type_KEYSEQ || + m_mode == Modifier::Type_ASSIGN); + } + + /// + Modifier::Type getMode() const { + return m_mode; + } }; @@ -174,147 +180,152 @@ public: class Keymap { public: - /// - enum Type - { - Type_keymap, /// this is keymap - Type_windowAnd, /// this is window && - Type_windowOr, /// this is window || - }; - /// - enum AssignOperator - { - AO_new, /// = - AO_add, /// += - AO_sub, /// -= - AO_overwrite, /// !, !! - }; - /// - enum AssignMode - { - AM_notModifier, /// not modifier - AM_normal, /// normal modifier - AM_true, /** ! true modifier(doesn't + /// + enum Type { + Type_keymap, /// this is keymap + Type_windowAnd, /// this is window && + Type_windowOr, /// this is window || + }; + /// + enum AssignOperator { + AO_new, /// = + AO_add, /// += + AO_sub, /// -= + AO_overwrite, /// !, !! + }; + /// + enum AssignMode { + AM_notModifier, /// not modifier + AM_normal, /// normal modifier + AM_true, /** ! true modifier(doesn't generate scan code) */ - AM_oneShot, /// !! one shot modifier - AM_oneShotRepeatable, /// !!! one shot modifier - }; - - /// key assignment - class KeyAssignment - { - public: - ModifiedKey m_modifiedKey; /// - KeySeq *m_keySeq; /// - - public: - /// - KeyAssignment(const ModifiedKey &i_modifiedKey, KeySeq *i_keySeq) - : m_modifiedKey(i_modifiedKey), m_keySeq(i_keySeq) { } - /// - KeyAssignment(const KeyAssignment &i_o) - : m_modifiedKey(i_o.m_modifiedKey), m_keySeq(i_o.m_keySeq) { } - /// - bool operator<(const KeyAssignment &i_o) const - { return m_modifiedKey < i_o.m_modifiedKey; } - }; - - /// modifier assignments - class ModAssignment - { - public: - AssignOperator m_assignOperator; /// - AssignMode m_assignMode; /// - Key *m_key; /// - }; - typedef std::list ModAssignments; /// - - /// parameter for describe(); - class DescribeParam - { - private: - typedef std::list DescribedKeys; - typedef std::list DescribedKeymap; - friend class Keymap; - - private: - DescribedKeys m_dk; - DescribedKeymap m_dkeymap; - bool m_doesDescribeModifiers; - - public: - DescribeParam() : m_doesDescribeModifiers(true) { } - }; - + AM_oneShot, /// !! one shot modifier + AM_oneShotRepeatable, /// !!! one shot modifier + }; + + /// key assignment + class KeyAssignment + { + public: + ModifiedKey m_modifiedKey; /// + KeySeq *m_keySeq; /// + + public: + /// + KeyAssignment(const ModifiedKey &i_modifiedKey, KeySeq *i_keySeq) + : m_modifiedKey(i_modifiedKey), m_keySeq(i_keySeq) { } + /// + KeyAssignment(const KeyAssignment &i_o) + : m_modifiedKey(i_o.m_modifiedKey), m_keySeq(i_o.m_keySeq) { } + /// + bool operator<(const KeyAssignment &i_o) const { + return m_modifiedKey < i_o.m_modifiedKey; + } + }; + + /// modifier assignments + class ModAssignment + { + public: + AssignOperator m_assignOperator; /// + AssignMode m_assignMode; /// + Key *m_key; /// + }; + typedef std::list ModAssignments; /// + + /// parameter for describe(); + class DescribeParam + { + private: + typedef std::list DescribedKeys; + typedef std::list DescribedKeymap; + friend class Keymap; + + private: + DescribedKeys m_dk; + DescribedKeymap m_dkeymap; + bool m_doesDescribeModifiers; + + public: + DescribeParam() : m_doesDescribeModifiers(true) { } + }; + private: - /// key assignments (hashed by first scan code) - typedef std::list KeyAssignments; - enum { - HASHED_KEY_ASSIGNMENT_SIZE = 32, /// - }; + /// key assignments (hashed by first scan code) + typedef std::list KeyAssignments; + enum { + HASHED_KEY_ASSIGNMENT_SIZE = 32, /// + }; private: - KeyAssignments m_hashedKeyAssignments[HASHED_KEY_ASSIGNMENT_SIZE]; /// - - /// modifier assignments - ModAssignments m_modAssignments[Modifier::Type_ASSIGN]; - - Type m_type; /// type - tstringi m_name; /// keymap name - tregex m_windowClass; /// window class name regexp - tregex m_windowTitle; /// window title name regexp - - KeySeq *m_defaultKeySeq; /// default keySeq - Keymap *m_parentKeymap; /// parent keymap - + KeyAssignments m_hashedKeyAssignments[HASHED_KEY_ASSIGNMENT_SIZE]; /// + + /// modifier assignments + ModAssignments m_modAssignments[Modifier::Type_ASSIGN]; + + Type m_type; /// type + tstringi m_name; /// keymap name + tregex m_windowClass; /// window class name regexp + tregex m_windowTitle; /// window title name regexp + + KeySeq *m_defaultKeySeq; /// default keySeq + Keymap *m_parentKeymap; /// parent keymap + private: - /// - KeyAssignments &getKeyAssignments(const ModifiedKey &i_mk); - /// - const KeyAssignments &getKeyAssignments(const ModifiedKey &i_mk) const; + /// + KeyAssignments &getKeyAssignments(const ModifiedKey &i_mk); + /// + const KeyAssignments &getKeyAssignments(const ModifiedKey &i_mk) const; public: - /// - Keymap(Type i_type, - const tstringi &i_name, - const tstringi &i_windowClass, - const tstringi &i_windowTitle, - KeySeq *i_defaultKeySeq, - Keymap *i_parentKeymap); - - /// add a key assignment; - void addAssignment(const ModifiedKey &i_mk, KeySeq *i_keySeq); - - /// add modifier - void addModifier(Modifier::Type i_mt, AssignOperator i_ao, - AssignMode i_am, Key *i_key); - - /// search - const KeyAssignment *searchAssignment(const ModifiedKey &i_mk) const; - - /// get - const KeySeq *getDefaultKeySeq() const { return m_defaultKeySeq; } - /// - Keymap *getParentKeymap() const { return m_parentKeymap; } - /// - const tstringi &getName() const { return m_name; } - - /// does same window - bool doesSameWindow(const tstringi i_className, - const tstringi &i_titleName); - - /// adjust modifier - void adjustModifier(Keyboard &i_keyboard); - - /// get modAssignments - const ModAssignments &getModAssignments(Modifier::Type i_mt) const - { return m_modAssignments[i_mt]; } - - /// describe - void describe(tostream &i_ost, DescribeParam *i_dp) const; - - /// set default keySeq and parent keymap if default keySeq has not been set - bool setIfNotYet(KeySeq *i_keySeq, Keymap *i_parentKeymap); + /// + Keymap(Type i_type, + const tstringi &i_name, + const tstringi &i_windowClass, + const tstringi &i_windowTitle, + KeySeq *i_defaultKeySeq, + Keymap *i_parentKeymap); + + /// add a key assignment; + void addAssignment(const ModifiedKey &i_mk, KeySeq *i_keySeq); + + /// add modifier + void addModifier(Modifier::Type i_mt, AssignOperator i_ao, + AssignMode i_am, Key *i_key); + + /// search + const KeyAssignment *searchAssignment(const ModifiedKey &i_mk) const; + + /// get + const KeySeq *getDefaultKeySeq() const { + return m_defaultKeySeq; + } + /// + Keymap *getParentKeymap() const { + return m_parentKeymap; + } + /// + const tstringi &getName() const { + return m_name; + } + + /// does same window + bool doesSameWindow(const tstringi i_className, + const tstringi &i_titleName); + + /// adjust modifier + void adjustModifier(Keyboard &i_keyboard); + + /// get modAssignments + const ModAssignments &getModAssignments(Modifier::Type i_mt) const { + return m_modAssignments[i_mt]; + } + + /// describe + void describe(tostream &i_ost, DescribeParam *i_dp) const; + + /// set default keySeq and parent keymap if default keySeq has not been set + bool setIfNotYet(KeySeq *i_keySeq, Keymap *i_parentKeymap); }; @@ -326,32 +337,32 @@ extern tostream &operator<<(tostream &i_ost, const Keymap *i_keymap); class Keymaps { public: - typedef std::list KeymapPtrList; /// - + typedef std::list KeymapPtrList; /// + private: - typedef std::list KeymapList; /// + typedef std::list KeymapList; /// private: - KeymapList m_keymapList; /** pointer into keymaps may + KeymapList m_keymapList; /** pointer into keymaps may exist */ - + public: - /// - Keymaps(); - - /// search by name - Keymap *searchByName(const tstringi &i_name); - - /// search window - void searchWindow(KeymapPtrList *o_keymapPtrList, - const tstringi &i_className, - const tstringi &i_titleName); - - /// add keymap - Keymap *add(const Keymap &i_keymap); - - /// adjust modifier - void adjustModifier(Keyboard &i_keyboard); + /// + Keymaps(); + + /// search by name + Keymap *searchByName(const tstringi &i_name); + + /// search window + void searchWindow(KeymapPtrList *o_keymapPtrList, + const tstringi &i_className, + const tstringi &i_titleName); + + /// add keymap + Keymap *add(const Keymap &i_keymap); + + /// adjust modifier + void adjustModifier(Keyboard &i_keyboard); }; @@ -359,17 +370,17 @@ public: class KeySeqs { private: - typedef std::list KeySeqList; /// + typedef std::list KeySeqList; /// private: - KeySeqList m_keySeqList; /// - + KeySeqList m_keySeqList; /// + public: - /// add a named keyseq (name can be empty) - KeySeq *add(const KeySeq &i_keySeq); - - /// search by name - KeySeq *searchByName(const tstringi &i_name); + /// add a named keyseq (name can be empty) + KeySeq *add(const KeySeq &i_keySeq); + + /// search by name + KeySeq *searchByName(const tstringi &i_name); }; diff --git a/layoutmanager.cpp b/layoutmanager.cpp index eddd48f..445a54e 100644 --- a/layoutmanager.cpp +++ b/layoutmanager.cpp @@ -10,9 +10,9 @@ // LayoutManager::LayoutManager(HWND i_hwnd) - : m_hwnd(i_hwnd), - m_smallestRestriction(RESTRICT_NONE), - m_largestRestriction(RESTRICT_NONE) + : m_hwnd(i_hwnd), + m_smallestRestriction(RESTRICT_NONE), + m_largestRestriction(RESTRICT_NONE) { } @@ -20,16 +20,15 @@ LayoutManager::LayoutManager(HWND i_hwnd) // specified by i_size void LayoutManager::restrictSmallestSize(Restrict i_restrict, SIZE *i_size) { - m_smallestRestriction = i_restrict; - if (i_size) - m_smallestSize = *i_size; - else - { - RECT rc; - GetWindowRect(m_hwnd, &rc); - m_smallestSize.cx = rc.right - rc.left; - m_smallestSize.cy = rc.bottom - rc.top; - } + m_smallestRestriction = i_restrict; + if (i_size) + m_smallestSize = *i_size; + else { + RECT rc; + GetWindowRect(m_hwnd, &rc); + m_smallestSize.cx = rc.right - rc.left; + m_smallestSize.cy = rc.bottom - rc.top; + } } @@ -37,206 +36,199 @@ void LayoutManager::restrictSmallestSize(Restrict i_restrict, SIZE *i_size) // specified by i_size void LayoutManager::restrictLargestSize(Restrict i_restrict, SIZE *i_size) { - m_largestRestriction = i_restrict; - if (i_size) - m_largestSize = *i_size; - else - { - RECT rc; - GetWindowRect(m_hwnd, &rc); - m_largestSize.cx = rc.right - rc.left; - m_largestSize.cy = rc.bottom - rc.top; - } + m_largestRestriction = i_restrict; + if (i_size) + m_largestSize = *i_size; + else { + RECT rc; + GetWindowRect(m_hwnd, &rc); + m_largestSize.cx = rc.right - rc.left; + m_largestSize.cy = rc.bottom - rc.top; + } } // bool LayoutManager::addItem(HWND i_hwnd, Origin i_originLeft, - Origin i_originTop, - Origin i_originRight, Origin i_originBottom) + Origin i_originTop, + Origin i_originRight, Origin i_originBottom) { - Item item; - if (!i_hwnd) - return false; - item.m_hwnd = i_hwnd; + Item item; + if (!i_hwnd) + return false; + item.m_hwnd = i_hwnd; #ifdef MAYU64 - if (!(GetWindowLongPtr(i_hwnd, GWL_STYLE) & WS_CHILD)) + if (!(GetWindowLongPtr(i_hwnd, GWL_STYLE) & WS_CHILD)) #else - if (!(GetWindowLong(i_hwnd, GWL_STYLE) & WS_CHILD)) + if (!(GetWindowLong(i_hwnd, GWL_STYLE) & WS_CHILD)) #endif - return false; - item.m_hwndParent = GetParent(i_hwnd); - if (!item.m_hwndParent) - return false; - getChildWindowRect(item.m_hwnd, &item.m_rc); - GetWindowRect(item.m_hwndParent, &item.m_rcParent); - item.m_origin[0] = i_originLeft; - item.m_origin[1] = i_originTop; - item.m_origin[2] = i_originRight; - item.m_origin[3] = i_originBottom; - - m_items.push_back(item); - return true; + return false; + item.m_hwndParent = GetParent(i_hwnd); + if (!item.m_hwndParent) + return false; + getChildWindowRect(item.m_hwnd, &item.m_rc); + GetWindowRect(item.m_hwndParent, &item.m_rcParent); + item.m_origin[0] = i_originLeft; + item.m_origin[1] = i_originTop; + item.m_origin[2] = i_originRight; + item.m_origin[3] = i_originBottom; + + m_items.push_back(item); + return true; } // void LayoutManager::adjust() const { - for (Items::const_iterator i = m_items.begin(); i != m_items.end(); ++ i) - { - RECT rc; - GetWindowRect(i->m_hwndParent, &rc); - - struct { int m_width, m_pos; int m_curWidth; LONG *m_out; } - pos[4] = - { - { rcWidth(&i->m_rcParent), i->m_rc.left, rcWidth(&rc), &rc.left }, - { rcHeight(&i->m_rcParent), i->m_rc.top, rcHeight(&rc), &rc.top }, - { rcWidth(&i->m_rcParent), i->m_rc.right, rcWidth(&rc), &rc.right }, - { rcHeight(&i->m_rcParent), i->m_rc.bottom, rcHeight(&rc), &rc.bottom } - }; - for (int j = 0; j < 4; ++ j) - { - switch (i->m_origin[j]) - { - case ORIGIN_LEFT_EDGE: - *pos[j].m_out = pos[j].m_pos; - break; - case ORIGIN_CENTER: - *pos[j].m_out = pos[j].m_curWidth / 2 - - (pos[j].m_width / 2 - pos[j].m_pos); - break; - case ORIGIN_RIGHT_EDGE: - *pos[j].m_out = pos[j].m_curWidth - - (pos[j].m_width - pos[j].m_pos); - break; - } - } - MoveWindow(i->m_hwnd, rc.left, rc.top, - rcWidth(&rc), rcHeight(&rc), FALSE); - } + for (Items::const_iterator i = m_items.begin(); i != m_items.end(); ++ i) { + RECT rc; + GetWindowRect(i->m_hwndParent, &rc); + + struct { + int m_width, m_pos; + int m_curWidth; + LONG *m_out; + } + pos[4] = { + { rcWidth(&i->m_rcParent), i->m_rc.left, rcWidth(&rc), &rc.left }, + { rcHeight(&i->m_rcParent), i->m_rc.top, rcHeight(&rc), &rc.top }, + { rcWidth(&i->m_rcParent), i->m_rc.right, rcWidth(&rc), &rc.right }, + { rcHeight(&i->m_rcParent), i->m_rc.bottom, rcHeight(&rc), &rc.bottom } + }; + for (int j = 0; j < 4; ++ j) { + switch (i->m_origin[j]) { + case ORIGIN_LEFT_EDGE: + *pos[j].m_out = pos[j].m_pos; + break; + case ORIGIN_CENTER: + *pos[j].m_out = pos[j].m_curWidth / 2 + - (pos[j].m_width / 2 - pos[j].m_pos); + break; + case ORIGIN_RIGHT_EDGE: + *pos[j].m_out = pos[j].m_curWidth + - (pos[j].m_width - pos[j].m_pos); + break; + } + } + MoveWindow(i->m_hwnd, rc.left, rc.top, + rcWidth(&rc), rcHeight(&rc), FALSE); + } } // draw size box BOOL LayoutManager::wmPaint() { - PAINTSTRUCT ps; - HDC hdc = BeginPaint(m_hwnd, &ps); - RECT rc; - GetClientRect(m_hwnd, &rc); - rc.left = rc.right - GetSystemMetrics(SM_CXHTHUMB); - rc.top = rc.bottom - GetSystemMetrics(SM_CYVTHUMB); - DrawFrameControl(hdc, &rc, DFC_SCROLL, DFCS_SCROLLSIZEGRIP); - EndPaint(m_hwnd, &ps); - return TRUE; + PAINTSTRUCT ps; + HDC hdc = BeginPaint(m_hwnd, &ps); + RECT rc; + GetClientRect(m_hwnd, &rc); + rc.left = rc.right - GetSystemMetrics(SM_CXHTHUMB); + rc.top = rc.bottom - GetSystemMetrics(SM_CYVTHUMB); + DrawFrameControl(hdc, &rc, DFC_SCROLL, DFCS_SCROLLSIZEGRIP); + EndPaint(m_hwnd, &ps); + return TRUE; } // size restriction BOOL LayoutManager::wmSizing(int i_edge, RECT *io_rc) { - switch (i_edge) - { - case WMSZ_TOPLEFT: - case WMSZ_LEFT: - case WMSZ_BOTTOMLEFT: - if (m_smallestRestriction & RESTRICT_HORIZONTALLY) - if (io_rc->right - io_rc->left < m_smallestSize.cx) - io_rc->left = io_rc->right - m_smallestSize.cx; - if (m_largestRestriction & RESTRICT_HORIZONTALLY) - if (m_largestSize.cx < io_rc->right - io_rc->left) - io_rc->left = io_rc->right - m_largestSize.cx; - break; - } - switch (i_edge) - { - case WMSZ_TOPRIGHT: - case WMSZ_RIGHT: - case WMSZ_BOTTOMRIGHT: - if (m_smallestRestriction & RESTRICT_HORIZONTALLY) - if (io_rc->right - io_rc->left < m_smallestSize.cx) - io_rc->right = io_rc->left + m_smallestSize.cx; - if (m_largestRestriction & RESTRICT_HORIZONTALLY) - if (m_largestSize.cx < io_rc->right - io_rc->left) - io_rc->right = io_rc->left + m_largestSize.cx; - break; - } - switch (i_edge) - { - case WMSZ_TOP: - case WMSZ_TOPLEFT: - case WMSZ_TOPRIGHT: - if (m_smallestRestriction & RESTRICT_VERTICALLY) - if (io_rc->bottom - io_rc->top < m_smallestSize.cy) - io_rc->top = io_rc->bottom - m_smallestSize.cy; - if (m_largestRestriction & RESTRICT_VERTICALLY) - if (m_largestSize.cy < io_rc->bottom - io_rc->top) - io_rc->top = io_rc->bottom - m_largestSize.cy; - break; - } - switch (i_edge) - { - case WMSZ_BOTTOM: - case WMSZ_BOTTOMLEFT: - case WMSZ_BOTTOMRIGHT: - if (m_smallestRestriction & RESTRICT_VERTICALLY) - if (io_rc->bottom - io_rc->top < m_smallestSize.cy) - io_rc->bottom = io_rc->top + m_smallestSize.cy; - if (m_largestRestriction & RESTRICT_VERTICALLY) - if (m_largestSize.cy < io_rc->bottom - io_rc->top) - io_rc->bottom = io_rc->top + m_largestSize.cy; - break; - } - return TRUE; + switch (i_edge) { + case WMSZ_TOPLEFT: + case WMSZ_LEFT: + case WMSZ_BOTTOMLEFT: + if (m_smallestRestriction & RESTRICT_HORIZONTALLY) + if (io_rc->right - io_rc->left < m_smallestSize.cx) + io_rc->left = io_rc->right - m_smallestSize.cx; + if (m_largestRestriction & RESTRICT_HORIZONTALLY) + if (m_largestSize.cx < io_rc->right - io_rc->left) + io_rc->left = io_rc->right - m_largestSize.cx; + break; + } + switch (i_edge) { + case WMSZ_TOPRIGHT: + case WMSZ_RIGHT: + case WMSZ_BOTTOMRIGHT: + if (m_smallestRestriction & RESTRICT_HORIZONTALLY) + if (io_rc->right - io_rc->left < m_smallestSize.cx) + io_rc->right = io_rc->left + m_smallestSize.cx; + if (m_largestRestriction & RESTRICT_HORIZONTALLY) + if (m_largestSize.cx < io_rc->right - io_rc->left) + io_rc->right = io_rc->left + m_largestSize.cx; + break; + } + switch (i_edge) { + case WMSZ_TOP: + case WMSZ_TOPLEFT: + case WMSZ_TOPRIGHT: + if (m_smallestRestriction & RESTRICT_VERTICALLY) + if (io_rc->bottom - io_rc->top < m_smallestSize.cy) + io_rc->top = io_rc->bottom - m_smallestSize.cy; + if (m_largestRestriction & RESTRICT_VERTICALLY) + if (m_largestSize.cy < io_rc->bottom - io_rc->top) + io_rc->top = io_rc->bottom - m_largestSize.cy; + break; + } + switch (i_edge) { + case WMSZ_BOTTOM: + case WMSZ_BOTTOMLEFT: + case WMSZ_BOTTOMRIGHT: + if (m_smallestRestriction & RESTRICT_VERTICALLY) + if (io_rc->bottom - io_rc->top < m_smallestSize.cy) + io_rc->bottom = io_rc->top + m_smallestSize.cy; + if (m_largestRestriction & RESTRICT_VERTICALLY) + if (m_largestSize.cy < io_rc->bottom - io_rc->top) + io_rc->bottom = io_rc->top + m_largestSize.cy; + break; + } + return TRUE; } // hittest for size box BOOL LayoutManager::wmNcHitTest(int i_x, int i_y) { - POINT p = { i_x, i_y }; - ScreenToClient(m_hwnd, &p); - RECT rc; - GetClientRect(m_hwnd, &rc); - if (rc.right - GetSystemMetrics(SM_CXHTHUMB) <= p.x && - rc.bottom - GetSystemMetrics(SM_CYVTHUMB) <= p.y) - { + POINT p = { i_x, i_y }; + ScreenToClient(m_hwnd, &p); + RECT rc; + GetClientRect(m_hwnd, &rc); + if (rc.right - GetSystemMetrics(SM_CXHTHUMB) <= p.x && + rc.bottom - GetSystemMetrics(SM_CYVTHUMB) <= p.y) { #ifdef MAYU64 - SetWindowLongPtr(m_hwnd, DWLP_MSGRESULT, HTBOTTOMRIGHT); + SetWindowLongPtr(m_hwnd, DWLP_MSGRESULT, HTBOTTOMRIGHT); #else - SetWindowLong(m_hwnd, DWL_MSGRESULT, HTBOTTOMRIGHT); + SetWindowLong(m_hwnd, DWL_MSGRESULT, HTBOTTOMRIGHT); #endif - return TRUE; - } - return FALSE; + return TRUE; + } + return FALSE; } // WM_SIZE BOOL LayoutManager::wmSize(DWORD /* i_fwSizeType */, short /* i_nWidth */, - short /* i_nHeight */) + short /* i_nHeight */) { - adjust(); - RedrawWindow(m_hwnd, NULL, NULL, - RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN); - return TRUE; + adjust(); + RedrawWindow(m_hwnd, NULL, NULL, + RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN); + return TRUE; } // forward message BOOL LayoutManager::defaultWMHandler(UINT i_message, - WPARAM i_wParam, LPARAM i_lParam) + WPARAM i_wParam, LPARAM i_lParam) { - switch (i_message) - { - case WM_SIZE: - return wmSize(i_wParam, LOWORD(i_lParam), HIWORD(i_lParam)); - case WM_PAINT: - return wmPaint(); - case WM_SIZING: - return wmSizing(i_wParam, reinterpret_cast(i_lParam)); - case WM_NCHITTEST: - return wmNcHitTest(GET_X_LPARAM(i_lParam), GET_Y_LPARAM(i_lParam)); - } - return FALSE; + switch (i_message) { + case WM_SIZE: + return wmSize(i_wParam, LOWORD(i_lParam), HIWORD(i_lParam)); + case WM_PAINT: + return wmPaint(); + case WM_SIZING: + return wmSizing(i_wParam, reinterpret_cast(i_lParam)); + case WM_NCHITTEST: + return wmNcHitTest(GET_X_LPARAM(i_lParam), GET_Y_LPARAM(i_lParam)); + } + return FALSE; } diff --git a/layoutmanager.h b/layoutmanager.h index 51ccb7d..f0d5a92 100644 --- a/layoutmanager.h +++ b/layoutmanager.h @@ -13,100 +13,98 @@ class LayoutManager { public: - /// - enum Origin - { - ORIGIN_LEFT_EDGE, /// - ORIGIN_TOP_EDGE = ORIGIN_LEFT_EDGE, /// - ORIGIN_CENTER, /// - ORIGIN_RIGHT_EDGE, /// - ORIGIN_BOTTOM_EDGE = ORIGIN_RIGHT_EDGE, /// - }; - - /// - enum Restrict - { - RESTRICT_NONE = 0, /// - RESTRICT_HORIZONTALLY = 1, /// - RESTRICT_VERTICALLY = 2, /// - RESTRICT_BOTH = RESTRICT_HORIZONTALLY | RESTRICT_VERTICALLY, /// - }; + /// + enum Origin { + ORIGIN_LEFT_EDGE, /// + ORIGIN_TOP_EDGE = ORIGIN_LEFT_EDGE, /// + ORIGIN_CENTER, /// + ORIGIN_RIGHT_EDGE, /// + ORIGIN_BOTTOM_EDGE = ORIGIN_RIGHT_EDGE, /// + }; + + /// + enum Restrict { + RESTRICT_NONE = 0, /// + RESTRICT_HORIZONTALLY = 1, /// + RESTRICT_VERTICALLY = 2, /// + RESTRICT_BOTH = RESTRICT_HORIZONTALLY | RESTRICT_VERTICALLY, /// + }; private: - /// - class Item - { - public: - HWND m_hwnd; /// - HWND m_hwndParent; /// - RECT m_rc; /// - RECT m_rcParent; /// - Origin m_origin[4]; /// - }; - - /// - class SmallestSize - { - public: - HWND m_hwnd; /// - SIZE m_size; /// - - public: - /// - SmallestSize() : m_hwnd(NULL) { } - }; - - typedef std::list Items; /// - + /// + class Item + { + public: + HWND m_hwnd; /// + HWND m_hwndParent; /// + RECT m_rc; /// + RECT m_rcParent; /// + Origin m_origin[4]; /// + }; + + /// + class SmallestSize + { + public: + HWND m_hwnd; /// + SIZE m_size; /// + + public: + /// + SmallestSize() : m_hwnd(NULL) { } + }; + + typedef std::list Items; /// + protected: - HWND m_hwnd; /// + HWND m_hwnd; /// private: - Items m_items; /// - Restrict m_smallestRestriction; /// - SIZE m_smallestSize; /// - Restrict m_largestRestriction; /// - SIZE m_largestSize; /// - + Items m_items; /// + Restrict m_smallestRestriction; /// + SIZE m_smallestSize; /// + Restrict m_largestRestriction; /// + SIZE m_largestSize; /// + public: - /// - LayoutManager(HWND i_hwnd); - - /** restrict the smallest size of the window to the current size of it or - specified by i_size */ - void restrictSmallestSize(Restrict i_restrict = RESTRICT_BOTH, - SIZE *i_size = NULL); - - /** restrict the largest size of the window to the current size of it or - specified by i_size */ - void restrictLargestSize(Restrict i_restrict = RESTRICT_BOTH, - SIZE *i_size = NULL); - - /// - bool addItem(HWND i_hwnd, - Origin i_originLeft = ORIGIN_LEFT_EDGE, - Origin i_originTop = ORIGIN_TOP_EDGE, - Origin i_originRight = ORIGIN_LEFT_EDGE, - Origin i_originBottom = ORIGIN_TOP_EDGE); - /// - void adjust() const; - - /// draw size box - virtual BOOL wmPaint(); - - /// size restriction - virtual BOOL wmSizing(int i_edge, RECT *io_rc); - - /// hittest for size box - virtual BOOL wmNcHitTest(int i_x, int i_y); - - /// WM_SIZE - virtual BOOL wmSize(DWORD /* i_fwSizeType */, short /* i_nWidth */, - short /* i_nHeight */); - - /// forward message - virtual BOOL defaultWMHandler(UINT i_message, WPARAM i_wParam, - LPARAM i_lParam); + /// + LayoutManager(HWND i_hwnd); + + /** restrict the smallest size of the window to the current size of it or + specified by i_size */ + void restrictSmallestSize(Restrict i_restrict = RESTRICT_BOTH, + SIZE *i_size = NULL); + + /** restrict the largest size of the window to the current size of it or + specified by i_size */ + void restrictLargestSize(Restrict i_restrict = RESTRICT_BOTH, + SIZE *i_size = NULL); + + /// + bool addItem(HWND i_hwnd, + Origin i_originLeft = ORIGIN_LEFT_EDGE, + Origin i_originTop = ORIGIN_TOP_EDGE, + Origin i_originRight = ORIGIN_LEFT_EDGE, + Origin i_originBottom = ORIGIN_TOP_EDGE); + /// + void adjust() const; + + /// draw size box + virtual BOOL wmPaint(); + + /// size restriction + virtual BOOL wmSizing(int i_edge, RECT *io_rc); + + /// hittest for size box + virtual BOOL wmNcHitTest(int i_x, int i_y); + + /// WM_SIZE + virtual BOOL wmSize(DWORD /* i_fwSizeType */, short /* i_nWidth */, + short /* i_nHeight */); + + /// forward message + virtual BOOL defaultWMHandler(UINT i_message, WPARAM i_wParam, + LPARAM i_lParam); }; diff --git a/mayu.cpp b/mayu.cpp index b9c044e..42a35ea 100644 --- a/mayu.cpp +++ b/mayu.cpp @@ -42,276 +42,254 @@ /// class Mayu { - HWND m_hwndTaskTray; /// tasktray window - HWND m_hwndLog; /// log dialog - HWND m_hwndInvestigate; /// investigate dialog - HWND m_hwndVersion; /// version dialog - - UINT m_WM_TaskbarRestart; /** window message sent when + HWND m_hwndTaskTray; /// tasktray window + HWND m_hwndLog; /// log dialog + HWND m_hwndInvestigate; /// investigate dialog + HWND m_hwndVersion; /// version dialog + + UINT m_WM_TaskbarRestart; /** window message sent when taskber restarts */ - UINT m_WM_MayuIPC; /** IPC message sent from + UINT m_WM_MayuIPC; /** IPC message sent from other applications */ - NOTIFYICONDATA m_ni; /// taskbar icon data - HICON m_tasktrayIcon[2]; /// taskbar icon - bool m_canUseTasktrayBaloon; /// + NOTIFYICONDATA m_ni; /// taskbar icon data + HICON m_tasktrayIcon[2]; /// taskbar icon + bool m_canUseTasktrayBaloon; /// - tomsgstream m_log; /** log stream (output to log + tomsgstream m_log; /** log stream (output to log dialog's edit) */ #ifdef LOG_TO_FILE - tofstream m_logFile; + tofstream m_logFile; #endif // LOG_TO_FILE - HMENU m_hMenuTaskTray; /// tasktray menu - STARTUPINFO m_si; - PROCESS_INFORMATION m_pi; - HANDLE m_mutex; + HMENU m_hMenuTaskTray; /// tasktray menu + STARTUPINFO m_si; + PROCESS_INFORMATION m_pi; + HANDLE m_mutex; #ifdef USE_MAILSLOT - HANDLE m_hNotifyMailslot; /// mailslot to receive notify - HANDLE m_hNotifyEvent; /// event on receive notify - OVERLAPPED m_olNotify; /// - BYTE m_notifyBuf[NOTIFY_MESSAGE_SIZE]; + HANDLE m_hNotifyMailslot; /// mailslot to receive notify + HANDLE m_hNotifyEvent; /// event on receive notify + OVERLAPPED m_olNotify; /// + BYTE m_notifyBuf[NOTIFY_MESSAGE_SIZE]; #endif // USE_MAILSLOT - - Setting *m_setting; /// current setting - bool m_isSettingDialogOpened; /// is setting dialog opened ? - - Engine m_engine; /// engine - - bool m_usingSN; /// using WTSRegisterSessionNotification() ? - time_t m_startTime; /// mayu started at ... - - enum - { - WM_APP_taskTrayNotify = WM_APP + 101, /// - WM_APP_msgStreamNotify = WM_APP + 102, /// - ID_TaskTrayIcon = 1, /// - }; + + Setting *m_setting; /// current setting + bool m_isSettingDialogOpened; /// is setting dialog opened ? + + Engine m_engine; /// engine + + bool m_usingSN; /// using WTSRegisterSessionNotification() ? + time_t m_startTime; /// mayu started at ... + + enum { + WM_APP_taskTrayNotify = WM_APP + 101, /// + WM_APP_msgStreamNotify = WM_APP + 102, /// + ID_TaskTrayIcon = 1, /// + }; private: #ifdef USE_MAILSLOT - static VOID CALLBACK mailslotProc(DWORD i_code, DWORD i_len, LPOVERLAPPED i_ol) - { - Mayu *pThis; - - pThis = reinterpret_cast(CONTAINING_RECORD(i_ol, Mayu, m_olNotify)); - pThis->mailslotHandler(i_code, i_len); - return; - } - - BOOL mailslotHandler(DWORD i_code, DWORD i_len) - { - BOOL result; - - if (i_len) - { - COPYDATASTRUCT cd; - - cd.dwData = reinterpret_cast(m_notifyBuf)->m_type; - cd.cbData = i_len; - cd.lpData = m_notifyBuf; - notifyHandler(&cd); - } - - memset(m_notifyBuf, 0, sizeof(m_notifyBuf)); - result = ReadFileEx(m_hNotifyMailslot, m_notifyBuf, sizeof(m_notifyBuf), - &m_olNotify, Mayu::mailslotProc); - return result; - } + static VOID CALLBACK mailslotProc(DWORD i_code, DWORD i_len, LPOVERLAPPED i_ol) { + Mayu *pThis; + + pThis = reinterpret_cast(CONTAINING_RECORD(i_ol, Mayu, m_olNotify)); + pThis->mailslotHandler(i_code, i_len); + return; + } + + BOOL mailslotHandler(DWORD i_code, DWORD i_len) { + BOOL result; + + if (i_len) { + COPYDATASTRUCT cd; + + cd.dwData = reinterpret_cast(m_notifyBuf)->m_type; + cd.cbData = i_len; + cd.lpData = m_notifyBuf; + notifyHandler(&cd); + } + + memset(m_notifyBuf, 0, sizeof(m_notifyBuf)); + result = ReadFileEx(m_hNotifyMailslot, m_notifyBuf, sizeof(m_notifyBuf), + &m_olNotify, Mayu::mailslotProc); + return result; + } #endif // USE_MAILSLOT - /// register class for tasktray - ATOM Register_tasktray() - { - WNDCLASS wc; - wc.style = 0; - wc.lpfnWndProc = tasktray_wndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = sizeof(Mayu *); - wc.hInstance = g_hInst; - wc.hIcon = NULL; - wc.hCursor = NULL; - wc.hbrBackground = NULL; - wc.lpszMenuName = NULL; - wc.lpszClassName = _T("mayuTasktray"); - return RegisterClass(&wc); - } - - /// notify handler - BOOL notifyHandler(COPYDATASTRUCT *cd) - { - switch (cd->dwData) - { - case Notify::Type_setFocus: - case Notify::Type_name: - { - NotifySetFocus *n = (NotifySetFocus *)cd->lpData; - n->m_className[NUMBER_OF(n->m_className) - 1] = _T('\0'); - n->m_titleName[NUMBER_OF(n->m_titleName) - 1] = _T('\0'); - - if (n->m_type == Notify::Type_setFocus) - m_engine.setFocus(reinterpret_cast(n->m_hwnd), n->m_threadId, - n->m_className, n->m_titleName, false); - - { - Acquire a(&m_log, 1); - m_log << _T("HWND:\t") << std::hex - << n->m_hwnd - << std::dec << std::endl; - m_log << _T("THREADID:") << static_cast(n->m_threadId) - << std::endl; - } - Acquire a(&m_log, (n->m_type == Notify::Type_name) ? 0 : 1); - m_log << _T("CLASS:\t") << n->m_className << std::endl; - m_log << _T("TITLE:\t") << n->m_titleName << std::endl; - - bool isMDI = true; - HWND hwnd = getToplevelWindow(reinterpret_cast(n->m_hwnd), &isMDI); - RECT rc; - if (isMDI) - { - getChildWindowRect(hwnd, &rc); - m_log << _T("MDI Window Position/Size: (") - << rc.left << _T(", ") << rc.top << _T(") / (") - << rcWidth(&rc) << _T("x") << rcHeight(&rc) << _T(")") - << std::endl; - hwnd = getToplevelWindow(reinterpret_cast(n->m_hwnd), NULL); - } - - GetWindowRect(hwnd, &rc); - m_log << _T("Toplevel Window Position/Size: (") - << rc.left << _T(", ") << rc.top << _T(") / (") - << rcWidth(&rc) << _T("x") << rcHeight(&rc) << _T(")") - << std::endl; - - SystemParametersInfo(SPI_GETWORKAREA, 0, (void *)&rc, FALSE); - m_log << _T("Desktop Window Position/Size: (") - << rc.left << _T(", ") << rc.top << _T(") / (") - << rcWidth(&rc) << _T("x") << rcHeight(&rc) << _T(")") - << std::endl; - - m_log << std::endl; - break; + /// register class for tasktray + ATOM Register_tasktray() { + WNDCLASS wc; + wc.style = 0; + wc.lpfnWndProc = tasktray_wndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = sizeof(Mayu *); + wc.hInstance = g_hInst; + wc.hIcon = NULL; + wc.hCursor = NULL; + wc.hbrBackground = NULL; + wc.lpszMenuName = NULL; + wc.lpszClassName = _T("mayuTasktray"); + return RegisterClass(&wc); } - - case Notify::Type_lockState: - { - NotifyLockState *n = (NotifyLockState *)cd->lpData; - m_engine.setLockState(n->m_isNumLockToggled, - n->m_isCapsLockToggled, - n->m_isScrollLockToggled, - n->m_isKanaLockToggled, - n->m_isImeLockToggled, - n->m_isImeCompToggled); + + /// notify handler + BOOL notifyHandler(COPYDATASTRUCT *cd) { + switch (cd->dwData) { + case Notify::Type_setFocus: + case Notify::Type_name: { + NotifySetFocus *n = (NotifySetFocus *)cd->lpData; + n->m_className[NUMBER_OF(n->m_className) - 1] = _T('\0'); + n->m_titleName[NUMBER_OF(n->m_titleName) - 1] = _T('\0'); + + if (n->m_type == Notify::Type_setFocus) + m_engine.setFocus(reinterpret_cast(n->m_hwnd), n->m_threadId, + n->m_className, n->m_titleName, false); + + { + Acquire a(&m_log, 1); + m_log << _T("HWND:\t") << std::hex + << n->m_hwnd + << std::dec << std::endl; + m_log << _T("THREADID:") << static_cast(n->m_threadId) + << std::endl; + } + Acquire a(&m_log, (n->m_type == Notify::Type_name) ? 0 : 1); + m_log << _T("CLASS:\t") << n->m_className << std::endl; + m_log << _T("TITLE:\t") << n->m_titleName << std::endl; + + bool isMDI = true; + HWND hwnd = getToplevelWindow(reinterpret_cast(n->m_hwnd), &isMDI); + RECT rc; + if (isMDI) { + getChildWindowRect(hwnd, &rc); + m_log << _T("MDI Window Position/Size: (") + << rc.left << _T(", ") << rc.top << _T(") / (") + << rcWidth(&rc) << _T("x") << rcHeight(&rc) << _T(")") + << std::endl; + hwnd = getToplevelWindow(reinterpret_cast(n->m_hwnd), NULL); + } + + GetWindowRect(hwnd, &rc); + m_log << _T("Toplevel Window Position/Size: (") + << rc.left << _T(", ") << rc.top << _T(") / (") + << rcWidth(&rc) << _T("x") << rcHeight(&rc) << _T(")") + << std::endl; + + SystemParametersInfo(SPI_GETWORKAREA, 0, (void *)&rc, FALSE); + m_log << _T("Desktop Window Position/Size: (") + << rc.left << _T(", ") << rc.top << _T(") / (") + << rcWidth(&rc) << _T("x") << rcHeight(&rc) << _T(")") + << std::endl; + + m_log << std::endl; + break; + } + + case Notify::Type_lockState: { + NotifyLockState *n = (NotifyLockState *)cd->lpData; + m_engine.setLockState(n->m_isNumLockToggled, + n->m_isCapsLockToggled, + n->m_isScrollLockToggled, + n->m_isKanaLockToggled, + n->m_isImeLockToggled, + n->m_isImeCompToggled); #if 0 - Acquire a(&m_log, 0); - if (n->m_isKanaLockToggled) { - m_log << _T("Notify::Type_lockState Kana on : "); - } else { - m_log << _T("Notify::Type_lockState Kana off : "); - } - m_log << n->m_debugParam << ", " - << g_hookData->m_correctKanaLockHandling << std::endl; + Acquire a(&m_log, 0); + if (n->m_isKanaLockToggled) { + m_log << _T("Notify::Type_lockState Kana on : "); + } else { + m_log << _T("Notify::Type_lockState Kana off : "); + } + m_log << n->m_debugParam << ", " + << g_hookData->m_correctKanaLockHandling << std::endl; #endif - break; - } + break; + } - case Notify::Type_sync: - { - m_engine.syncNotify(); - break; - } + case Notify::Type_sync: { + m_engine.syncNotify(); + break; + } - case Notify::Type_threadDetach: - { - NotifyThreadDetach *n = (NotifyThreadDetach *)cd->lpData; - m_engine.threadDetachNotify(n->m_threadId); - break; - } + case Notify::Type_threadDetach: { + NotifyThreadDetach *n = (NotifyThreadDetach *)cd->lpData; + m_engine.threadDetachNotify(n->m_threadId); + break; + } - case Notify::Type_command: - { - NotifyCommand *n = (NotifyCommand *)cd->lpData; - m_engine.commandNotify(n->m_hwnd, n->m_message, - n->m_wParam, n->m_lParam); - break; - } + case Notify::Type_command: { + NotifyCommand *n = (NotifyCommand *)cd->lpData; + m_engine.commandNotify(n->m_hwnd, n->m_message, + n->m_wParam, n->m_lParam); + break; + } - case Notify::Type_show: - { - NotifyShow *n = (NotifyShow *)cd->lpData; - switch (n->m_show) - { - case NotifyShow::Show_Maximized: - m_engine.setShow(true, false, n->m_isMDI); - break; - case NotifyShow::Show_Minimized: - m_engine.setShow(false, true, n->m_isMDI); - break; - case NotifyShow::Show_Normal: - default: - m_engine.setShow(false, false, n->m_isMDI); - break; - } - break; - } + case Notify::Type_show: { + NotifyShow *n = (NotifyShow *)cd->lpData; + switch (n->m_show) { + case NotifyShow::Show_Maximized: + m_engine.setShow(true, false, n->m_isMDI); + break; + case NotifyShow::Show_Minimized: + m_engine.setShow(false, true, n->m_isMDI); + break; + case NotifyShow::Show_Normal: + default: + m_engine.setShow(false, false, n->m_isMDI); + break; + } + break; + } - case Notify::Type_log: - { - Acquire a(&m_log, 1); - NotifyLog *n = (NotifyLog *)cd->lpData; - m_log << _T("hook log: ") << n->m_msg << std::endl; - break; + case Notify::Type_log: { + Acquire a(&m_log, 1); + NotifyLog *n = (NotifyLog *)cd->lpData; + m_log << _T("hook log: ") << n->m_msg << std::endl; + break; + } + } + return true; } - } - return true; - } - - /// window procedure for tasktray - static LRESULT CALLBACK - tasktray_wndProc(HWND i_hwnd, UINT i_message, - WPARAM i_wParam, LPARAM i_lParam) - { + + /// window procedure for tasktray + static LRESULT CALLBACK + tasktray_wndProc(HWND i_hwnd, UINT i_message, + WPARAM i_wParam, LPARAM i_lParam) { #ifdef MAYU64 - Mayu *This = reinterpret_cast(GetWindowLongPtr(i_hwnd, 0)); + Mayu *This = reinterpret_cast(GetWindowLongPtr(i_hwnd, 0)); #else - Mayu *This = reinterpret_cast(GetWindowLong(i_hwnd, 0)); + Mayu *This = reinterpret_cast(GetWindowLong(i_hwnd, 0)); #endif - if (!This) - switch (i_message) - { - case WM_CREATE: - This = reinterpret_cast( - reinterpret_cast(i_lParam)->lpCreateParams); + if (!This) + switch (i_message) { + case WM_CREATE: + This = reinterpret_cast( + reinterpret_cast(i_lParam)->lpCreateParams); #ifdef MAYU64 - SetWindowLongPtr(i_hwnd, 0, (LONG_PTR)This); + SetWindowLongPtr(i_hwnd, 0, (LONG_PTR)This); #else - SetWindowLong(i_hwnd, 0, (long)This); + SetWindowLong(i_hwnd, 0, (long)This); #endif - return 0; - } - else - switch (i_message) - { - case WM_COPYDATA: - { - COPYDATASTRUCT *cd; - cd = reinterpret_cast(i_lParam); - return This->notifyHandler(cd); - } - case WM_QUERYENDSESSION: - This->m_engine.prepairQuit(); - PostQuitMessage(0); - return TRUE; + return 0; + } + else + switch (i_message) { + case WM_COPYDATA: { + COPYDATASTRUCT *cd; + cd = reinterpret_cast(i_lParam); + return This->notifyHandler(cd); + } + case WM_QUERYENDSESSION: + This->m_engine.prepairQuit(); + PostQuitMessage(0); + return TRUE; #ifndef WM_WTSSESSION_CHANGE // WinUser.h # define WM_WTSSESSION_CHANGE 0x02B1 #endif - case WM_WTSSESSION_CHANGE: - { - const char *m = ""; - switch (i_wParam) - { + case WM_WTSSESSION_CHANGE: { + const char *m = ""; + switch (i_wParam) { #ifndef WTS_CONSOLE_CONNECT // WinUser.h # define WTS_CONSOLE_CONNECT 0x1 # define WTS_CONSOLE_DISCONNECT 0x2 @@ -322,742 +300,692 @@ private: # define WTS_SESSION_LOCK 0x7 # define WTS_SESSION_UNLOCK 0x8 #endif - case WTS_CONSOLE_CONNECT: - m = "WTS_CONSOLE_CONNECT"; - if (!This->m_engine.resume()) { - This->m_engine.prepairQuit(); - PostQuitMessage(0); - } - break; - case WTS_CONSOLE_DISCONNECT: - m = "WTS_CONSOLE_DISCONNECT"; - This->m_engine.pause(); - break; - case WTS_REMOTE_CONNECT: m = "WTS_REMOTE_CONNECT"; break; - case WTS_REMOTE_DISCONNECT: m = "WTS_REMOTE_DISCONNECT"; break; - case WTS_SESSION_LOGON: m = "WTS_SESSION_LOGON"; break; - case WTS_SESSION_LOGOFF: m = "WTS_SESSION_LOGOFF"; break; - case WTS_SESSION_LOCK: m = "WTS_SESSION_LOCK"; break; - case WTS_SESSION_UNLOCK: m = "WTS_SESSION_UNLOCK"; break; - //case WTS_SESSION_REMOTE_CONTROL: m = "WTS_SESSION_REMOTE_CONTROL"; break; - } - This->m_log << _T("WM_WTSESSION_CHANGE(") - << i_wParam << ", " << i_lParam << "): " - << m << std::endl; - return TRUE; - } - case WM_APP_msgStreamNotify: - { - tomsgstream::StreamBuf *log = - reinterpret_cast(i_lParam); - const tstring &str = log->acquireString(); + case WTS_CONSOLE_CONNECT: + m = "WTS_CONSOLE_CONNECT"; + if (!This->m_engine.resume()) { + This->m_engine.prepairQuit(); + PostQuitMessage(0); + } + break; + case WTS_CONSOLE_DISCONNECT: + m = "WTS_CONSOLE_DISCONNECT"; + This->m_engine.pause(); + break; + case WTS_REMOTE_CONNECT: + m = "WTS_REMOTE_CONNECT"; + break; + case WTS_REMOTE_DISCONNECT: + m = "WTS_REMOTE_DISCONNECT"; + break; + case WTS_SESSION_LOGON: + m = "WTS_SESSION_LOGON"; + break; + case WTS_SESSION_LOGOFF: + m = "WTS_SESSION_LOGOFF"; + break; + case WTS_SESSION_LOCK: + m = "WTS_SESSION_LOCK"; + break; + case WTS_SESSION_UNLOCK: + m = "WTS_SESSION_UNLOCK"; + break; + //case WTS_SESSION_REMOTE_CONTROL: m = "WTS_SESSION_REMOTE_CONTROL"; break; + } + This->m_log << _T("WM_WTSESSION_CHANGE(") + << i_wParam << ", " << i_lParam << "): " + << m << std::endl; + return TRUE; + } + case WM_APP_msgStreamNotify: { + tomsgstream::StreamBuf *log = + reinterpret_cast(i_lParam); + const tstring &str = log->acquireString(); #ifdef LOG_TO_FILE - This->m_logFile << str << std::flush; + This->m_logFile << str << std::flush; #endif // LOG_TO_FILE - editInsertTextAtLast(GetDlgItem(This->m_hwndLog, IDC_EDIT_log), - str, 65000); - log->releaseString(); - return 0; + editInsertTextAtLast(GetDlgItem(This->m_hwndLog, IDC_EDIT_log), + str, 65000); + log->releaseString(); + return 0; + } + + case WM_APP_taskTrayNotify: { + if (i_wParam == ID_TaskTrayIcon) + switch (i_lParam) { + case WM_RBUTTONUP: { + POINT p; + CHECK_TRUE( GetCursorPos(&p) ); + SetForegroundWindow(i_hwnd); + HMENU hMenuSub = GetSubMenu(This->m_hMenuTaskTray, 0); + if (This->m_engine.getIsEnabled()) + CheckMenuItem(hMenuSub, ID_MENUITEM_disable, + MF_UNCHECKED | MF_BYCOMMAND); + else + CheckMenuItem(hMenuSub, ID_MENUITEM_disable, + MF_CHECKED | MF_BYCOMMAND); + CHECK_TRUE( SetMenuDefaultItem(hMenuSub, + ID_MENUITEM_investigate, FALSE) ); + + // create reload menu + HMENU hMenuSubSub = GetSubMenu(hMenuSub, 1); + Registry reg(MAYU_REGISTRY_ROOT); + int mayuIndex; + reg.read(_T(".mayuIndex"), &mayuIndex, 0); + while (DeleteMenu(hMenuSubSub, 0, MF_BYPOSITION)) + ; + tregex getName(_T("^([^;]*);")); + for (int index = 0; ; index ++) { + _TCHAR buf[100]; + _sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index); + tstringi dot_mayu; + if (!reg.read(buf, &dot_mayu)) + break; + tsmatch what; + if (boost::regex_search(dot_mayu, what, getName)) { + MENUITEMINFO mii; + std::memset(&mii, 0, sizeof(mii)); + mii.cbSize = sizeof(mii); + mii.fMask = MIIM_ID | MIIM_STATE | MIIM_TYPE; + mii.fType = MFT_STRING; + mii.fState = + MFS_ENABLED | ((mayuIndex == index) ? MFS_CHECKED : 0); + mii.wID = ID_MENUITEM_reloadBegin + index; + tstringi name(what.str(1)); + mii.dwTypeData = const_cast<_TCHAR *>(name.c_str()); + mii.cch = name.size(); + + InsertMenuItem(hMenuSubSub, index, TRUE, &mii); + } + } + + // show popup menu + TrackPopupMenu(hMenuSub, TPM_LEFTALIGN, + p.x, p.y, 0, i_hwnd, NULL); + // TrackPopupMenu may fail (ERROR_POPUP_ALREADY_ACTIVE) + break; + } + + case WM_LBUTTONDBLCLK: + SendMessage(i_hwnd, WM_COMMAND, + MAKELONG(ID_MENUITEM_investigate, 0), 0); + break; + } + return 0; + } + + case WM_COMMAND: { + int notify_code = HIWORD(i_wParam); + int id = LOWORD(i_wParam); + if (notify_code == 0) // menu + switch (id) { + default: + if (ID_MENUITEM_reloadBegin <= id) { + Registry reg(MAYU_REGISTRY_ROOT); + reg.write(_T(".mayuIndex"), id - ID_MENUITEM_reloadBegin); + This->load(); + } + break; + case ID_MENUITEM_reload: + This->load(); + break; + case ID_MENUITEM_investigate: { + ShowWindow(This->m_hwndLog, SW_SHOW); + ShowWindow(This->m_hwndInvestigate, SW_SHOW); + + RECT rc1, rc2; + GetWindowRect(This->m_hwndInvestigate, &rc1); + GetWindowRect(This->m_hwndLog, &rc2); + + MoveWindow(This->m_hwndLog, rc1.left, rc1.bottom, + rcWidth(&rc1), rcHeight(&rc2), TRUE); + + SetForegroundWindow(This->m_hwndLog); + SetForegroundWindow(This->m_hwndInvestigate); + break; + } + case ID_MENUITEM_setting: + if (!This->m_isSettingDialogOpened) { + This->m_isSettingDialogOpened = true; + if (DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_setting), + NULL, dlgSetting_dlgProc)) + This->load(); + This->m_isSettingDialogOpened = false; + } + break; + case ID_MENUITEM_log: + ShowWindow(This->m_hwndLog, SW_SHOW); + SetForegroundWindow(This->m_hwndLog); + break; + case ID_MENUITEM_check: { + BOOL ret; + BYTE keys[256]; + ret = GetKeyboardState(keys); + if (ret == 0) { + This->m_log << _T("Check Keystate Failed(%d)") + << GetLastError() << std::endl; + } else { + This->m_log << _T("Check Keystate: ") << std::endl; + for (int i = 0; i < 0xff; i++) { + USHORT asyncKey; + asyncKey = GetAsyncKeyState(i); + This->m_log << std::hex; + if (asyncKey & 0x8000) { + This->m_log << _T(" ") << VK2TCHAR[i] + << _T("(0x") << i << _T("): pressed!") + << std::endl; + } + if (i == 0x14 || // VK_CAPTITAL + i == 0x15 || // VK_KANA + i == 0x19 || // VK_KANJI + i == 0x90 || // VK_NUMLOCK + i == 0x91 // VK_SCROLL + ) { + if (keys[i] & 1) { + This->m_log << _T(" ") << VK2TCHAR[i] + << _T("(0x") << i << _T("): locked!") + << std::endl; + } + } + This->m_log << std::dec; + } + This->m_log << std::endl; + } + break; + } + case ID_MENUITEM_version: + ShowWindow(This->m_hwndVersion, SW_SHOW); + SetForegroundWindow(This->m_hwndVersion); + break; + case ID_MENUITEM_help: { + _TCHAR buf[GANA_MAX_PATH]; + CHECK_TRUE( GetModuleFileName(g_hInst, buf, NUMBER_OF(buf)) ); + tstringi helpFilename = pathRemoveFileSpec(buf); + helpFilename += _T("\\"); + helpFilename += loadString(IDS_helpFilename); + ShellExecute(NULL, _T("open"), helpFilename.c_str(), + NULL, NULL, SW_SHOWNORMAL); + break; + } + case ID_MENUITEM_disable: + This->m_engine.enable(!This->m_engine.getIsEnabled()); + This->showTasktrayIcon(); + break; + case ID_MENUITEM_quit: + This->m_engine.prepairQuit(); + PostQuitMessage(0); + break; + } + return 0; + } + + case WM_APP_engineNotify: { + switch (i_wParam) { + case EngineNotify_shellExecute: + This->m_engine.shellExecute(); + break; + case EngineNotify_loadSetting: + This->load(); + break; + case EngineNotify_helpMessage: + This->showHelpMessage(false); + if (i_lParam) + This->showHelpMessage(true); + break; + case EngineNotify_showDlg: { + // show investigate/log window + int sw = (i_lParam & ~MayuDialogType_mask); + HWND hwnd = NULL; + switch (static_cast( + i_lParam & MayuDialogType_mask)) { + case MayuDialogType_investigate: + hwnd = This->m_hwndInvestigate; + break; + case MayuDialogType_log: + hwnd = This->m_hwndLog; + break; + } + if (hwnd) { + ShowWindow(hwnd, sw); + switch (sw) { + case SW_SHOWNORMAL: + case SW_SHOWMAXIMIZED: + case SW_SHOW: + case SW_RESTORE: + case SW_SHOWDEFAULT: + SetForegroundWindow(hwnd); + break; + } + } + break; + } + case EngineNotify_setForegroundWindow: + // FIXME: completely useless. why ? + setForegroundWindow(reinterpret_cast(i_lParam)); + { + Acquire a(&This->m_log, 1); + This->m_log << _T("setForegroundWindow(0x") + << std::hex << i_lParam << std::dec << _T(")") + << std::endl; + } + break; + case EngineNotify_clearLog: + SendMessage(This->m_hwndLog, WM_COMMAND, + MAKELONG(IDC_BUTTON_clearLog, 0), 0); + break; + default: + break; + } + return 0; + } + + case WM_APP_dlglogNotify: { + switch (i_wParam) { + case DlgLogNotify_logCleared: + This->showBanner(true); + break; + default: + break; + } + return 0; + } + + case WM_DESTROY: + if (This->m_usingSN) { + wtsUnRegisterSessionNotification(i_hwnd); + This->m_usingSN = false; + } + return 0; + + default: + if (i_message == This->m_WM_TaskbarRestart) { + if (This->showTasktrayIcon(true)) { + Acquire a(&This->m_log, 0); + This->m_log << _T("Tasktray icon is updated.") << std::endl; + } else { + Acquire a(&This->m_log, 1); + This->m_log << _T("Tasktray icon already exists.") << std::endl; + } + return 0; + } else if (i_message == This->m_WM_MayuIPC) { + switch (static_cast(i_wParam)) { + case MayuIPCCommand_Enable: + This->m_engine.enable(!!i_lParam); + This->showTasktrayIcon(); + if (i_lParam) { + Acquire a(&This->m_log, 1); + This->m_log << _T("Enabled by another application.") + << std::endl; + } else { + Acquire a(&This->m_log, 1); + This->m_log << _T("Disabled by another application.") + << std::endl; + } + break; + } + } + } + return DefWindowProc(i_hwnd, i_message, i_wParam, i_lParam); } - - case WM_APP_taskTrayNotify: - { - if (i_wParam == ID_TaskTrayIcon) - switch (i_lParam) - { - case WM_RBUTTONUP: - { - POINT p; - CHECK_TRUE( GetCursorPos(&p) ); - SetForegroundWindow(i_hwnd); - HMENU hMenuSub = GetSubMenu(This->m_hMenuTaskTray, 0); - if (This->m_engine.getIsEnabled()) - CheckMenuItem(hMenuSub, ID_MENUITEM_disable, - MF_UNCHECKED | MF_BYCOMMAND); - else - CheckMenuItem(hMenuSub, ID_MENUITEM_disable, - MF_CHECKED | MF_BYCOMMAND); - CHECK_TRUE( SetMenuDefaultItem(hMenuSub, - ID_MENUITEM_investigate, FALSE) ); - - // create reload menu - HMENU hMenuSubSub = GetSubMenu(hMenuSub, 1); - Registry reg(MAYU_REGISTRY_ROOT); - int mayuIndex; - reg.read(_T(".mayuIndex"), &mayuIndex, 0); - while (DeleteMenu(hMenuSubSub, 0, MF_BYPOSITION)) - ; - tregex getName(_T("^([^;]*);")); - for (int index = 0; ; index ++) - { - _TCHAR buf[100]; - _sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index); - tstringi dot_mayu; - if (!reg.read(buf, &dot_mayu)) - break; - tsmatch what; - if (boost::regex_search(dot_mayu, what, getName)) - { - MENUITEMINFO mii; - std::memset(&mii, 0, sizeof(mii)); - mii.cbSize = sizeof(mii); - mii.fMask = MIIM_ID | MIIM_STATE | MIIM_TYPE; - mii.fType = MFT_STRING; - mii.fState = - MFS_ENABLED | ((mayuIndex == index) ? MFS_CHECKED : 0); - mii.wID = ID_MENUITEM_reloadBegin + index; - tstringi name(what.str(1)); - mii.dwTypeData = const_cast<_TCHAR *>(name.c_str()); - mii.cch = name.size(); - - InsertMenuItem(hMenuSubSub, index, TRUE, &mii); - } - } - // show popup menu - TrackPopupMenu(hMenuSub, TPM_LEFTALIGN, - p.x, p.y, 0, i_hwnd, NULL); - // TrackPopupMenu may fail (ERROR_POPUP_ALREADY_ACTIVE) - break; - } - - case WM_LBUTTONDBLCLK: - SendMessage(i_hwnd, WM_COMMAND, - MAKELONG(ID_MENUITEM_investigate, 0), 0); - break; - } - return 0; - } - - case WM_COMMAND: - { - int notify_code = HIWORD(i_wParam); - int id = LOWORD(i_wParam); - if (notify_code == 0) // menu - switch (id) - { - default: - if (ID_MENUITEM_reloadBegin <= id) - { - Registry reg(MAYU_REGISTRY_ROOT); - reg.write(_T(".mayuIndex"), id - ID_MENUITEM_reloadBegin); - This->load(); - } - break; - case ID_MENUITEM_reload: - This->load(); - break; - case ID_MENUITEM_investigate: - { - ShowWindow(This->m_hwndLog, SW_SHOW); - ShowWindow(This->m_hwndInvestigate, SW_SHOW); - - RECT rc1, rc2; - GetWindowRect(This->m_hwndInvestigate, &rc1); - GetWindowRect(This->m_hwndLog, &rc2); - - MoveWindow(This->m_hwndLog, rc1.left, rc1.bottom, - rcWidth(&rc1), rcHeight(&rc2), TRUE); - - SetForegroundWindow(This->m_hwndLog); - SetForegroundWindow(This->m_hwndInvestigate); - break; - } - case ID_MENUITEM_setting: - if (!This->m_isSettingDialogOpened) - { - This->m_isSettingDialogOpened = true; - if (DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_setting), - NULL, dlgSetting_dlgProc)) - This->load(); - This->m_isSettingDialogOpened = false; - } - break; - case ID_MENUITEM_log: - ShowWindow(This->m_hwndLog, SW_SHOW); - SetForegroundWindow(This->m_hwndLog); - break; - case ID_MENUITEM_check: - { - BOOL ret; - BYTE keys[256]; - ret = GetKeyboardState(keys); - if (ret == 0) - { - This->m_log << _T("Check Keystate Failed(%d)") - << GetLastError() << std::endl; + /// load setting + void load() { + Setting *newSetting = new Setting; + + // set symbol + for (int i = 1; i < __argc; ++ i) { + if (__targv[i][0] == _T('-') && __targv[i][1] == _T('D')) + newSetting->m_symbols.insert(__targv[i] + 2); } - else - { - This->m_log << _T("Check Keystate: ") << std::endl; - for (int i = 0; i < 0xff; i++) - { - USHORT asyncKey; - asyncKey = GetAsyncKeyState(i); - This->m_log << std::hex; - if (asyncKey & 0x8000) - { - This->m_log << _T(" ") << VK2TCHAR[i] - << _T("(0x") << i << _T("): pressed!") - << std::endl; - } - if (i == 0x14 || // VK_CAPTITAL - i == 0x15 || // VK_KANA - i == 0x19 || // VK_KANJI - i == 0x90 || // VK_NUMLOCK - i == 0x91 // VK_SCROLL - ) - { - if (keys[i] & 1) - { - This->m_log << _T(" ") << VK2TCHAR[i] - << _T("(0x") << i << _T("): locked!") - << std::endl; - } - } - This->m_log << std::dec; - } - This->m_log << std::endl; + + if (!SettingLoader(&m_log, &m_log).load(newSetting)) { + ShowWindow(m_hwndLog, SW_SHOW); + SetForegroundWindow(m_hwndLog); + delete newSetting; + Acquire a(&m_log, 0); + m_log << _T("error: failed to load.") << std::endl; + return; } - break; - } - case ID_MENUITEM_version: - ShowWindow(This->m_hwndVersion, SW_SHOW); - SetForegroundWindow(This->m_hwndVersion); - break; - case ID_MENUITEM_help: - { - _TCHAR buf[GANA_MAX_PATH]; - CHECK_TRUE( GetModuleFileName(g_hInst, buf, NUMBER_OF(buf)) ); - tstringi helpFilename = pathRemoveFileSpec(buf); - helpFilename += _T("\\"); - helpFilename += loadString(IDS_helpFilename); - ShellExecute(NULL, _T("open"), helpFilename.c_str(), - NULL, NULL, SW_SHOWNORMAL); - break; - } - case ID_MENUITEM_disable: - This->m_engine.enable(!This->m_engine.getIsEnabled()); - This->showTasktrayIcon(); - break; - case ID_MENUITEM_quit: - This->m_engine.prepairQuit(); - PostQuitMessage(0); - break; - } - return 0; + m_log << _T("successfully loaded.") << std::endl; + while (!m_engine.setSetting(newSetting)) + Sleep(1000); + delete m_setting; + m_setting = newSetting; } - case WM_APP_engineNotify: - { - switch (i_wParam) - { - case EngineNotify_shellExecute: - This->m_engine.shellExecute(); - break; - case EngineNotify_loadSetting: - This->load(); - break; - case EngineNotify_helpMessage: - This->showHelpMessage(false); - if (i_lParam) - This->showHelpMessage(true); - break; - case EngineNotify_showDlg: - { - // show investigate/log window - int sw = (i_lParam & ~MayuDialogType_mask); - HWND hwnd = NULL; - switch (static_cast( - i_lParam & MayuDialogType_mask)) - { - case MayuDialogType_investigate: - hwnd = This->m_hwndInvestigate; - break; - case MayuDialogType_log: - hwnd = This->m_hwndLog; - break; - } - if (hwnd) - { - ShowWindow(hwnd, sw); - switch (sw) - { - case SW_SHOWNORMAL: - case SW_SHOWMAXIMIZED: - case SW_SHOW: - case SW_RESTORE: - case SW_SHOWDEFAULT: - SetForegroundWindow(hwnd); - break; + // show message (a baloon from the task tray icon) + void showHelpMessage(bool i_doesShow = true) { + if (m_canUseTasktrayBaloon) { + if (i_doesShow) { + tstring helpMessage, helpTitle; + m_engine.getHelpMessages(&helpMessage, &helpTitle); + tcslcpy(m_ni.szInfo, helpMessage.c_str(), NUMBER_OF(m_ni.szInfo)); + tcslcpy(m_ni.szInfoTitle, helpTitle.c_str(), + NUMBER_OF(m_ni.szInfoTitle)); + m_ni.dwInfoFlags = NIIF_INFO; + } else + m_ni.szInfo[0] = m_ni.szInfoTitle[0] = _T('\0'); + CHECK_TRUE( Shell_NotifyIcon(NIM_MODIFY, &m_ni) ); } - } - break; - } - case EngineNotify_setForegroundWindow: - // FIXME: completely useless. why ? - setForegroundWindow(reinterpret_cast(i_lParam)); - { - Acquire a(&This->m_log, 1); - This->m_log << _T("setForegroundWindow(0x") - << std::hex << i_lParam << std::dec << _T(")") - << std::endl; - } - break; - case EngineNotify_clearLog: - SendMessage(This->m_hwndLog, WM_COMMAND, - MAKELONG(IDC_BUTTON_clearLog, 0), 0); - break; - default: - break; - } - return 0; - } - - case WM_APP_dlglogNotify: - { - switch (i_wParam) - { - case DlgLogNotify_logCleared: - This->showBanner(true); - break; - default: - break; - } - return 0; } - case WM_DESTROY: - if (This->m_usingSN) - { - wtsUnRegisterSessionNotification(i_hwnd); - This->m_usingSN = false; - } - return 0; - - default: - if (i_message == This->m_WM_TaskbarRestart) - { - if (This->showTasktrayIcon(true)) - { - Acquire a(&This->m_log, 0); - This->m_log << _T("Tasktray icon is updated.") << std::endl; - } - else - { - Acquire a(&This->m_log, 1); - This->m_log << _T("Tasktray icon already exists.") << std::endl; - } - return 0; - } - else if (i_message == This->m_WM_MayuIPC) - { - switch (static_cast(i_wParam)) - { - case MayuIPCCommand_Enable: - This->m_engine.enable(!!i_lParam); - This->showTasktrayIcon(); - if (i_lParam) - { - Acquire a(&This->m_log, 1); - This->m_log << _T("Enabled by another application.") - << std::endl; + // change the task tray icon + bool showTasktrayIcon(bool i_doesAdd = false) { + m_ni.hIcon = m_tasktrayIcon[m_engine.getIsEnabled() ? 1 : 0]; + m_ni.szInfo[0] = m_ni.szInfoTitle[0] = _T('\0'); + if (i_doesAdd) { + // http://support.microsoft.com/kb/418138/JA/ + int guard = 60; + for (; !Shell_NotifyIcon(NIM_ADD, &m_ni) && 0 < guard; -- guard) { + if (Shell_NotifyIcon(NIM_MODIFY, &m_ni)) { + return true; + } + Sleep(1000); // 1sec + } + return 0 < guard; + } else { + return !!Shell_NotifyIcon(NIM_MODIFY, &m_ni); } - else - { - Acquire a(&This->m_log, 1); - This->m_log << _T("Disabled by another application.") - << std::endl; - } - break; - } - } - } - return DefWindowProc(i_hwnd, i_message, i_wParam, i_lParam); - } - - /// load setting - void load() - { - Setting *newSetting = new Setting; - - // set symbol - for (int i = 1; i < __argc; ++ i) - { - if (__targv[i][0] == _T('-') && __targv[i][1] == _T('D')) - newSetting->m_symbols.insert(__targv[i] + 2); - } - - if (!SettingLoader(&m_log, &m_log).load(newSetting)) - { - ShowWindow(m_hwndLog, SW_SHOW); - SetForegroundWindow(m_hwndLog); - delete newSetting; - Acquire a(&m_log, 0); - m_log << _T("error: failed to load.") << std::endl; - return; - } - m_log << _T("successfully loaded.") << std::endl; - while (!m_engine.setSetting(newSetting)) - Sleep(1000); - delete m_setting; - m_setting = newSetting; - } - - // show message (a baloon from the task tray icon) - void showHelpMessage(bool i_doesShow = true) - { - if (m_canUseTasktrayBaloon) - { - if (i_doesShow) - { - tstring helpMessage, helpTitle; - m_engine.getHelpMessages(&helpMessage, &helpTitle); - tcslcpy(m_ni.szInfo, helpMessage.c_str(), NUMBER_OF(m_ni.szInfo)); - tcslcpy(m_ni.szInfoTitle, helpTitle.c_str(), - NUMBER_OF(m_ni.szInfoTitle)); - m_ni.dwInfoFlags = NIIF_INFO; - } - else - m_ni.szInfo[0] = m_ni.szInfoTitle[0] = _T('\0'); - CHECK_TRUE( Shell_NotifyIcon(NIM_MODIFY, &m_ni) ); - } - } - - // change the task tray icon - bool showTasktrayIcon(bool i_doesAdd = false) - { - m_ni.hIcon = m_tasktrayIcon[m_engine.getIsEnabled() ? 1 : 0]; - m_ni.szInfo[0] = m_ni.szInfoTitle[0] = _T('\0'); - if (i_doesAdd) { - // http://support.microsoft.com/kb/418138/JA/ - int guard = 60; - for (; !Shell_NotifyIcon(NIM_ADD, &m_ni) && 0 < guard; -- guard) { - if (Shell_NotifyIcon(NIM_MODIFY, &m_ni)) { - return true; } - Sleep(1000); // 1sec - } - return 0 < guard; - } else { - return !!Shell_NotifyIcon(NIM_MODIFY, &m_ni); - } - } - - void showBanner(bool i_isCleared) - { - time_t now; - time(&now); - - _TCHAR starttimebuf[1024]; - _TCHAR timebuf[1024]; + + void showBanner(bool i_isCleared) { + time_t now; + time(&now); + + _TCHAR starttimebuf[1024]; + _TCHAR timebuf[1024]; #ifdef __BORLANDC__ #pragma message("\t\t****\tAfter std::ostream() is called, ") #pragma message("\t\t****\tstrftime(... \"%%#c\" ...) fails.") #pragma message("\t\t****\tWhy ? Bug of Borland C++ 5.5.1 ? ") #pragma message("\t\t****\t - nayuta") - _tcsftime(timebuf, NUMBER_OF(timebuf), _T("%Y/%m/%d %H:%M:%S"), - localtime(&now)); - _tcsftime(starttimebuf, NUMBER_OF(starttimebuf), _T("%Y/%m/%d %H:%M:%S"), - localtime(&m_startTime)); + _tcsftime(timebuf, NUMBER_OF(timebuf), _T("%Y/%m/%d %H:%M:%S"), + localtime(&now)); + _tcsftime(starttimebuf, NUMBER_OF(starttimebuf), _T("%Y/%m/%d %H:%M:%S"), + localtime(&m_startTime)); #else - _tcsftime(timebuf, NUMBER_OF(timebuf), _T("%#c"), localtime(&now)); - _tcsftime(starttimebuf, NUMBER_OF(starttimebuf), _T("%#c"), - localtime(&m_startTime)); + _tcsftime(timebuf, NUMBER_OF(timebuf), _T("%#c"), localtime(&now)); + _tcsftime(starttimebuf, NUMBER_OF(starttimebuf), _T("%#c"), + localtime(&m_startTime)); #endif - - Acquire a(&m_log, 0); - m_log << _T("------------------------------------------------------------") << std::endl; - m_log << loadString(IDS_mayu) << _T(" ") _T(VERSION); + + Acquire a(&m_log, 0); + m_log << _T("------------------------------------------------------------") << std::endl; + m_log << loadString(IDS_mayu) << _T(" ") _T(VERSION); #ifndef NDEBUG - m_log << _T(" (DEBUG)"); + m_log << _T(" (DEBUG)"); #endif #ifdef _UNICODE - m_log << _T(" (UNICODE)"); + m_log << _T(" (UNICODE)"); #endif - m_log << std::endl; - m_log << _T(" built by ") - << _T(LOGNAME) << _T("@") << toLower(_T(COMPUTERNAME)) - << _T(" (") << _T(__DATE__) << _T(" ") - << _T(__TIME__) << _T(", ") - << getCompilerVersionString() << _T(")") << std::endl; - _TCHAR modulebuf[1024]; - CHECK_TRUE( GetModuleFileName(g_hInst, modulebuf, - NUMBER_OF(modulebuf)) ); - m_log << _T("started at ") << starttimebuf << std::endl; - m_log << modulebuf << std::endl; - m_log << _T("------------------------------------------------------------") << std::endl; - - if (i_isCleared) { - m_log << _T("log was cleared at ") << timebuf << std::endl; - } else { - m_log << _T("log begins at ") << timebuf << std::endl; - } - } + m_log << std::endl; + m_log << _T(" built by ") + << _T(LOGNAME) << _T("@") << toLower(_T(COMPUTERNAME)) + << _T(" (") << _T(__DATE__) << _T(" ") + << _T(__TIME__) << _T(", ") + << getCompilerVersionString() << _T(")") << std::endl; + _TCHAR modulebuf[1024]; + CHECK_TRUE( GetModuleFileName(g_hInst, modulebuf, + NUMBER_OF(modulebuf)) ); + m_log << _T("started at ") << starttimebuf << std::endl; + m_log << modulebuf << std::endl; + m_log << _T("------------------------------------------------------------") << std::endl; + + if (i_isCleared) { + m_log << _T("log was cleared at ") << timebuf << std::endl; + } else { + m_log << _T("log begins at ") << timebuf << std::endl; + } + } public: - /// - Mayu(HANDLE i_mutex) - : m_hwndTaskTray(NULL), - m_mutex(i_mutex), - m_hwndLog(NULL), - m_WM_TaskbarRestart(RegisterWindowMessage(_T("TaskbarCreated"))), - m_WM_MayuIPC(RegisterWindowMessage(WM_MayuIPC_NAME)), - m_canUseTasktrayBaloon( - PACKVERSION(5, 0) <= getDllVersion(_T("shlwapi.dll"))), - m_log(WM_APP_msgStreamNotify), - m_setting(NULL), - m_isSettingDialogOpened(false), - m_engine(m_log) - { + /// + Mayu(HANDLE i_mutex) + : m_hwndTaskTray(NULL), + m_mutex(i_mutex), + m_hwndLog(NULL), + m_WM_TaskbarRestart(RegisterWindowMessage(_T("TaskbarCreated"))), + m_WM_MayuIPC(RegisterWindowMessage(WM_MayuIPC_NAME)), + m_canUseTasktrayBaloon( + PACKVERSION(5, 0) <= getDllVersion(_T("shlwapi.dll"))), + m_log(WM_APP_msgStreamNotify), + m_setting(NULL), + m_isSettingDialogOpened(false), + m_engine(m_log) { #ifdef USE_MAILSLOT - m_hNotifyMailslot = CreateMailslot(NOTIFY_MAILSLOT_NAME, 0, MAILSLOT_WAIT_FOREVER, (SECURITY_ATTRIBUTES *)NULL); - ASSERT(m_hNotifyMailslot != INVALID_HANDLE_VALUE); - m_hNotifyEvent = CreateEvent(NULL, FALSE, FALSE, NULL); - ASSERT(m_hNotifyEvent); - m_olNotify.Offset = 0; - m_olNotify.OffsetHigh = 0; - m_olNotify.hEvent = m_hNotifyEvent; + m_hNotifyMailslot = CreateMailslot(NOTIFY_MAILSLOT_NAME, 0, MAILSLOT_WAIT_FOREVER, (SECURITY_ATTRIBUTES *)NULL); + ASSERT(m_hNotifyMailslot != INVALID_HANDLE_VALUE); + m_hNotifyEvent = CreateEvent(NULL, FALSE, FALSE, NULL); + ASSERT(m_hNotifyEvent); + m_olNotify.Offset = 0; + m_olNotify.OffsetHigh = 0; + m_olNotify.hEvent = m_hNotifyEvent; #endif // USE_MAILSLOT - time(&m_startTime); + time(&m_startTime); - CHECK_TRUE( Register_focus() ); - CHECK_TRUE( Register_target() ); - CHECK_TRUE( Register_tasktray() ); + CHECK_TRUE( Register_focus() ); + CHECK_TRUE( Register_target() ); + CHECK_TRUE( Register_tasktray() ); - // change dir + // change dir #if 0 - HomeDirectories pathes; - getHomeDirectories(&pathes); - for (HomeDirectories::iterator i = pathes.begin(); i != pathes.end(); ++ i) - if (SetCurrentDirectory(i->c_str())) - break; + HomeDirectories pathes; + getHomeDirectories(&pathes); + for (HomeDirectories::iterator i = pathes.begin(); i != pathes.end(); ++ i) + if (SetCurrentDirectory(i->c_str())) + break; #endif - - // create windows, dialogs - tstringi title = loadString(IDS_mayu); - m_hwndTaskTray = CreateWindow(_T("mayuTasktray"), title.c_str(), - WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, CW_USEDEFAULT, - CW_USEDEFAULT, CW_USEDEFAULT, - NULL, NULL, g_hInst, this); - CHECK_TRUE( m_hwndTaskTray ); - - // set window handle of tasktray to hooks + + // create windows, dialogs + tstringi title = loadString(IDS_mayu); + m_hwndTaskTray = CreateWindow(_T("mayuTasktray"), title.c_str(), + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, CW_USEDEFAULT, + CW_USEDEFAULT, CW_USEDEFAULT, + NULL, NULL, g_hInst, this); + CHECK_TRUE( m_hwndTaskTray ); + + // set window handle of tasktray to hooks #ifndef USE_MAILSLOT - g_hookData->m_hwndTaskTray = reinterpret_cast(m_hwndTaskTray); + g_hookData->m_hwndTaskTray = reinterpret_cast(m_hwndTaskTray); #endif // !USE_MAILSLOT - CHECK_FALSE( installHooks(Engine::keyboardDetour, &m_engine) ); - m_usingSN = wtsRegisterSessionNotification(m_hwndTaskTray, - NOTIFY_FOR_THIS_SESSION); - - DlgLogData dld; - dld.m_log = &m_log; - dld.m_hwndTaskTray = m_hwndTaskTray; - m_hwndLog = - CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_log), NULL, - dlgLog_dlgProc, (LPARAM)&dld); - CHECK_TRUE( m_hwndLog ); - - DlgInvestigateData did; - did.m_engine = &m_engine; - did.m_hwndLog = m_hwndLog; - m_hwndInvestigate = - CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_investigate), NULL, - dlgInvestigate_dlgProc, (LPARAM)&did); - CHECK_TRUE( m_hwndInvestigate ); - - m_hwndVersion = - CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_version), - NULL, dlgVersion_dlgProc, - (LPARAM)m_engine.getMayudVersion().c_str()); - CHECK_TRUE( m_hwndVersion ); - - // attach log + CHECK_FALSE( installHooks(Engine::keyboardDetour, &m_engine) ); + m_usingSN = wtsRegisterSessionNotification(m_hwndTaskTray, + NOTIFY_FOR_THIS_SESSION); + + DlgLogData dld; + dld.m_log = &m_log; + dld.m_hwndTaskTray = m_hwndTaskTray; + m_hwndLog = + CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_log), NULL, + dlgLog_dlgProc, (LPARAM)&dld); + CHECK_TRUE( m_hwndLog ); + + DlgInvestigateData did; + did.m_engine = &m_engine; + did.m_hwndLog = m_hwndLog; + m_hwndInvestigate = + CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_investigate), NULL, + dlgInvestigate_dlgProc, (LPARAM)&did); + CHECK_TRUE( m_hwndInvestigate ); + + m_hwndVersion = + CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_version), + NULL, dlgVersion_dlgProc, + (LPARAM)m_engine.getMayudVersion().c_str()); + CHECK_TRUE( m_hwndVersion ); + + // attach log #ifdef LOG_TO_FILE - tstring path; - _TCHAR exePath[GANA_MAX_PATH]; - _TCHAR exeDrive[GANA_MAX_PATH]; - _TCHAR exeDir[GANA_MAX_PATH]; - GetModuleFileName(NULL, exePath, GANA_MAX_PATH); - _tsplitpath_s(exePath, exeDrive, GANA_MAX_PATH, exeDir, GANA_MAX_PATH, NULL, 0, NULL, 0); - path = exeDrive; - path += exeDir; - path += _T("mayu.log"); - m_logFile.open(path.c_str(), std::ios::app); - m_logFile.imbue(std::locale("japanese")); + tstring path; + _TCHAR exePath[GANA_MAX_PATH]; + _TCHAR exeDrive[GANA_MAX_PATH]; + _TCHAR exeDir[GANA_MAX_PATH]; + GetModuleFileName(NULL, exePath, GANA_MAX_PATH); + _tsplitpath_s(exePath, exeDrive, GANA_MAX_PATH, exeDir, GANA_MAX_PATH, NULL, 0, NULL, 0); + path = exeDrive; + path += exeDir; + path += _T("mayu.log"); + m_logFile.open(path.c_str(), std::ios::app); + m_logFile.imbue(std::locale("japanese")); #endif // LOG_TO_FILE - SendMessage(GetDlgItem(m_hwndLog, IDC_EDIT_log), EM_SETLIMITTEXT, 0, 0); - m_log.attach(m_hwndTaskTray); - - // start keyboard handler thread - m_engine.setAssociatedWndow(m_hwndTaskTray); - m_engine.start(); - - // show tasktray icon - m_tasktrayIcon[0] = loadSmallIcon(IDI_ICON_mayu_disabled); - m_tasktrayIcon[1] = loadSmallIcon(IDI_ICON_mayu); - std::memset(&m_ni, 0, sizeof(m_ni)); - m_ni.uID = ID_TaskTrayIcon; - m_ni.hWnd = m_hwndTaskTray; - m_ni.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; - m_ni.hIcon = m_tasktrayIcon[1]; - m_ni.uCallbackMessage = WM_APP_taskTrayNotify; - tstring tip = loadString(IDS_mayu); - tcslcpy(m_ni.szTip, tip.c_str(), NUMBER_OF(m_ni.szTip)); - if (m_canUseTasktrayBaloon) - { - m_ni.cbSize = sizeof(m_ni); - m_ni.uFlags |= NIF_INFO; - } - else - m_ni.cbSize = NOTIFYICONDATA_V1_SIZE; - showTasktrayIcon(true); - - // create menu - m_hMenuTaskTray = LoadMenu(g_hInst, MAKEINTRESOURCE(IDR_MENU_tasktray)); - ASSERT(m_hMenuTaskTray); - - // set initial lock state - notifyLockState(); - - BOOL result; - - ZeroMemory(&m_pi,sizeof(m_pi)); - ZeroMemory(&m_si,sizeof(m_si)); - m_si.cb=sizeof(m_si); + SendMessage(GetDlgItem(m_hwndLog, IDC_EDIT_log), EM_SETLIMITTEXT, 0, 0); + m_log.attach(m_hwndTaskTray); + + // start keyboard handler thread + m_engine.setAssociatedWndow(m_hwndTaskTray); + m_engine.start(); + + // show tasktray icon + m_tasktrayIcon[0] = loadSmallIcon(IDI_ICON_mayu_disabled); + m_tasktrayIcon[1] = loadSmallIcon(IDI_ICON_mayu); + std::memset(&m_ni, 0, sizeof(m_ni)); + m_ni.uID = ID_TaskTrayIcon; + m_ni.hWnd = m_hwndTaskTray; + m_ni.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; + m_ni.hIcon = m_tasktrayIcon[1]; + m_ni.uCallbackMessage = WM_APP_taskTrayNotify; + tstring tip = loadString(IDS_mayu); + tcslcpy(m_ni.szTip, tip.c_str(), NUMBER_OF(m_ni.szTip)); + if (m_canUseTasktrayBaloon) { + m_ni.cbSize = sizeof(m_ni); + m_ni.uFlags |= NIF_INFO; + } else + m_ni.cbSize = NOTIFYICONDATA_V1_SIZE; + showTasktrayIcon(true); + + // create menu + m_hMenuTaskTray = LoadMenu(g_hInst, MAKEINTRESOURCE(IDR_MENU_tasktray)); + ASSERT(m_hMenuTaskTray); + + // set initial lock state + notifyLockState(); + + BOOL result; + + ZeroMemory(&m_pi,sizeof(m_pi)); + ZeroMemory(&m_si,sizeof(m_si)); + m_si.cb=sizeof(m_si); #ifdef _WIN64 - result = CreateProcess(_T("yamyd32"), _T("yamyd32"), NULL, NULL, FALSE, - NORMAL_PRIORITY_CLASS, 0, NULL, &m_si, &m_pi); - if (result == FALSE) - { - TCHAR buf[1024]; - TCHAR text[1024]; - TCHAR title[1024]; - - LoadString(GetModuleHandle(NULL), IDS_cannotInvoke, - text, sizeof(text)/sizeof(text[0])); - LoadString(GetModuleHandle(NULL), IDS_mayu, - title, sizeof(title)/sizeof(title[0])); - _stprintf_s(buf, sizeof(buf)/sizeof(buf[0]), - text, _T("yamyd32"), GetLastError()); - MessageBox((HWND)NULL, buf, title, MB_OK | MB_ICONSTOP); - } - else - { - CloseHandle(m_pi.hThread); - CloseHandle(m_pi.hProcess); - } + result = CreateProcess(_T("yamyd32"), _T("yamyd32"), NULL, NULL, FALSE, + NORMAL_PRIORITY_CLASS, 0, NULL, &m_si, &m_pi); + if (result == FALSE) { + TCHAR buf[1024]; + TCHAR text[1024]; + TCHAR title[1024]; + + LoadString(GetModuleHandle(NULL), IDS_cannotInvoke, + text, sizeof(text)/sizeof(text[0])); + LoadString(GetModuleHandle(NULL), IDS_mayu, + title, sizeof(title)/sizeof(title[0])); + _stprintf_s(buf, sizeof(buf)/sizeof(buf[0]), + text, _T("yamyd32"), GetLastError()); + MessageBox((HWND)NULL, buf, title, MB_OK | MB_ICONSTOP); + } else { + CloseHandle(m_pi.hThread); + CloseHandle(m_pi.hProcess); + } #endif // _WIN64 - } - - /// - ~Mayu() - { - ReleaseMutex(m_mutex); - WaitForSingleObject(m_mutex, INFINITE); - // first, detach log from edit control to avoid deadlock - m_log.detach(); + } + + /// + ~Mayu() { + ReleaseMutex(m_mutex); + WaitForSingleObject(m_mutex, INFINITE); + // first, detach log from edit control to avoid deadlock + m_log.detach(); #ifdef LOG_TO_FILE - m_logFile.close(); + m_logFile.close(); #endif // LOG_TO_FILE - - // stop notify from mayu.dll - g_hookData->m_hwndTaskTray = NULL; - CHECK_FALSE( uninstallHooks() ); - PostMessage(HWND_BROADCAST, WM_NULL, 0, 0); - - // destroy windows - CHECK_TRUE( DestroyWindow(m_hwndVersion) ); - CHECK_TRUE( DestroyWindow(m_hwndInvestigate) ); - CHECK_TRUE( DestroyWindow(m_hwndLog) ); - CHECK_TRUE( DestroyWindow(m_hwndTaskTray) ); - - // destroy menu - DestroyMenu(m_hMenuTaskTray); - - // delete tasktray icon - CHECK_TRUE( Shell_NotifyIcon(NIM_DELETE, &m_ni) ); - CHECK_TRUE( DestroyIcon(m_tasktrayIcon[1]) ); - CHECK_TRUE( DestroyIcon(m_tasktrayIcon[0]) ); - - // stop keyboard handler thread - m_engine.stop(); - - // remove setting; - delete m_setting; - + + // stop notify from mayu.dll + g_hookData->m_hwndTaskTray = NULL; + CHECK_FALSE( uninstallHooks() ); + PostMessage(HWND_BROADCAST, WM_NULL, 0, 0); + + // destroy windows + CHECK_TRUE( DestroyWindow(m_hwndVersion) ); + CHECK_TRUE( DestroyWindow(m_hwndInvestigate) ); + CHECK_TRUE( DestroyWindow(m_hwndLog) ); + CHECK_TRUE( DestroyWindow(m_hwndTaskTray) ); + + // destroy menu + DestroyMenu(m_hMenuTaskTray); + + // delete tasktray icon + CHECK_TRUE( Shell_NotifyIcon(NIM_DELETE, &m_ni) ); + CHECK_TRUE( DestroyIcon(m_tasktrayIcon[1]) ); + CHECK_TRUE( DestroyIcon(m_tasktrayIcon[0]) ); + + // stop keyboard handler thread + m_engine.stop(); + + // remove setting; + delete m_setting; + #ifdef USE_MAILSLOT - CloseHandle(m_hNotifyEvent); - CloseHandle(m_hNotifyMailslot); + CloseHandle(m_hNotifyEvent); + CloseHandle(m_hNotifyMailslot); #endif // USE_MAILSLOT - } - - /// message loop - WPARAM messageLoop() - { - showBanner(false); - load(); - -#ifdef USE_MAILSLOT - mailslotHandler(0, 0); - while (1) - { - HANDLE handles[] = { m_hNotifyEvent }; - DWORD ret; - switch (ret = MsgWaitForMultipleObjectsEx(NUMBER_OF(handles), &handles[0], - INFINITE, QS_ALLINPUT, MWMO_ALERTABLE | MWMO_INPUTAVAILABLE)) - { - case WAIT_OBJECT_0: // m_hNotifyEvent - break; - - case WAIT_OBJECT_0 + NUMBER_OF(handles): - { - MSG msg; - if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != 0) - { - if (msg.message == WM_QUIT) - { - return msg.wParam; - } - if (IsDialogMessage(m_hwndLog, &msg)) - break; - if (IsDialogMessage(m_hwndInvestigate, &msg)) - break; - if (IsDialogMessage(m_hwndVersion, &msg)) - break; - TranslateMessage(&msg); - DispatchMessage(&msg); - break; - } - break; } - - case WAIT_IO_COMPLETION: - break; - - case 0x102: - default: - break; - } - } + + /// message loop + WPARAM messageLoop() { + showBanner(false); + load(); + +#ifdef USE_MAILSLOT + mailslotHandler(0, 0); + while (1) { + HANDLE handles[] = { m_hNotifyEvent }; + DWORD ret; + switch (ret = MsgWaitForMultipleObjectsEx(NUMBER_OF(handles), &handles[0], + INFINITE, QS_ALLINPUT, MWMO_ALERTABLE | MWMO_INPUTAVAILABLE)) { + case WAIT_OBJECT_0: // m_hNotifyEvent + break; + + case WAIT_OBJECT_0 + NUMBER_OF(handles): { + MSG msg; + if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != 0) { + if (msg.message == WM_QUIT) { + return msg.wParam; + } + if (IsDialogMessage(m_hwndLog, &msg)) + break; + if (IsDialogMessage(m_hwndInvestigate, &msg)) + break; + if (IsDialogMessage(m_hwndVersion, &msg)) + break; + TranslateMessage(&msg); + DispatchMessage(&msg); + break; + } + break; + } + + case WAIT_IO_COMPLETION: + break; + + case 0x102: + default: + break; + } + } #else // !USE_MAILSLOT - MSG msg; - while (0 < GetMessage(&msg, NULL, 0, 0)) - { - if (IsDialogMessage(m_hwndLog, &msg)) - continue; - if (IsDialogMessage(m_hwndInvestigate, &msg)) - continue; - if (IsDialogMessage(m_hwndVersion, &msg)) - continue; - TranslateMessage(&msg); - DispatchMessage(&msg); - } - return msg.wParam; + MSG msg; + while (0 < GetMessage(&msg, NULL, 0, 0)) { + if (IsDialogMessage(m_hwndLog, &msg)) + continue; + if (IsDialogMessage(m_hwndInvestigate, &msg)) + continue; + if (IsDialogMessage(m_hwndVersion, &msg)) + continue; + TranslateMessage(&msg); + DispatchMessage(&msg); + } + return msg.wParam; #endif // !USE_MAILSLOT - } + } }; @@ -1068,122 +996,109 @@ public: /// convert registry void convertRegistry() { - Registry reg(MAYU_REGISTRY_ROOT); - tstringi dot_mayu; - bool doesAdd = false; - DWORD index; - if (reg.read(_T(".mayu"), &dot_mayu)) - { - reg.write(_T(".mayu0"), _T(";") + dot_mayu + _T(";")); - reg.remove(_T(".mayu")); - doesAdd = true; - index = 0; - } - else if (!reg.read(_T(".mayu0"), &dot_mayu)) - { - reg.write(_T(".mayu0"), loadString(IDS_readFromHomeDirectory) + _T(";;")); - doesAdd = true; - index = 1; - } - if (doesAdd) - { - Registry commonreg(HKEY_LOCAL_MACHINE, _T("Software\\GANAware\\mayu")); - tstringi dir, layout; - if (commonreg.read(_T("dir"), &dir) && - commonreg.read(_T("layout"), &layout)) - { - tstringi tmp = _T(";") + dir + _T("\\dot.mayu"); - if (layout == _T("109")) - { - reg.write(_T(".mayu1"), loadString(IDS_109Emacs) + tmp - + _T(";-DUSE109") _T(";-DUSEdefault")); - reg.write(_T(".mayu2"), loadString(IDS_104on109Emacs) + tmp - + _T(";-DUSE109") _T(";-DUSEdefault") _T(";-DUSE104on109")); - reg.write(_T(".mayu3"), loadString(IDS_109) + tmp - + _T(";-DUSE109")); - reg.write(_T(".mayu4"), loadString(IDS_104on109) + tmp - + _T(";-DUSE109") _T(";-DUSE104on109")); - } - else - { - reg.write(_T(".mayu1"), loadString(IDS_104Emacs) + tmp - + _T(";-DUSE104") _T(";-DUSEdefault")); - reg.write(_T(".mayu2"), loadString(IDS_109on104Emacs) + tmp - + _T(";-DUSE104") _T(";-DUSEdefault") _T(";-DUSE109on104")); - reg.write(_T(".mayu3"), loadString(IDS_104) + tmp - + _T(";-DUSE104")); - reg.write(_T(".mayu4"), loadString(IDS_109on104) + tmp - + _T(";-DUSE104") _T(";-DUSE109on104")); - } - reg.write(_T(".mayuIndex"), index); - } - } + Registry reg(MAYU_REGISTRY_ROOT); + tstringi dot_mayu; + bool doesAdd = false; + DWORD index; + if (reg.read(_T(".mayu"), &dot_mayu)) { + reg.write(_T(".mayu0"), _T(";") + dot_mayu + _T(";")); + reg.remove(_T(".mayu")); + doesAdd = true; + index = 0; + } else if (!reg.read(_T(".mayu0"), &dot_mayu)) { + reg.write(_T(".mayu0"), loadString(IDS_readFromHomeDirectory) + _T(";;")); + doesAdd = true; + index = 1; + } + if (doesAdd) { + Registry commonreg(HKEY_LOCAL_MACHINE, _T("Software\\GANAware\\mayu")); + tstringi dir, layout; + if (commonreg.read(_T("dir"), &dir) && + commonreg.read(_T("layout"), &layout)) { + tstringi tmp = _T(";") + dir + _T("\\dot.mayu"); + if (layout == _T("109")) { + reg.write(_T(".mayu1"), loadString(IDS_109Emacs) + tmp + + _T(";-DUSE109") _T(";-DUSEdefault")); + reg.write(_T(".mayu2"), loadString(IDS_104on109Emacs) + tmp + + _T(";-DUSE109") _T(";-DUSEdefault") _T(";-DUSE104on109")); + reg.write(_T(".mayu3"), loadString(IDS_109) + tmp + + _T(";-DUSE109")); + reg.write(_T(".mayu4"), loadString(IDS_104on109) + tmp + + _T(";-DUSE109") _T(";-DUSE104on109")); + } else { + reg.write(_T(".mayu1"), loadString(IDS_104Emacs) + tmp + + _T(";-DUSE104") _T(";-DUSEdefault")); + reg.write(_T(".mayu2"), loadString(IDS_109on104Emacs) + tmp + + _T(";-DUSE104") _T(";-DUSEdefault") _T(";-DUSE109on104")); + reg.write(_T(".mayu3"), loadString(IDS_104) + tmp + + _T(";-DUSE104")); + reg.write(_T(".mayu4"), loadString(IDS_109on104) + tmp + + _T(";-DUSE104") _T(";-DUSE109on104")); + } + reg.write(_T(".mayuIndex"), index); + } + } } /// main int WINAPI _tWinMain(HINSTANCE i_hInstance, HINSTANCE /* i_hPrevInstance */, - LPTSTR /* i_lpszCmdLine */, int /* i_nCmdShow */) + LPTSTR /* i_lpszCmdLine */, int /* i_nCmdShow */) { - g_hInst = i_hInstance; + g_hInst = i_hInstance; - // set locale - CHECK_TRUE( _tsetlocale(LC_ALL, _T("")) ); + // set locale + CHECK_TRUE( _tsetlocale(LC_ALL, _T("")) ); - // common controls + // common controls #if defined(_WIN95) - InitCommonControls(); + InitCommonControls(); #else - INITCOMMONCONTROLSEX icc; - icc.dwSize = sizeof(icc); - icc.dwICC = ICC_LISTVIEW_CLASSES; - CHECK_TRUE( InitCommonControlsEx(&icc) ); + INITCOMMONCONTROLSEX icc; + icc.dwSize = sizeof(icc); + icc.dwICC = ICC_LISTVIEW_CLASSES; + CHECK_TRUE( InitCommonControlsEx(&icc) ); #endif - // convert old registry to new registry + // convert old registry to new registry #ifndef USE_INI - convertRegistry(); + convertRegistry(); #endif // !USE_INI - - // is another mayu running ? - HANDLE mutex = CreateMutex((SECURITY_ATTRIBUTES *)NULL, TRUE, - MUTEX_MAYU_EXCLUSIVE_RUNNING); - if (GetLastError() == ERROR_ALREADY_EXISTS) - { - // another mayu already running - tstring text = loadString(IDS_mayuAlreadyExists); - tstring title = loadString(IDS_mayu); - if (g_hookData) { - UINT WM_TaskbarRestart = RegisterWindowMessage(_T("TaskbarCreated")); - PostMessage(reinterpret_cast(g_hookData->m_hwndTaskTray), - WM_TaskbarRestart, 0, 0); - } - MessageBox((HWND)NULL, text.c_str(), title.c_str(), MB_OK | MB_ICONSTOP); - return 1; - } - - // check remote desktop - DWORD sessionId; - if (!ProcessIdToSessionId(GetCurrentProcessId(), &sessionId) || - wtsGetActiveConsoleSessionId() != sessionId) - { - tstring text = loadString(IDS_executedInRemoteDesktop); - tstring title = loadString(IDS_mayu); - MessageBox((HWND)NULL, text.c_str(), title.c_str(), MB_OK | MB_ICONSTOP); - return 1; - } - - try - { - Mayu(mutex).messageLoop(); - } - catch (ErrorMessage &i_e) - { - tstring title = loadString(IDS_mayu); - MessageBox((HWND)NULL, i_e.getMessage().c_str(), title.c_str(), - MB_OK | MB_ICONSTOP); - } - - CHECK_TRUE( CloseHandle(mutex) ); - return 0; + + // is another mayu running ? + HANDLE mutex = CreateMutex((SECURITY_ATTRIBUTES *)NULL, TRUE, + MUTEX_MAYU_EXCLUSIVE_RUNNING); + if (GetLastError() == ERROR_ALREADY_EXISTS) { + // another mayu already running + tstring text = loadString(IDS_mayuAlreadyExists); + tstring title = loadString(IDS_mayu); + if (g_hookData) { + UINT WM_TaskbarRestart = RegisterWindowMessage(_T("TaskbarCreated")); + PostMessage(reinterpret_cast(g_hookData->m_hwndTaskTray), + WM_TaskbarRestart, 0, 0); + } + MessageBox((HWND)NULL, text.c_str(), title.c_str(), MB_OK | MB_ICONSTOP); + return 1; + } + + // check remote desktop + DWORD sessionId; + if (!ProcessIdToSessionId(GetCurrentProcessId(), &sessionId) || + wtsGetActiveConsoleSessionId() != sessionId) { + tstring text = loadString(IDS_executedInRemoteDesktop); + tstring title = loadString(IDS_mayu); + MessageBox((HWND)NULL, text.c_str(), title.c_str(), MB_OK | MB_ICONSTOP); + return 1; + } + + try { + Mayu(mutex).messageLoop(); + } catch (ErrorMessage &i_e) { + tstring title = loadString(IDS_mayu); + MessageBox((HWND)NULL, i_e.getMessage().c_str(), title.c_str(), + MB_OK | MB_ICONSTOP); + } + + CHECK_TRUE( CloseHandle(mutex) ); + return 0; } diff --git a/mayuipc.h b/mayuipc.h index 5b5bbd0..2c37794 100644 --- a/mayuipc.h +++ b/mayuipc.h @@ -7,50 +7,45 @@ # include # ifdef __cplusplus -extern "C" { +extern "C" +{ # endif // __cplusplus -/// +/// # define WM_MayuIPC_NAME _T("MayuIPC{46269F4D-D560-40f9-B38B-DB5E280FEF47}") -enum MayuIPCCommand -{ - // enable or disable Mayu - MayuIPCCommand_Enable = 1, -}; + enum MayuIPCCommand { + // enable or disable Mayu + MayuIPCCommand_Enable = 1, + }; -BOOL MayuIPC_PostMessage(MayuIPCCommand i_wParam, LPARAM i_lParam); -BOOL MayuIPC_Enable(BOOL i_isEnabled); + BOOL MayuIPC_PostMessage(MayuIPCCommand i_wParam, LPARAM i_lParam); + BOOL MayuIPC_Enable(BOOL i_isEnabled); # ifdef _MAYUIPC_H_DEFINE_FUNCTIONS -BOOL MayuIPC_PostMessage(MayuIPCCommand i_command, LPARAM i_lParam) -{ - static UINT WM_MayuIPC; - HWND hwnd; - - if (WM_MayuIPC == 0) - { - WM_MayuIPC = RegisterWindowMessage(WM_MayuIPC_NAME); - if (WM_MayuIPC == 0) - { + BOOL MayuIPC_PostMessage(MayuIPCCommand i_command, LPARAM i_lParam) { + static UINT WM_MayuIPC; + HWND hwnd; + + if (WM_MayuIPC == 0) { + WM_MayuIPC = RegisterWindowMessage(WM_MayuIPC_NAME); + if (WM_MayuIPC == 0) { + return FALSE; + } + } + + hwnd = FindWindow(_T("mayuTasktray"), NULL); + if (hwnd == NULL) { return FALSE; } + PostMessage(hwnd, WM_MayuIPC, i_command, i_lParam); + return TRUE; } - - hwnd = FindWindow(_T("mayuTasktray"), NULL); - if (hwnd == NULL) - { - return FALSE; - } - PostMessage(hwnd, WM_MayuIPC, i_command, i_lParam); - return TRUE; -} -BOOL MayuIPC_Enable(BOOL i_isEnabled) -{ - return MayuIPC_PostMessage(MayuIPCCommand_Enable, i_isEnabled); -} + BOOL MayuIPC_Enable(BOOL i_isEnabled) { + return MayuIPC_PostMessage(MayuIPCCommand_Enable, i_isEnabled); + } # endif // _MAYUIPC_H_DEFINE_FUNCTIONS diff --git a/mayurc.h b/mayurc.h old mode 100755 new mode 100644 index e72ed56..85a4e6d --- a/mayurc.h +++ b/mayurc.h @@ -78,7 +78,7 @@ #define IDC_STATIC -1 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 103 diff --git a/msgstream.h b/msgstream.h index 6af8767..749a44f 100644 --- a/msgstream.h +++ b/msgstream.h @@ -18,7 +18,7 @@

Before writing to omsgstream, you must acquire lock by calling acquire(). Then after completion of writing, you must call release().

- +

Omsgbuf calls PostMessage(hwnd, messageid, 0, (LPARAM)omsgbuf) to notify that string is ready to get. When the window (hwnd) get the message, you can get @@ -29,265 +29,241 @@ */ template, class A = std::allocator > +class TR = std::char_traits, class A = std::allocator > class basic_msgbuf : public std::basic_streambuf, public SyncObject { public: - typedef std::basic_string String; /// - typedef std::basic_streambuf Super; /// - + typedef std::basic_string String; /// + typedef std::basic_streambuf Super; /// + private: - HWND m_hwnd; /** window handle for + HWND m_hwnd; /** window handle for notification */ - UINT m_messageId; /// messageid for notification - T *m_buf; /// for streambuf - String m_str; /// for notification - CriticalSection m_cs; /// lock - A m_allocator; /// allocator - - /** debug level. - if ( m_msgDebugLevel <= m_debugLevel ), message is displayed - */ - int m_debugLevel; - int m_msgDebugLevel; /// + UINT m_messageId; /// messageid for notification + T *m_buf; /// for streambuf + String m_str; /// for notification + CriticalSection m_cs; /// lock + A m_allocator; /// allocator + + /** debug level. + if ( m_msgDebugLevel <= m_debugLevel ), message is displayed + */ + int m_debugLevel; + int m_msgDebugLevel; /// private: - basic_msgbuf(const basic_msgbuf &); /// disable copy constructor + basic_msgbuf(const basic_msgbuf &); /// disable copy constructor public: - /// - basic_msgbuf(UINT i_messageId, HWND i_hwnd = 0) - : m_hwnd(i_hwnd), - m_messageId(i_messageId), - m_buf(m_allocator.allocate(SIZE, 0)), - m_debugLevel(0), - m_msgDebugLevel(0) - { - ASSERT(m_buf); - setp(m_buf, m_buf + SIZE); - } - - /// - ~basic_msgbuf() - { - sync(); - m_allocator.deallocate(m_buf, SIZE); - } - - /// attach/detach a window - basic_msgbuf* attach(HWND i_hwnd) - { - Acquire a(&m_cs); - ASSERT( !m_hwnd && i_hwnd ); - m_hwnd = i_hwnd; - if (!m_str.empty()) - PostMessage(m_hwnd, m_messageId, 0, (LPARAM)this); - return this; - } - - /// - basic_msgbuf* detach() - { - Acquire a(&m_cs); - sync(); - m_hwnd = 0; - return this; - } - - /// get window handle - HWND getHwnd() const { return m_hwnd; } - - /// is a window attached ? - int is_open() const { return !!m_hwnd; } - - /// acquire string and release the string - const String &acquireString() - { - m_cs.acquire(); - return m_str; - } - - /// - void releaseString() - { - m_str.resize(0); - m_cs.release(); - } - - /// set debug level - void setDebugLevel(int i_debugLevel) - { - m_debugLevel = i_debugLevel; - } - - /// - int getDebugLevel() const { return m_debugLevel; } - - // for stream - typename Super::int_type overflow(typename Super::int_type i_c = TR::eof()) - { - if (sync() == TR::eof()) // sync before new buffer created below - return TR::eof(); - - if (i_c != TR::eof()) - { - *pptr() = TR::to_char_type(i_c); - pbump(1); - sync(); - } - return TR::not_eof(i_c); // return something other than EOF if successful - } - - // for stream - int sync() - { - T *begin = pbase(); - T *end = pptr(); - T *i; - for (i = begin; i < end; ++ i) - if (_istlead(*i)) - ++ i; - if (i == end) - { - if (m_msgDebugLevel <= m_debugLevel) - m_str += String(begin, end - begin); - setp(m_buf, m_buf + SIZE); - } - else // end < i - { - if (m_msgDebugLevel <= m_debugLevel) - m_str += String(begin, end - begin - 1); - m_buf[0] = end[-1]; - setp(m_buf, m_buf + SIZE); - pbump(1); - } - return TR::not_eof(0); - } - - // sync object - - /// begin writing - virtual void acquire() - { - m_cs.acquire(); - } - - /// begin writing - virtual void acquire(int i_msgDebugLevel) - { - m_cs.acquire(); - m_msgDebugLevel = i_msgDebugLevel; - } - - /// end writing - virtual void release() - { - if (!m_str.empty()) - PostMessage(m_hwnd, m_messageId, 0, reinterpret_cast(this)); - m_msgDebugLevel = m_debugLevel; - m_cs.release(); - } + /// + basic_msgbuf(UINT i_messageId, HWND i_hwnd = 0) + : m_hwnd(i_hwnd), + m_messageId(i_messageId), + m_buf(m_allocator.allocate(SIZE, 0)), + m_debugLevel(0), + m_msgDebugLevel(0) { + ASSERT(m_buf); + setp(m_buf, m_buf + SIZE); + } + + /// + ~basic_msgbuf() { + sync(); + m_allocator.deallocate(m_buf, SIZE); + } + + /// attach/detach a window + basic_msgbuf* attach(HWND i_hwnd) { + Acquire a(&m_cs); + ASSERT( !m_hwnd && i_hwnd ); + m_hwnd = i_hwnd; + if (!m_str.empty()) + PostMessage(m_hwnd, m_messageId, 0, (LPARAM)this); + return this; + } + + /// + basic_msgbuf* detach() { + Acquire a(&m_cs); + sync(); + m_hwnd = 0; + return this; + } + + /// get window handle + HWND getHwnd() const { + return m_hwnd; + } + + /// is a window attached ? + int is_open() const { + return !!m_hwnd; + } + + /// acquire string and release the string + const String &acquireString() { + m_cs.acquire(); + return m_str; + } + + /// + void releaseString() { + m_str.resize(0); + m_cs.release(); + } + + /// set debug level + void setDebugLevel(int i_debugLevel) { + m_debugLevel = i_debugLevel; + } + + /// + int getDebugLevel() const { + return m_debugLevel; + } + + // for stream + typename Super::int_type overflow(typename Super::int_type i_c = TR::eof()) { + if (sync() == TR::eof()) // sync before new buffer created below + return TR::eof(); + + if (i_c != TR::eof()) { + *pptr() = TR::to_char_type(i_c); + pbump(1); + sync(); + } + return TR::not_eof(i_c); // return something other than EOF if successful + } + + // for stream + int sync() { + T *begin = pbase(); + T *end = pptr(); + T *i; + for (i = begin; i < end; ++ i) + if (_istlead(*i)) + ++ i; + if (i == end) { + if (m_msgDebugLevel <= m_debugLevel) + m_str += String(begin, end - begin); + setp(m_buf, m_buf + SIZE); + } else { // end < i + if (m_msgDebugLevel <= m_debugLevel) + m_str += String(begin, end - begin - 1); + m_buf[0] = end[-1]; + setp(m_buf, m_buf + SIZE); + pbump(1); + } + return TR::not_eof(0); + } + + // sync object + + /// begin writing + virtual void acquire() { + m_cs.acquire(); + } + + /// begin writing + virtual void acquire(int i_msgDebugLevel) { + m_cs.acquire(); + m_msgDebugLevel = i_msgDebugLevel; + } + + /// end writing + virtual void release() { + if (!m_str.empty()) + PostMessage(m_hwnd, m_messageId, 0, reinterpret_cast(this)); + m_msgDebugLevel = m_debugLevel; + m_cs.release(); + } }; /// template, class A = std::allocator > +class TR = std::char_traits, class A = std::allocator > class basic_omsgstream : public std::basic_ostream, public SyncObject { public: - typedef std::basic_ostream Super; /// - typedef basic_msgbuf StreamBuf; /// - typedef std::basic_string String; /// - + typedef std::basic_ostream Super; /// + typedef basic_msgbuf StreamBuf; /// + typedef std::basic_string String; /// + private: - StreamBuf m_streamBuf; /// + StreamBuf m_streamBuf; /// public: - /// - explicit basic_omsgstream(UINT i_messageId, HWND i_hwnd = 0) - : Super(&m_streamBuf), m_streamBuf(i_messageId, i_hwnd) - { - } - - /// - virtual ~basic_omsgstream() - { - } - - /// - StreamBuf *rdbuf() const - { - return const_cast(&m_streamBuf); - } - - /// attach a msg control - void attach(HWND i_hwnd) - { - m_streamBuf.attach(i_hwnd); - } - - /// detach a msg control - void detach() - { - m_streamBuf.detach(); - } - - /// get window handle of the msg control - HWND getHwnd() const - { - return m_streamBuf.getHwnd(); - } - - /// is the msg control attached ? - int is_open() const - { - return m_streamBuf.is_open(); - } - - /// set debug level - void setDebugLevel(int i_debugLevel) - { - m_streamBuf.setDebugLevel(i_debugLevel); - } - - /// - int getDebugLevel() const - { - return m_streamBuf.getDebugLevel(); - } - - /// acquire string and release the string - const String &acquireString() - { - return m_streamBuf.acquireString(); - } - - /// - void releaseString() - { - m_streamBuf->releaseString(); - } - - // sync object - - /// begin writing - virtual void acquire() - { - m_streamBuf.acquire(); - } - - /// begin writing - virtual void acquire(int i_msgDebugLevel) - { - m_streamBuf.acquire(i_msgDebugLevel); - } - - /// end writing - virtual void release() - { - m_streamBuf.release(); - } + /// + explicit basic_omsgstream(UINT i_messageId, HWND i_hwnd = 0) + : Super(&m_streamBuf), m_streamBuf(i_messageId, i_hwnd) { + } + + /// + virtual ~basic_omsgstream() { + } + + /// + StreamBuf *rdbuf() const { + return const_cast(&m_streamBuf); + } + + /// attach a msg control + void attach(HWND i_hwnd) { + m_streamBuf.attach(i_hwnd); + } + + /// detach a msg control + void detach() { + m_streamBuf.detach(); + } + + /// get window handle of the msg control + HWND getHwnd() const { + return m_streamBuf.getHwnd(); + } + + /// is the msg control attached ? + int is_open() const { + return m_streamBuf.is_open(); + } + + /// set debug level + void setDebugLevel(int i_debugLevel) { + m_streamBuf.setDebugLevel(i_debugLevel); + } + + /// + int getDebugLevel() const { + return m_streamBuf.getDebugLevel(); + } + + /// acquire string and release the string + const String &acquireString() { + return m_streamBuf.acquireString(); + } + + /// + void releaseString() { + m_streamBuf->releaseString(); + } + + // sync object + + /// begin writing + virtual void acquire() { + m_streamBuf.acquire(); + } + + /// begin writing + virtual void acquire(int i_msgDebugLevel) { + m_streamBuf.acquire(i_msgDebugLevel); + } + + /// end writing + virtual void release() { + m_streamBuf.release(); + } }; /// diff --git a/multithread.h b/multithread.h index ea315c7..038a325 100644 --- a/multithread.h +++ b/multithread.h @@ -12,44 +12,60 @@ class SyncObject { public: - /// - virtual void acquire() = 0; - /// - virtual void acquire(int ) { acquire(); } - /// - virtual void release() = 0; + /// + virtual void acquire() = 0; + /// + virtual void acquire(int ) { + acquire(); + } + /// + virtual void release() = 0; }; /// class CriticalSection : public SyncObject { - CRITICAL_SECTION m_cs; /// + CRITICAL_SECTION m_cs; /// public: - /// - CriticalSection() { InitializeCriticalSection(&m_cs); } - /// - ~CriticalSection() { DeleteCriticalSection(&m_cs); } - /// - void acquire() { EnterCriticalSection(&m_cs); } - /// - void release() { LeaveCriticalSection(&m_cs); } + /// + CriticalSection() { + InitializeCriticalSection(&m_cs); + } + /// + ~CriticalSection() { + DeleteCriticalSection(&m_cs); + } + /// + void acquire() { + EnterCriticalSection(&m_cs); + } + /// + void release() { + LeaveCriticalSection(&m_cs); + } }; /// class Acquire { - SyncObject *m_so; /// - + SyncObject *m_so; /// + public: - /// - Acquire(SyncObject *i_so) : m_so(i_so) { m_so->acquire(); } - /// - Acquire(SyncObject *i_so, int i_n) : m_so(i_so) { m_so->acquire(i_n); } - /// - ~Acquire() { m_so->release(); } + /// + Acquire(SyncObject *i_so) : m_so(i_so) { + m_so->acquire(); + } + /// + Acquire(SyncObject *i_so, int i_n) : m_so(i_so) { + m_so->acquire(i_n); + } + /// + ~Acquire() { + m_so->release(); + } }; diff --git a/parser.cpp b/parser.cpp index 3f129aa..d111896 100644 --- a/parser.cpp +++ b/parser.cpp @@ -14,105 +14,116 @@ Token::Token(const Token &i_token) - : m_type(i_token.m_type), - m_isValueQuoted(i_token.m_isValueQuoted), - m_numericValue(i_token.m_numericValue), - m_stringValue(i_token.m_stringValue), - m_data(i_token.m_data) + : m_type(i_token.m_type), + m_isValueQuoted(i_token.m_isValueQuoted), + m_numericValue(i_token.m_numericValue), + m_stringValue(i_token.m_stringValue), + m_data(i_token.m_data) { } Token::Token(int i_value, const tstringi &i_display) - : m_type(Type_number), - m_isValueQuoted(false), - m_numericValue(i_value), - m_stringValue(i_display), - m_data(NULL) + : m_type(Type_number), + m_isValueQuoted(false), + m_numericValue(i_value), + m_stringValue(i_display), + m_data(NULL) { } Token::Token(const tstringi &i_value, bool i_isValueQuoted, bool i_isRegexp) - : m_type(i_isRegexp ? Type_regexp : Type_string), - m_isValueQuoted(i_isValueQuoted), - m_numericValue(0), - m_stringValue(i_value), - m_data(NULL) + : m_type(i_isRegexp ? Type_regexp : Type_string), + m_isValueQuoted(i_isValueQuoted), + m_numericValue(0), + m_stringValue(i_value), + m_data(NULL) { } Token::Token(Type i_m_type) - : m_type(i_m_type), - m_isValueQuoted(false), - m_numericValue(0), - m_stringValue(_T("")), - m_data(NULL) + : m_type(i_m_type), + m_isValueQuoted(false), + m_numericValue(0), + m_stringValue(_T("")), + m_data(NULL) { - ASSERT(m_type == Type_openParen || m_type == Type_closeParen || - m_type == Type_comma); + ASSERT(m_type == Type_openParen || m_type == Type_closeParen || + m_type == Type_comma); } // get numeric value int Token::getNumber() const { - if (m_type == Type_number) - return m_numericValue; - if (m_stringValue.empty()) - return 0; - else - throw ErrorMessage() << _T("`") << *this << _T("' is not a Type_number."); + if (m_type == Type_number) + return m_numericValue; + if (m_stringValue.empty()) + return 0; + else + throw ErrorMessage() << _T("`") << *this << _T("' is not a Type_number."); } // get string value tstringi Token::getString() const { - if (m_type == Type_string) - return m_stringValue; - throw ErrorMessage() << _T("`") << *this << _T("' is not a string."); + if (m_type == Type_string) + return m_stringValue; + throw ErrorMessage() << _T("`") << *this << _T("' is not a string."); } // get regexp value tstringi Token::getRegexp() const { - if (m_type == Type_regexp) - return m_stringValue; - throw ErrorMessage() << _T("`") << *this << _T("' is not a regexp."); + if (m_type == Type_regexp) + return m_stringValue; + throw ErrorMessage() << _T("`") << *this << _T("' is not a regexp."); } // case insensitive equal bool Token::operator==(const _TCHAR *i_str) const { - if (m_type == Type_string) - return m_stringValue == i_str; - return false; + if (m_type == Type_string) + return m_stringValue == i_str; + return false; } // paren equal bool Token::operator==(const _TCHAR i_c) const { - if (i_c == _T('(')) return m_type == Type_openParen; - if (i_c == _T(')')) return m_type == Type_openParen; - return false; + if (i_c == _T('(')) return m_type == Type_openParen; + if (i_c == _T(')')) return m_type == Type_openParen; + return false; } // add string void Token::add(const tstringi &i_str) { - m_stringValue += i_str; + m_stringValue += i_str; } // stream output tostream &operator<<(tostream &i_ost, const Token &i_token) { - switch (i_token.m_type) - { - case Token::Type_string: i_ost << i_token.m_stringValue; break; - case Token::Type_number: i_ost << i_token.m_stringValue; break; - case Token::Type_regexp: i_ost << i_token.m_stringValue; break; - case Token::Type_openParen: i_ost << _T("("); break; - case Token::Type_closeParen: i_ost << _T(")"); break; - case Token::Type_comma: i_ost << _T(", "); break; - } - return i_ost; + switch (i_token.m_type) { + case Token::Type_string: + i_ost << i_token.m_stringValue; + break; + case Token::Type_number: + i_ost << i_token.m_stringValue; + break; + case Token::Type_regexp: + i_ost << i_token.m_stringValue; + break; + case Token::Type_openParen: + i_ost << _T("("); + break; + case Token::Type_closeParen: + i_ost << _T(")"); + break; + case Token::Type_comma: + i_ost << _T(", "); + break; + } + return i_ost; } @@ -121,11 +132,11 @@ tostream &operator<<(tostream &i_ost, const Token &i_token) Parser::Parser(const _TCHAR *i_str, size_t i_length) - : m_lineNumber(1), - m_prefixes(NULL), - m_internalLineNumber(1), - m_ptr(i_str), - m_end(i_str + i_length) + : m_lineNumber(1), + m_prefixes(NULL), + m_internalLineNumber(1), + m_ptr(i_str), + m_end(i_str + i_length) { } @@ -133,77 +144,75 @@ Parser::Parser(const _TCHAR *i_str, size_t i_length) // prefix_ is not copied, so it must be preserved after setPrefix() void Parser::setPrefixes(const Prefixes *i_prefixes) { - m_prefixes = i_prefixes; + m_prefixes = i_prefixes; } // get a line bool Parser::getLine(tstringi *o_line) { - o_line->resize(0); - - if (m_ptr == m_end) - return false; - - const _TCHAR *begin = m_ptr; - const _TCHAR *end = m_end; - - // lines are separated by: "\r\n", "\n", "\x2028" (Unicode Line Separator) - while (m_ptr != m_end) - switch (*m_ptr) - { - case _T('\n'): + o_line->resize(0); + + if (m_ptr == m_end) + return false; + + const _TCHAR *begin = m_ptr; + const _TCHAR *end = m_end; + + // lines are separated by: "\r\n", "\n", "\x2028" (Unicode Line Separator) + while (m_ptr != m_end) + switch (*m_ptr) { + case _T('\n'): #ifdef UNICODE - case 0x2028: - //case _T('\x2028'): // (U+2028) + case 0x2028: + //case _T('\x2028'): // (U+2028) #endif - end = m_ptr; - ++ m_ptr; - goto got_line_end; - case _T('\r'): - if (m_ptr + 1 != m_end && m_ptr[1] == _T('\n')) - { - end = m_ptr; - m_ptr += 2; - goto got_line_end; - } - // fall through - default: - ++ m_ptr; - break; - } - got_line_end: - ++ m_internalLineNumber; - // o_line->assign(begin, end); // why bcc cannot link this ? - o_line->assign(begin, end - begin); // workarond for bcc - return true; + end = m_ptr; + ++ m_ptr; + goto got_line_end; + case _T('\r'): + if (m_ptr + 1 != m_end && m_ptr[1] == _T('\n')) { + end = m_ptr; + m_ptr += 2; + goto got_line_end; + } + // fall through + default: + ++ m_ptr; + break; + } +got_line_end: + ++ m_internalLineNumber; + // o_line->assign(begin, end); // why bcc cannot link this ? + o_line->assign(begin, end - begin); // workarond for bcc + return true; } // symbol test static bool isSymbolChar(_TCHAR i_c) { - if (i_c == _T('\0')) - return false; - if (_istlead(i_c) || - _istalpha(i_c) || - _istdigit(i_c) || - _istlead(i_c)) - return true; + if (i_c == _T('\0')) + return false; + if (_istlead(i_c) || + _istalpha(i_c) || + _istdigit(i_c) || + _istlead(i_c)) + return true; #ifdef UNICODE - if (0x80 <= i_c && _istgraph(i_c)) - return true; + if (0x80 <= i_c && _istgraph(i_c)) + return true; #endif // UNICODE - if (_istpunct(i_c)) - return !!_tcschr(_T("-+/?_\\"), i_c); + if (_istpunct(i_c)) + return !!_tcschr(_T("-+/?_\\"), i_c); #ifdef UNICODE - // check arrows - if (_tcschr(_T("\x2190\x2191\x2192\x2193"), i_c)) { - return true; - } + // check arrows + if (_tcschr(_T("\x2190\x2191\x2192\x2193"), i_c)) { + return true; + } #endif // UNICODE - return _istgraph(i_c); + return _istgraph(i_c); } @@ -211,166 +220,152 @@ static bool isSymbolChar(_TCHAR i_c) // if no more lines exist, returns false bool Parser::getLine(std::vector *o_tokens) { - o_tokens->clear(); - m_lineNumber = m_internalLineNumber; - - tstringi line; - bool isTokenExist = false; - continue_getLineLoop: - while (getLine(&line)) - { - const _TCHAR *t = line.c_str(); - - continue_getTokenLoop: - while (true) - { - // skip white space - while (*t != _T('\0') && _istspace(*t)) - t ++; - if (*t == _T('\0') || *t == _T('#')) - goto break_getTokenLoop; // no more tokens exist - if (*t == _T('\\') && *(t + 1) == _T('\0')) - goto continue_getLineLoop; // continue to next line - - const _TCHAR *tokenStart = t; - - // comma or empty token - if (*t == _T(',')) - { - if (!isTokenExist) - o_tokens->push_back(Token(_T(""), false)); - isTokenExist = false; - o_tokens->push_back(Token(Token::Type_comma)); - t ++; - goto continue_getTokenLoop; - } - - // paren - if (*t == _T('(')) - { - o_tokens->push_back(Token(Token::Type_openParen)); - isTokenExist = false; - t ++; - goto continue_getTokenLoop; - } - if (*t == _T(')')) - { - if (!isTokenExist) - o_tokens->push_back(Token(_T(""), false)); - isTokenExist = true; - o_tokens->push_back(Token(Token::Type_closeParen)); - t ++; - goto continue_getTokenLoop; - } - - isTokenExist = true; - - // prefix - if (m_prefixes) - for (size_t i = 0; i < m_prefixes->size(); i ++) - if (_tcsnicmp(tokenStart, m_prefixes->at(i).c_str(), - m_prefixes->at(i).size()) == 0) - { - o_tokens->push_back(Token(m_prefixes->at(i), false)); - t += m_prefixes->at(i).size(); - goto continue_getTokenLoop; - } - - // quoted or regexp - if (*t == _T('"') || *t == _T('\'') || - *t == _T('/') || (*t == _T('\\') && *(t + 1) == _T('m') && - *(t + 2) != _T('\0'))) - { - bool isRegexp = !(*t == _T('"') || *t == _T('\'')); - _TCHAR q[2] = { *t++, _T('\0') }; // quote character - if (q[0] == _T('\\')) - { - t++; - q[0] = *t++; - } - tokenStart = t; - - while (*t != _T('\0') && *t != q[0]) - { - if (*t == _T('\\') && *(t + 1)) - t ++; - if (_istlead(*t) && *(t + 1)) - t ++; - t ++; - } - - tstring str = - interpretMetaCharacters(tokenStart, t - tokenStart, q, isRegexp); + o_tokens->clear(); + m_lineNumber = m_internalLineNumber; + + tstringi line; + bool isTokenExist = false; +continue_getLineLoop: + while (getLine(&line)) { + const _TCHAR *t = line.c_str(); + +continue_getTokenLoop: + while (true) { + // skip white space + while (*t != _T('\0') && _istspace(*t)) + t ++; + if (*t == _T('\0') || *t == _T('#')) + goto break_getTokenLoop; // no more tokens exist + if (*t == _T('\\') && *(t + 1) == _T('\0')) + goto continue_getLineLoop; // continue to next line + + const _TCHAR *tokenStart = t; + + // comma or empty token + if (*t == _T(',')) { + if (!isTokenExist) + o_tokens->push_back(Token(_T(""), false)); + isTokenExist = false; + o_tokens->push_back(Token(Token::Type_comma)); + t ++; + goto continue_getTokenLoop; + } + + // paren + if (*t == _T('(')) { + o_tokens->push_back(Token(Token::Type_openParen)); + isTokenExist = false; + t ++; + goto continue_getTokenLoop; + } + if (*t == _T(')')) { + if (!isTokenExist) + o_tokens->push_back(Token(_T(""), false)); + isTokenExist = true; + o_tokens->push_back(Token(Token::Type_closeParen)); + t ++; + goto continue_getTokenLoop; + } + + isTokenExist = true; + + // prefix + if (m_prefixes) + for (size_t i = 0; i < m_prefixes->size(); i ++) + if (_tcsnicmp(tokenStart, m_prefixes->at(i).c_str(), + m_prefixes->at(i).size()) == 0) { + o_tokens->push_back(Token(m_prefixes->at(i), false)); + t += m_prefixes->at(i).size(); + goto continue_getTokenLoop; + } + + // quoted or regexp + if (*t == _T('"') || *t == _T('\'') || + *t == _T('/') || (*t == _T('\\') && *(t + 1) == _T('m') && + *(t + 2) != _T('\0'))) { + bool isRegexp = !(*t == _T('"') || *t == _T('\'')); + _TCHAR q[2] = { *t++, _T('\0') }; // quote character + if (q[0] == _T('\\')) { + t++; + q[0] = *t++; + } + tokenStart = t; + + while (*t != _T('\0') && *t != q[0]) { + if (*t == _T('\\') && *(t + 1)) + t ++; + if (_istlead(*t) && *(t + 1)) + t ++; + t ++; + } + + tstring str = + interpretMetaCharacters(tokenStart, t - tokenStart, q, isRegexp); #ifdef _MBCS - if (isRegexp) - str = guardRegexpFromMbcs(str.c_str()); + if (isRegexp) + str = guardRegexpFromMbcs(str.c_str()); #endif - // concatinate continuous string - if (!isRegexp && - 0 < o_tokens->size() && o_tokens->back().isString() && - o_tokens->back().isQuoted()) - o_tokens->back().add(str); - else - o_tokens->push_back(Token(str, true, isRegexp)); - if (*t != _T('\0')) - t ++; - goto continue_getTokenLoop; - } - - // not quoted - { - while (isSymbolChar(*t)) - { - if (*t == _T('\\')) - if (*(t + 1)) - t ++; - else - break; - if (_istlead(*t) && *(t + 1)) - t ++; - t ++; - } - if (t == tokenStart) - { - ErrorMessage e; - e << _T("invalid character "); + // concatinate continuous string + if (!isRegexp && + 0 < o_tokens->size() && o_tokens->back().isString() && + o_tokens->back().isQuoted()) + o_tokens->back().add(str); + else + o_tokens->push_back(Token(str, true, isRegexp)); + if (*t != _T('\0')) + t ++; + goto continue_getTokenLoop; + } + + // not quoted + { + while (isSymbolChar(*t)) { + if (*t == _T('\\')) + if (*(t + 1)) + t ++; + else + break; + if (_istlead(*t) && *(t + 1)) + t ++; + t ++; + } + if (t == tokenStart) { + ErrorMessage e; + e << _T("invalid character "); #ifdef UNICODE - e << _T("U+"); - e << std::hex; // << std::setw(4) << std::setfill(_T('0')); - e << (int)(wchar_t)*t; + e << _T("U+"); + e << std::hex; // << std::setw(4) << std::setfill(_T('0')); + e << (int)(wchar_t)*t; #else - e << _T("\\x"); - e << std::hex; // << std::setw(2) << std::setfill(_T('0')); - e << (int)(u_char)*t; + e << _T("\\x"); + e << std::hex; // << std::setw(2) << std::setfill(_T('0')); + e << (int)(u_char)*t; #endif - e << std::dec; - if (_istprint(*t)) - e << _T("(") << *t << _T(")"); - throw e; - } - - _TCHAR *numEnd = NULL; - long value = _tcstol(tokenStart, &numEnd, 0); - if (tokenStart == numEnd) - { - tstring str = interpretMetaCharacters(tokenStart, t - tokenStart); - o_tokens->push_back(Token(str, false)); + e << std::dec; + if (_istprint(*t)) + e << _T("(") << *t << _T(")"); + throw e; + } + + _TCHAR *numEnd = NULL; + long value = _tcstol(tokenStart, &numEnd, 0); + if (tokenStart == numEnd) { + tstring str = interpretMetaCharacters(tokenStart, t - tokenStart); + o_tokens->push_back(Token(str, false)); + } else { + o_tokens->push_back( + Token(value, tstringi(tokenStart, numEnd - tokenStart))); + t = numEnd; + } + goto continue_getTokenLoop; + } + } +break_getTokenLoop: + if (0 < o_tokens->size()) + break; + m_lineNumber = m_internalLineNumber; + isTokenExist = false; } - else - { - o_tokens->push_back( - Token(value, tstringi(tokenStart, numEnd - tokenStart))); - t = numEnd; - } - goto continue_getTokenLoop; - } - } - break_getTokenLoop: - if (0 < o_tokens->size()) - break; - m_lineNumber = m_internalLineNumber; - isTokenExist = false; - } - - return 0 < o_tokens->size(); + + return 0 < o_tokens->size(); } diff --git a/parser.h b/parser.h index b71eabd..d71ff0a 100644 --- a/parser.h +++ b/parser.h @@ -14,90 +14,115 @@ class Token { public: - /// - enum Type - { - Type_string, /// - Type_number, /// - Type_regexp, /// - Type_openParen, /// - Type_closeParen, /// - Type_comma, /// - }; - + /// + enum Type { + Type_string, /// + Type_number, /// + Type_regexp, /// + Type_openParen, /// + Type_closeParen, /// + Type_comma, /// + }; + private: - u_char m_type; /// - bool m_isValueQuoted; /// - int m_numericValue; /// - tstringi m_stringValue; /// - long m_data; /// - + u_char m_type; /// + bool m_isValueQuoted; /// + int m_numericValue; /// + tstringi m_stringValue; /// + long m_data; /// + public: - /// - Token(const Token &i_token); - /// - Token(int i_value, const tstringi &i_display); - /// - Token(const tstringi &i_value, bool i_isValueQuoted, - bool i_isRegexp = false); - /// - Token(Type i_type); - - /// is the value quoted ? - bool isQuoted() const { return m_isValueQuoted; } - - /// value type - Type getType() const { return static_cast(m_type); } - /// - bool isString() const { return m_type == Type_string; } - /// - bool isNumber() const { return m_type == Type_number; } - /// - bool isRegexp() const { return m_type == Type_regexp; } - /// - bool isOpenParen() const { return m_type == Type_openParen; } - /// - bool isCloseParen() const { return m_type == Type_closeParen; } - /// - bool isComma() const { return m_type == Type_comma; } - - /// get numeric value - int getNumber() const; - - /// get string value - tstringi getString() const; - - /// get regexp value - tstringi getRegexp() const; - - /// get data - long getData() const { return m_data; } - /// - void setData(long i_data) { m_data = i_data; } - - /// case insensitive equal - bool operator==(const tstringi &i_str) const - { return *this == i_str.c_str(); } - /// - bool operator==(const _TCHAR *i_str) const; - /// - bool operator!=(const tstringi &i_str) const - { return *this != i_str.c_str(); } - /// - bool operator!=(const _TCHAR *i_str) const { return !(*this == i_str); } - - /** paren equal - @param i_c '(' or ')' */ - bool operator==(const _TCHAR i_c) const; - /** paren equal - @param i_c '(' or ')' */ - bool operator!=(const _TCHAR i_c) const { return !(*this == i_c); } - - /// add string - void add(const tstringi &i_str); - - /// stream output - friend tostream &operator<<(tostream &i_ost, const Token &i_token); + /// + Token(const Token &i_token); + /// + Token(int i_value, const tstringi &i_display); + /// + Token(const tstringi &i_value, bool i_isValueQuoted, + bool i_isRegexp = false); + /// + Token(Type i_type); + + /// is the value quoted ? + bool isQuoted() const { + return m_isValueQuoted; + } + + /// value type + Type getType() const { + return static_cast(m_type); + } + /// + bool isString() const { + return m_type == Type_string; + } + /// + bool isNumber() const { + return m_type == Type_number; + } + /// + bool isRegexp() const { + return m_type == Type_regexp; + } + /// + bool isOpenParen() const { + return m_type == Type_openParen; + } + /// + bool isCloseParen() const { + return m_type == Type_closeParen; + } + /// + bool isComma() const { + return m_type == Type_comma; + } + + /// get numeric value + int getNumber() const; + + /// get string value + tstringi getString() const; + + /// get regexp value + tstringi getRegexp() const; + + /// get data + long getData() const { + return m_data; + } + /// + void setData(long i_data) { + m_data = i_data; + } + + /// case insensitive equal + bool operator==(const tstringi &i_str) const { + return *this == i_str.c_str(); + } + /// + bool operator==(const _TCHAR *i_str) const; + /// + bool operator!=(const tstringi &i_str) const { + return *this != i_str.c_str(); + } + /// + bool operator!=(const _TCHAR *i_str) const { + return !(*this == i_str); + } + + /** paren equal + @param i_c '(' or ')' */ + bool operator==(const _TCHAR i_c) const; + /** paren equal + @param i_c '(' or ')' */ + bool operator!=(const _TCHAR i_c) const { + return !(*this == i_c); + } + + /// add string + void add(const tstringi &i_str); + + /// stream output + friend tostream &operator<<(tostream &i_ost, const Token &i_token); }; @@ -105,39 +130,41 @@ public: class Parser { public: - /// - typedef std::vector Tokens; - + /// + typedef std::vector Tokens; + private: - /// - typedef std::vector Prefixes; - + /// + typedef std::vector Prefixes; + private: - size_t m_lineNumber; /// current line number - const Prefixes *m_prefixes; /** string that may be prefix + size_t m_lineNumber; /// current line number + const Prefixes *m_prefixes; /** string that may be prefix of a token */ - - size_t m_internalLineNumber; /// next line number - const _TCHAR *m_ptr; /// read pointer - const _TCHAR *m_end; /// end pointer + + size_t m_internalLineNumber; /// next line number + const _TCHAR *m_ptr; /// read pointer + const _TCHAR *m_end; /// end pointer private: - /// get a line - bool getLine(tstringi *o_line); - + /// get a line + bool getLine(tstringi *o_line); + public: - /// - Parser(const _TCHAR *i_str, size_t i_length); - - /** get a parsed line. if no more lines exist, returns false */ - bool getLine(Tokens *o_tokens); - - /// get current line number - size_t getLineNumber() const { return m_lineNumber; } - - /** set string that may be prefix of a token. prefix_ is not - copied, so it must be preserved after setPrefix() */ - void setPrefixes(const Prefixes *m_prefixes); + /// + Parser(const _TCHAR *i_str, size_t i_length); + + /** get a parsed line. if no more lines exist, returns false */ + bool getLine(Tokens *o_tokens); + + /// get current line number + size_t getLineNumber() const { + return m_lineNumber; + } + + /** set string that may be prefix of a token. prefix_ is not + copied, so it must be preserved after setPrefix() */ + void setPrefixes(const Prefixes *m_prefixes); }; diff --git a/registry.cpp b/registry.cpp index 70e2a7a..167d92d 100644 --- a/registry.cpp +++ b/registry.cpp @@ -10,23 +10,23 @@ // remove bool Registry::remove(HKEY i_root, const tstring &i_path, - const tstring &i_name) + const tstring &i_name) { #ifdef USE_INI - return false; - if (i_name.empty()) - return false; - return WritePrivateProfileString(_T("yamy"), i_name.c_str(), NULL, i_path.c_str()) == TRUE; + return false; + if (i_name.empty()) + return false; + return WritePrivateProfileString(_T("yamy"), i_name.c_str(), NULL, i_path.c_str()) == TRUE; #else // !USE_INI - if (i_name.empty()) - return RegDeleteKey(i_root, i_path.c_str()) == ERROR_SUCCESS; - HKEY hkey; - if (ERROR_SUCCESS != - RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_SET_VALUE, &hkey)) - return false; - LONG r = RegDeleteValue(hkey, i_name.c_str()); - RegCloseKey(hkey); - return r == ERROR_SUCCESS; + if (i_name.empty()) + return RegDeleteKey(i_root, i_path.c_str()) == ERROR_SUCCESS; + HKEY hkey; + if (ERROR_SUCCESS != + RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_SET_VALUE, &hkey)) + return false; + LONG r = RegDeleteValue(hkey, i_name.c_str()); + RegCloseKey(hkey); + return r == ERROR_SUCCESS; #endif // !USE_INI } @@ -35,146 +35,140 @@ bool Registry::remove(HKEY i_root, const tstring &i_path, bool Registry::doesExist(HKEY i_root, const tstring &i_path) { #ifdef USE_INI - return true; + return true; #else // !USE_INI - HKEY hkey; - if (ERROR_SUCCESS != - RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) - return false; - RegCloseKey(hkey); - return true; + HKEY hkey; + if (ERROR_SUCCESS != + RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) + return false; + RegCloseKey(hkey); + return true; #endif // !USE_INI } // read DWORD bool Registry::read(HKEY i_root, const tstring &i_path, - const tstring &i_name, int *o_value, int i_defaultValue) + const tstring &i_name, int *o_value, int i_defaultValue) { #ifdef USE_INI - *o_value = - GetPrivateProfileInt(_T("yamy"), i_name.c_str(), i_defaultValue, i_path.c_str()); - return true; + *o_value = + GetPrivateProfileInt(_T("yamy"), i_name.c_str(), i_defaultValue, i_path.c_str()); + return true; #else // !USE_INI - HKEY hkey; - if (ERROR_SUCCESS == - RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) - { - DWORD type = REG_DWORD; - DWORD size = sizeof(*o_value); - LONG r = RegQueryValueEx(hkey, i_name.c_str(), NULL, - &type, (BYTE *)o_value, &size); - RegCloseKey(hkey); - if (r == ERROR_SUCCESS) - return true; - } - *o_value = i_defaultValue; - return false; + HKEY hkey; + if (ERROR_SUCCESS == + RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) { + DWORD type = REG_DWORD; + DWORD size = sizeof(*o_value); + LONG r = RegQueryValueEx(hkey, i_name.c_str(), NULL, + &type, (BYTE *)o_value, &size); + RegCloseKey(hkey); + if (r == ERROR_SUCCESS) + return true; + } + *o_value = i_defaultValue; + return false; #endif // !USE_INI } // write DWORD bool Registry::write(HKEY i_root, const tstring &i_path, const tstring &i_name, - int i_value) + int i_value) { #ifdef USE_INI - DWORD ret; - _TCHAR buf[GANA_MAX_PATH]; + DWORD ret; + _TCHAR buf[GANA_MAX_PATH]; - _stprintf(buf, _T("%d"), i_value); - ret = WritePrivateProfileString(_T("yamy"), i_name.c_str(), - buf, i_path.c_str()); - return ret != 0; + _stprintf(buf, _T("%d"), i_value); + ret = WritePrivateProfileString(_T("yamy"), i_name.c_str(), + buf, i_path.c_str()); + return ret != 0; #else // !USE_INI - HKEY hkey; - DWORD disposition; - if (ERROR_SUCCESS != - RegCreateKeyEx(i_root, i_path.c_str(), 0, _T(""), - REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, NULL, &hkey, &disposition)) - return false; - LONG r = RegSetValueEx(hkey, i_name.c_str(), NULL, REG_DWORD, - (BYTE *)&i_value, sizeof(i_value)); - RegCloseKey(hkey); - return r == ERROR_SUCCESS; + HKEY hkey; + DWORD disposition; + if (ERROR_SUCCESS != + RegCreateKeyEx(i_root, i_path.c_str(), 0, _T(""), + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, NULL, &hkey, &disposition)) + return false; + LONG r = RegSetValueEx(hkey, i_name.c_str(), NULL, REG_DWORD, + (BYTE *)&i_value, sizeof(i_value)); + RegCloseKey(hkey); + return r == ERROR_SUCCESS; #endif // !USE_INI } // read string bool Registry::read(HKEY i_root, const tstring &i_path, const tstring &i_name, - tstring *o_value, const tstring &i_defaultValue) + tstring *o_value, const tstring &i_defaultValue) { #ifdef USE_INI - _TCHAR buf[GANA_MAX_PATH]; - DWORD len; - len = GetPrivateProfileString(_T("yamy"), i_name.c_str(), _T(""), - buf, sizeof(buf) / sizeof(buf[0]), i_path.c_str()); - if (len > 0) - { - *o_value = buf; - return true; - } - if (!i_defaultValue.empty()) - *o_value = i_defaultValue; - return false; + _TCHAR buf[GANA_MAX_PATH]; + DWORD len; + len = GetPrivateProfileString(_T("yamy"), i_name.c_str(), _T(""), + buf, sizeof(buf) / sizeof(buf[0]), i_path.c_str()); + if (len > 0) { + *o_value = buf; + return true; + } + if (!i_defaultValue.empty()) + *o_value = i_defaultValue; + return false; #else // !USE_INI - HKEY hkey; - if (ERROR_SUCCESS == - RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) - { - DWORD type = REG_SZ; - DWORD size = 0; - BYTE dummy; - if (ERROR_MORE_DATA == - RegQueryValueEx(hkey, i_name.c_str(), NULL, &type, &dummy, &size)) - { - if (0 < size) - { - Array buf(size); - if (ERROR_SUCCESS == RegQueryValueEx(hkey, i_name.c_str(), - NULL, &type, buf.get(), &size)) - { - buf.back() = 0; - *o_value = reinterpret_cast<_TCHAR *>(buf.get()); - RegCloseKey(hkey); - return true; + HKEY hkey; + if (ERROR_SUCCESS == + RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) { + DWORD type = REG_SZ; + DWORD size = 0; + BYTE dummy; + if (ERROR_MORE_DATA == + RegQueryValueEx(hkey, i_name.c_str(), NULL, &type, &dummy, &size)) { + if (0 < size) { + Array buf(size); + if (ERROR_SUCCESS == RegQueryValueEx(hkey, i_name.c_str(), + NULL, &type, buf.get(), &size)) { + buf.back() = 0; + *o_value = reinterpret_cast<_TCHAR *>(buf.get()); + RegCloseKey(hkey); + return true; + } + } + } + RegCloseKey(hkey); } - } - } - RegCloseKey(hkey); - } - if (!i_defaultValue.empty()) - *o_value = i_defaultValue; - return false; + if (!i_defaultValue.empty()) + *o_value = i_defaultValue; + return false; #endif // !USE_INI } // write string bool Registry::write(HKEY i_root, const tstring &i_path, - const tstring &i_name, const tstring &i_value) + const tstring &i_name, const tstring &i_value) { #ifdef USE_INI - DWORD ret; + DWORD ret; - ret = WritePrivateProfileString(_T("yamy"), i_name.c_str(), - i_value.c_str(), i_path.c_str()); - return ret != 0; + ret = WritePrivateProfileString(_T("yamy"), i_name.c_str(), + i_value.c_str(), i_path.c_str()); + return ret != 0; #else // !USE_INI - HKEY hkey; - DWORD disposition; - if (ERROR_SUCCESS != - RegCreateKeyEx(i_root, i_path.c_str(), 0, _T(""), - REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, NULL, &hkey, &disposition)) - return false; - RegSetValueEx(hkey, i_name.c_str(), NULL, REG_SZ, - (BYTE *)i_value.c_str(), - (i_value.size() + 1) * sizeof(tstring::value_type)); - RegCloseKey(hkey); - return true; + HKEY hkey; + DWORD disposition; + if (ERROR_SUCCESS != + RegCreateKeyEx(i_root, i_path.c_str(), 0, _T(""), + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, NULL, &hkey, &disposition)) + return false; + RegSetValueEx(hkey, i_name.c_str(), NULL, REG_SZ, + (BYTE *)i_value.c_str(), + (i_value.size() + 1) * sizeof(tstring::value_type)); + RegCloseKey(hkey); + return true; #endif // !USE_INI } @@ -182,113 +176,105 @@ bool Registry::write(HKEY i_root, const tstring &i_path, #ifndef USE_INI // read list of string bool Registry::read(HKEY i_root, const tstring &i_path, const tstring &i_name, - tstrings *o_value, const tstrings &i_defaultValue) + tstrings *o_value, const tstrings &i_defaultValue) { - HKEY hkey; - if (ERROR_SUCCESS == - RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) - { - DWORD type = REG_MULTI_SZ; - DWORD size = 0; - BYTE dummy; - if (ERROR_MORE_DATA == - RegQueryValueEx(hkey, i_name.c_str(), NULL, &type, &dummy, &size)) - { - if (0 < size) - { - Array buf(size); - if (ERROR_SUCCESS == RegQueryValueEx(hkey, i_name.c_str(), - NULL, &type, buf.get(), &size)) - { - buf.back() = 0; - o_value->clear(); - const _TCHAR *p = reinterpret_cast<_TCHAR *>(buf.get()); - const _TCHAR *end = reinterpret_cast<_TCHAR *>(buf.end()); - while (p < end && *p) - { - o_value->push_back(p); - p += o_value->back().length() + 1; - } - RegCloseKey(hkey); - return true; + HKEY hkey; + if (ERROR_SUCCESS == + RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) { + DWORD type = REG_MULTI_SZ; + DWORD size = 0; + BYTE dummy; + if (ERROR_MORE_DATA == + RegQueryValueEx(hkey, i_name.c_str(), NULL, &type, &dummy, &size)) { + if (0 < size) { + Array buf(size); + if (ERROR_SUCCESS == RegQueryValueEx(hkey, i_name.c_str(), + NULL, &type, buf.get(), &size)) { + buf.back() = 0; + o_value->clear(); + const _TCHAR *p = reinterpret_cast<_TCHAR *>(buf.get()); + const _TCHAR *end = reinterpret_cast<_TCHAR *>(buf.end()); + while (p < end && *p) { + o_value->push_back(p); + p += o_value->back().length() + 1; + } + RegCloseKey(hkey); + return true; + } + } + } + RegCloseKey(hkey); } - } - } - RegCloseKey(hkey); - } - if (!i_defaultValue.empty()) - *o_value = i_defaultValue; - return false; + if (!i_defaultValue.empty()) + *o_value = i_defaultValue; + return false; } // write list of string bool Registry::write(HKEY i_root, const tstring &i_path, - const tstring &i_name, const tstrings &i_value) + const tstring &i_name, const tstrings &i_value) { - HKEY hkey; - DWORD disposition; - if (ERROR_SUCCESS != - RegCreateKeyEx(i_root, i_path.c_str(), 0, _T(""), - REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, NULL, &hkey, &disposition)) - return false; - tstring value; - for (tstrings::const_iterator i = i_value.begin(); i != i_value.end(); ++ i) - { - value += *i; - value += _T('\0'); - } - RegSetValueEx(hkey, i_name.c_str(), NULL, REG_MULTI_SZ, - (BYTE *)value.c_str(), - (value.size() + 1) * sizeof(tstring::value_type)); - RegCloseKey(hkey); - return true; + HKEY hkey; + DWORD disposition; + if (ERROR_SUCCESS != + RegCreateKeyEx(i_root, i_path.c_str(), 0, _T(""), + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, NULL, &hkey, &disposition)) + return false; + tstring value; + for (tstrings::const_iterator i = i_value.begin(); i != i_value.end(); ++ i) { + value += *i; + value += _T('\0'); + } + RegSetValueEx(hkey, i_name.c_str(), NULL, REG_MULTI_SZ, + (BYTE *)value.c_str(), + (value.size() + 1) * sizeof(tstring::value_type)); + RegCloseKey(hkey); + return true; } // read binary bool Registry::read(HKEY i_root, const tstring &i_path, - const tstring &i_name, BYTE *o_value, DWORD i_valueSize, - const BYTE *i_defaultValue, DWORD i_defaultValueSize) + const tstring &i_name, BYTE *o_value, DWORD i_valueSize, + const BYTE *i_defaultValue, DWORD i_defaultValueSize) { - if (o_value && 0 < i_valueSize) - { - HKEY hkey; - if (ERROR_SUCCESS == - RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) - { - DWORD type = REG_BINARY; - LONG r = RegQueryValueEx(hkey, i_name.c_str(), NULL, &type, - (BYTE *)o_value, &i_valueSize); - RegCloseKey(hkey); - if (r == ERROR_SUCCESS) - return true; - } - } - if (i_defaultValue) - CopyMemory(o_value, i_defaultValue, - MIN(i_defaultValueSize, i_valueSize)); - return false; + if (o_value && 0 < i_valueSize) { + HKEY hkey; + if (ERROR_SUCCESS == + RegOpenKeyEx(i_root, i_path.c_str(), 0, KEY_READ, &hkey)) { + DWORD type = REG_BINARY; + LONG r = RegQueryValueEx(hkey, i_name.c_str(), NULL, &type, + (BYTE *)o_value, &i_valueSize); + RegCloseKey(hkey); + if (r == ERROR_SUCCESS) + return true; + } + } + if (i_defaultValue) + CopyMemory(o_value, i_defaultValue, + MIN(i_defaultValueSize, i_valueSize)); + return false; } // write binary bool Registry::write(HKEY i_root, const tstring &i_path, const tstring &i_name, - const BYTE *i_value, DWORD i_valueSize) + const BYTE *i_value, DWORD i_valueSize) { - if (!i_value) - return false; - HKEY hkey; - DWORD disposition; - if (ERROR_SUCCESS != - RegCreateKeyEx(i_root, i_path.c_str(), 0, _T(""), - REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, NULL, &hkey, &disposition)) - return false; - RegSetValueEx(hkey, i_name.c_str(), NULL, REG_BINARY, i_value, i_valueSize); - RegCloseKey(hkey); - return true; + if (!i_value) + return false; + HKEY hkey; + DWORD disposition; + if (ERROR_SUCCESS != + RegCreateKeyEx(i_root, i_path.c_str(), 0, _T(""), + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, NULL, &hkey, &disposition)) + return false; + RegSetValueEx(hkey, i_name.c_str(), NULL, REG_BINARY, i_value, i_valueSize); + RegCloseKey(hkey); + return true; } #endif //!USE_INI @@ -296,59 +282,58 @@ bool Registry::write(HKEY i_root, const tstring &i_path, const tstring &i_name, // static bool string2logfont(LOGFONT *o_lf, const tstring &i_strlf) { - // -13,0,0,0,400,0,0,0,128,1,2,1,1,Terminal - tregex lf(_T("^(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+),") - _T("(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+),") - _T("(-?\\d+),(-?\\d+),(-?\\d+),(.+)$")); - tsmatch what; + // -13,0,0,0,400,0,0,0,128,1,2,1,1,Terminal + tregex lf(_T("^(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+),") + _T("(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+),(-?\\d+),") + _T("(-?\\d+),(-?\\d+),(-?\\d+),(.+)$")); + tsmatch what; - if (!boost::regex_match(i_strlf, what, lf)) - return false; - o_lf->lfHeight = _ttoi(what.str(1).c_str()); - o_lf->lfWidth = _ttoi(what.str(2).c_str()); - o_lf->lfEscapement = _ttoi(what.str(3).c_str()); - o_lf->lfOrientation = _ttoi(what.str(4).c_str()); - o_lf->lfWeight = _ttoi(what.str(5).c_str()); - o_lf->lfItalic = (BYTE)_ttoi(what.str(6).c_str()); - o_lf->lfUnderline = (BYTE)_ttoi(what.str(7).c_str()); - o_lf->lfStrikeOut = (BYTE)_ttoi(what.str(8).c_str()); - o_lf->lfCharSet = (BYTE)_ttoi(what.str(9).c_str()); - o_lf->lfOutPrecision = (BYTE)_ttoi(what.str(10).c_str()); - o_lf->lfClipPrecision = (BYTE)_ttoi(what.str(11).c_str()); - o_lf->lfQuality = (BYTE)_ttoi(what.str(12).c_str()); - o_lf->lfPitchAndFamily = (BYTE)_ttoi(what.str(13).c_str()); - tcslcpy(o_lf->lfFaceName, what.str(14).c_str(), NUMBER_OF(o_lf->lfFaceName)); - return true; + if (!boost::regex_match(i_strlf, what, lf)) + return false; + o_lf->lfHeight = _ttoi(what.str(1).c_str()); + o_lf->lfWidth = _ttoi(what.str(2).c_str()); + o_lf->lfEscapement = _ttoi(what.str(3).c_str()); + o_lf->lfOrientation = _ttoi(what.str(4).c_str()); + o_lf->lfWeight = _ttoi(what.str(5).c_str()); + o_lf->lfItalic = (BYTE)_ttoi(what.str(6).c_str()); + o_lf->lfUnderline = (BYTE)_ttoi(what.str(7).c_str()); + o_lf->lfStrikeOut = (BYTE)_ttoi(what.str(8).c_str()); + o_lf->lfCharSet = (BYTE)_ttoi(what.str(9).c_str()); + o_lf->lfOutPrecision = (BYTE)_ttoi(what.str(10).c_str()); + o_lf->lfClipPrecision = (BYTE)_ttoi(what.str(11).c_str()); + o_lf->lfQuality = (BYTE)_ttoi(what.str(12).c_str()); + o_lf->lfPitchAndFamily = (BYTE)_ttoi(what.str(13).c_str()); + tcslcpy(o_lf->lfFaceName, what.str(14).c_str(), NUMBER_OF(o_lf->lfFaceName)); + return true; } // read LOGFONT bool Registry::read(HKEY i_root, const tstring &i_path, const tstring &i_name, - LOGFONT *o_value, const tstring &i_defaultStringValue) + LOGFONT *o_value, const tstring &i_defaultStringValue) { - tstring buf; - if (!read(i_root, i_path, i_name, &buf) || !string2logfont(o_value, buf)) - { - if (!i_defaultStringValue.empty()) - string2logfont(o_value, i_defaultStringValue); - return false; - } - return true; + tstring buf; + if (!read(i_root, i_path, i_name, &buf) || !string2logfont(o_value, buf)) { + if (!i_defaultStringValue.empty()) + string2logfont(o_value, i_defaultStringValue); + return false; + } + return true; } // write LOGFONT bool Registry::write(HKEY i_root, const tstring &i_path, const tstring &i_name, - const LOGFONT &i_value) + const LOGFONT &i_value) { - _TCHAR buf[1024]; - _sntprintf(buf, NUMBER_OF(buf), - _T("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%s"), - i_value.lfHeight, i_value.lfWidth, i_value.lfEscapement, - i_value.lfOrientation, i_value.lfWeight, i_value.lfItalic, - i_value.lfUnderline, i_value.lfStrikeOut, i_value.lfCharSet, - i_value.lfOutPrecision, i_value.lfClipPrecision, - i_value.lfQuality, - i_value.lfPitchAndFamily, i_value.lfFaceName); - return Registry::write(i_root, i_path, i_name, buf); + _TCHAR buf[1024]; + _sntprintf(buf, NUMBER_OF(buf), + _T("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%s"), + i_value.lfHeight, i_value.lfWidth, i_value.lfEscapement, + i_value.lfOrientation, i_value.lfWeight, i_value.lfItalic, + i_value.lfUnderline, i_value.lfStrikeOut, i_value.lfCharSet, + i_value.lfOutPrecision, i_value.lfClipPrecision, + i_value.lfQuality, + i_value.lfPitchAndFamily, i_value.lfFaceName); + return Registry::write(i_root, i_path, i_name, buf); } diff --git a/registry.h b/registry.h index 8a283c2..5671feb 100644 --- a/registry.h +++ b/registry.h @@ -12,123 +12,137 @@ /// registry access class class Registry { - HKEY m_root; /// registry root - tstring m_path; /// path from registry root + HKEY m_root; /// registry root + tstring m_path; /// path from registry root public: - typedef std::list tstrings; - + typedef std::list tstrings; + public: - /// - Registry() : m_root(NULL) { setRoot(NULL, _T("")); } - /// - Registry(HKEY i_root, const tstring &i_path) - : m_root(i_root), m_path(i_path) { setRoot(i_root, i_path); } - - /// set registry root and path - void setRoot(HKEY i_root, const tstring &i_path) - { - m_root = i_root; - m_path = i_path; - _TCHAR exePath[GANA_MAX_PATH]; - _TCHAR exeDrive[GANA_MAX_PATH]; - _TCHAR exeDir[GANA_MAX_PATH]; - GetModuleFileName(NULL, exePath, GANA_MAX_PATH); - _tsplitpath_s(exePath, exeDrive, GANA_MAX_PATH, exeDir, GANA_MAX_PATH, NULL, 0, NULL, 0); - m_path = exeDrive; - m_path += exeDir; - m_path += _T("yamy.ini"); - } - - /// remvoe - bool remove(const tstring &i_name = _T("")) const - { return remove(m_root, m_path, i_name); } - - /// does exist the key ? - bool doesExist() const { return doesExist(m_root, m_path); } - - /// read DWORD - bool read(const tstring &i_name, int *o_value, int i_defaultValue = 0) - const - { return read(m_root, m_path, i_name, o_value, i_defaultValue); } - /// write DWORD - bool write(const tstring &i_name, int i_value) const - { return write(m_root, m_path, i_name, i_value); } - - /// read tstring - bool read(const tstring &i_name, tstring *o_value, - const tstring &i_defaultValue = _T("")) const - { return read(m_root, m_path, i_name, o_value, i_defaultValue); } - /// write tstring - bool write(const tstring &i_name, const tstring &i_value) const - { return write(m_root, m_path, i_name, i_value); } + /// + Registry() : m_root(NULL) { + setRoot(NULL, _T("")); + } + /// + Registry(HKEY i_root, const tstring &i_path) + : m_root(i_root), m_path(i_path) { + setRoot(i_root, i_path); + } + + /// set registry root and path + void setRoot(HKEY i_root, const tstring &i_path) { + m_root = i_root; + m_path = i_path; + _TCHAR exePath[GANA_MAX_PATH]; + _TCHAR exeDrive[GANA_MAX_PATH]; + _TCHAR exeDir[GANA_MAX_PATH]; + GetModuleFileName(NULL, exePath, GANA_MAX_PATH); + _tsplitpath_s(exePath, exeDrive, GANA_MAX_PATH, exeDir, GANA_MAX_PATH, NULL, 0, NULL, 0); + m_path = exeDrive; + m_path += exeDir; + m_path += _T("yamy.ini"); + } + + /// remvoe + bool remove(const tstring &i_name = _T("")) const { + return remove(m_root, m_path, i_name); + } + + /// does exist the key ? + bool doesExist() const { + return doesExist(m_root, m_path); + } + + /// read DWORD + bool read(const tstring &i_name, int *o_value, int i_defaultValue = 0) + const { + return read(m_root, m_path, i_name, o_value, i_defaultValue); + } + /// write DWORD + bool write(const tstring &i_name, int i_value) const { + return write(m_root, m_path, i_name, i_value); + } + + /// read tstring + bool read(const tstring &i_name, tstring *o_value, + const tstring &i_defaultValue = _T("")) const { + return read(m_root, m_path, i_name, o_value, i_defaultValue); + } + /// write tstring + bool write(const tstring &i_name, const tstring &i_value) const { + return write(m_root, m_path, i_name, i_value); + } #ifndef USE_INI - /// read list of tstring - bool read(const tstring &i_name, tstrings *o_value, - const tstrings &i_defaultValue = tstrings()) const - { return read(m_root, m_path, i_name, o_value, i_defaultValue); } - /// write list of tstring - bool write(const tstring &i_name, const tstrings &i_value) const - { return write(m_root, m_path, i_name, i_value); } - - /// read binary data - bool read(const tstring &i_name, BYTE *o_value, DWORD i_valueSize, - const BYTE *i_defaultValue = NULL, DWORD i_defaultValueSize = 0) - const - { return read(m_root, m_path, i_name, o_value, i_valueSize, i_defaultValue, - i_defaultValueSize); } - /// write binary data - bool write(const tstring &i_name, const BYTE *i_value, - DWORD i_valueSize) const - { return write(m_root, m_path, i_name, i_value, i_valueSize); } + /// read list of tstring + bool read(const tstring &i_name, tstrings *o_value, + const tstrings &i_defaultValue = tstrings()) const { + return read(m_root, m_path, i_name, o_value, i_defaultValue); + } + /// write list of tstring + bool write(const tstring &i_name, const tstrings &i_value) const { + return write(m_root, m_path, i_name, i_value); + } + + /// read binary data + bool read(const tstring &i_name, BYTE *o_value, DWORD i_valueSize, + const BYTE *i_defaultValue = NULL, DWORD i_defaultValueSize = 0) + const { + return read(m_root, m_path, i_name, o_value, i_valueSize, i_defaultValue, + i_defaultValueSize); + } + /// write binary data + bool write(const tstring &i_name, const BYTE *i_value, + DWORD i_valueSize) const { + return write(m_root, m_path, i_name, i_value, i_valueSize); + } #endif //!USE_INI public: - /// remove - static bool remove(HKEY i_root, const tstring &i_path, - const tstring &i_name = _T("")); - - /// does exist the key ? - static bool doesExist(HKEY i_root, const tstring &i_path); - - /// read DWORD - static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name, - int *o_value, int i_defaultValue = 0); - /// write DWORD - static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name, - int i_value); - - /// read tstring - static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name, - tstring *o_value, const tstring &i_defaultValue = _T("")); - /// write tstring - static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name, - const tstring &i_value); - + /// remove + static bool remove(HKEY i_root, const tstring &i_path, + const tstring &i_name = _T("")); + + /// does exist the key ? + static bool doesExist(HKEY i_root, const tstring &i_path); + + /// read DWORD + static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name, + int *o_value, int i_defaultValue = 0); + /// write DWORD + static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name, + int i_value); + + /// read tstring + static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name, + tstring *o_value, const tstring &i_defaultValue = _T("")); + /// write tstring + static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name, + const tstring &i_value); + #ifndef USE_INI - /// read list of tstring - static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name, - tstrings *o_value, const tstrings &i_defaultValue = tstrings()); - /// write list of tstring - static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name, - const tstrings &i_value); - - /// read binary data - static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name, - BYTE *o_value, DWORD i_valueSize, - const BYTE *i_defaultValue = NULL, - DWORD i_defaultValueSize = 0); - /// write binary data - static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name, - const BYTE *i_value, DWORD i_valueSize); + /// read list of tstring + static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name, + tstrings *o_value, const tstrings &i_defaultValue = tstrings()); + /// write list of tstring + static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name, + const tstrings &i_value); + + /// read binary data + static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name, + BYTE *o_value, DWORD i_valueSize, + const BYTE *i_defaultValue = NULL, + DWORD i_defaultValueSize = 0); + /// write binary data + static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name, + const BYTE *i_value, DWORD i_valueSize); #endif //!USE_INI - /// read LOGFONT - static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name, - LOGFONT *o_value, const tstring &i_defaultStringValue); - /// write LOGFONT - static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name, - const LOGFONT &i_value); + /// read LOGFONT + static bool read(HKEY i_root, const tstring &i_path, const tstring &i_name, + LOGFONT *o_value, const tstring &i_defaultStringValue); + /// write LOGFONT + static bool write(HKEY i_root, const tstring &i_path, const tstring &i_name, + const LOGFONT &i_value); }; diff --git a/s/installer.cpp b/s/installer.cpp index cd40581..bf567f1 100644 --- a/s/installer.cpp +++ b/s/installer.cpp @@ -15,638 +15,614 @@ namespace Installer { - using namespace std; - - - ///////////////////////////////////////////////////////////////////////////// - // Utility Functions - - /** createLink - uses the shell's IShellLink and IPersistFile interfaces to - create and store a shortcut to the specified object. - @return - the result of calling the member functions of the interfaces. - @param i_pathObj - address of a buffer containing the path of the object. - @param i_pathLink - address of a buffer containing the path where the - shell link is to be stored. - @param i_desc - address of a buffer containing the description of the - shell link. - */ - HRESULT createLink(LPCTSTR i_pathObj, LPCTSTR i_pathLink, LPCTSTR i_desc, - LPCTSTR i_workingDirectory) - { - // Get a pointer to the IShellLink interface. - IShellLink* psl; - HRESULT hres = - CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, - IID_IShellLink, (void **)&psl); - if (SUCCEEDED(hres)) - { - // Set the path to the shortcut target and add the description. - psl->SetPath(i_pathObj); - psl->SetDescription(i_desc); - if (i_workingDirectory) - psl->SetWorkingDirectory(i_workingDirectory); - - // Query IShellLink for the IPersistFile interface for saving the - // shortcut in persistent storage. - IPersistFile* ppf; - hres = psl->QueryInterface(IID_IPersistFile, (void **)&ppf); - - if (SUCCEEDED(hres)) - { +using namespace std; + + +///////////////////////////////////////////////////////////////////////////// +// Utility Functions + +/** createLink + uses the shell's IShellLink and IPersistFile interfaces to + create and store a shortcut to the specified object. + @return + the result of calling the member functions of the interfaces. + @param i_pathObj + address of a buffer containing the path of the object. + @param i_pathLink + address of a buffer containing the path where the + shell link is to be stored. + @param i_desc + address of a buffer containing the description of the + shell link. +*/ +HRESULT createLink(LPCTSTR i_pathObj, LPCTSTR i_pathLink, LPCTSTR i_desc, + LPCTSTR i_workingDirectory) +{ + // Get a pointer to the IShellLink interface. + IShellLink* psl; + HRESULT hres = + CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, + IID_IShellLink, (void **)&psl); + if (SUCCEEDED(hres)) { + // Set the path to the shortcut target and add the description. + psl->SetPath(i_pathObj); + psl->SetDescription(i_desc); + if (i_workingDirectory) + psl->SetWorkingDirectory(i_workingDirectory); + + // Query IShellLink for the IPersistFile interface for saving the + // shortcut in persistent storage. + IPersistFile* ppf; + hres = psl->QueryInterface(IID_IPersistFile, (void **)&ppf); + + if (SUCCEEDED(hres)) { #ifdef UNICODE - // Save the link by calling IPersistFile::Save. - hres = ppf->Save(i_pathLink, TRUE); + // Save the link by calling IPersistFile::Save. + hres = ppf->Save(i_pathLink, TRUE); #else - wchar_t wsz[MAX_PATH]; - // Ensure that the string is ANSI. - MultiByteToWideChar(CP_ACP, 0, i_pathLink, -1, wsz, MAX_PATH); - // Save the link by calling IPersistFile::Save. - hres = ppf->Save(wsz, TRUE); + wchar_t wsz[MAX_PATH]; + // Ensure that the string is ANSI. + MultiByteToWideChar(CP_ACP, 0, i_pathLink, -1, wsz, MAX_PATH); + // Save the link by calling IPersistFile::Save. + hres = ppf->Save(wsz, TRUE); #endif - ppf->Release(); - } - psl->Release(); - } - return hres; - } - - - // create file extension information - void createFileExtension(const tstringi &i_ext, const tstring &i_contentType, - const tstringi &i_fileType, - const tstring &i_fileTypeName, - const tstringi &i_iconPath, - const tstring &i_command) - { - tstring dummy; - - Registry regExt(HKEY_CLASSES_ROOT, i_ext); - if (! regExt.read (_T(""), &dummy)) - CHECK_TRUE( regExt.write(_T(""), i_fileType) ); - if (! regExt.read (_T("Content Type"), &dummy)) - CHECK_TRUE( regExt.write(_T("Content Type"), i_contentType) ); - - Registry regFileType(HKEY_CLASSES_ROOT, i_fileType); - if (! regFileType.read (_T(""), &dummy)) - CHECK_TRUE( regFileType.write(_T(""), i_fileTypeName) ); - - Registry regFileTypeIcon(HKEY_CLASSES_ROOT, - i_fileType + _T("\\DefaultIcon")); - if (! regFileTypeIcon.read (_T(""), &dummy)) - CHECK_TRUE( regFileTypeIcon.write(_T(""), i_iconPath) ); - - Registry regFileTypeComand(HKEY_CLASSES_ROOT, - i_fileType + _T("\\shell\\open\\command")); - if (! regFileTypeComand.read (_T(""), &dummy)) - CHECK_TRUE( regFileTypeComand.write(_T(""), i_command) ); - } - - - // remove file extension information - void removeFileExtension(const tstringi &i_ext, const tstringi &i_fileType) - { - Registry::remove(HKEY_CLASSES_ROOT, i_ext); - Registry::remove(HKEY_CLASSES_ROOT, - i_fileType + _T("\\shell\\open\\command")); - Registry::remove(HKEY_CLASSES_ROOT, i_fileType + _T("\\shell\\open")); - Registry::remove(HKEY_CLASSES_ROOT, i_fileType + _T("\\shell")); - Registry::remove(HKEY_CLASSES_ROOT, i_fileType); - } - - - // create uninstallation information - void createUninstallInformation(const tstringi &i_name, - const tstring &i_displayName, - const tstring &i_commandLine) - { - Registry reg( - HKEY_LOCAL_MACHINE, - _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\") - + i_name); - - CHECK_TRUE( reg.write(_T("DisplayName"), i_displayName) ); - CHECK_TRUE( reg.write(_T("UninstallString"), i_commandLine) ); - } - - - // remove uninstallation information - void removeUninstallInformation(const tstringi &i_name) - { - Registry:: - remove(HKEY_LOCAL_MACHINE, - _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\") - + i_name); - } - - - // normalize path - tstringi normalizePath(tstringi i_path) - { - tregex regSlash(_T("^(.*)/(.*)$")); - tsmatch what; - while (boost::regex_search(i_path, what, regSlash)) - i_path = what.str(1) + _T("\\") + what.str(2); - - tregex regTailBackSlash(_T("^(.*)\\\\$")); - while (boost::regex_search(i_path, what, regTailBackSlash)) - i_path = what.str(1); - - return i_path; - } - - - // create deep directory - bool createDirectories(const _TCHAR *i_folder) - { - const _TCHAR *s = _tcschr(i_folder, _T('\\')); // TODO: '/' - if (s && s - i_folder == 2 && i_folder[1] == _T(':')) - s = _tcschr(s + 1, _T('\\')); - - struct _stat sbuf; - while (s) - { - tstringi f(i_folder, 0, s - i_folder); - if (_tstat(f.c_str(), &sbuf) < 0) - if (!CreateDirectory(f.c_str(), NULL)) - return false; - s = _tcschr(s + 1, _T('\\')); - } - if (_tstat(i_folder, &sbuf) < 0) - if (!CreateDirectory(i_folder, NULL)) - return false; - return true; - } - - - // get driver directory - tstringi getDriverDirectory() - { - _TCHAR buf[GANA_MAX_PATH]; - CHECK_TRUE( GetSystemDirectory(buf, NUMBER_OF(buf)) ); - return tstringi(buf) + _T("\\drivers"); - } - - - // get current directory - tstringi getModuleDirectory() - { - _TCHAR buf[GANA_MAX_PATH]; - CHECK_TRUE( GetModuleFileName(g_hInst, buf, NUMBER_OF(buf)) ); - tregex reg(_T("^(.*)\\\\[^\\\\]*$")); - tsmatch what; - tstringi path(buf); - if (boost::regex_search(path, what, reg)) - return what.str(1); - else - return path; - } - - - // get start menu name - tstringi getStartMenuName(const tstringi &i_shortcutName) - { + ppf->Release(); + } + psl->Release(); + } + return hres; +} + + +// create file extension information +void createFileExtension(const tstringi &i_ext, const tstring &i_contentType, + const tstringi &i_fileType, + const tstring &i_fileTypeName, + const tstringi &i_iconPath, + const tstring &i_command) +{ + tstring dummy; + + Registry regExt(HKEY_CLASSES_ROOT, i_ext); + if (! regExt.read (_T(""), &dummy)) + CHECK_TRUE( regExt.write(_T(""), i_fileType) ); + if (! regExt.read (_T("Content Type"), &dummy)) + CHECK_TRUE( regExt.write(_T("Content Type"), i_contentType) ); + + Registry regFileType(HKEY_CLASSES_ROOT, i_fileType); + if (! regFileType.read (_T(""), &dummy)) + CHECK_TRUE( regFileType.write(_T(""), i_fileTypeName) ); + + Registry regFileTypeIcon(HKEY_CLASSES_ROOT, + i_fileType + _T("\\DefaultIcon")); + if (! regFileTypeIcon.read (_T(""), &dummy)) + CHECK_TRUE( regFileTypeIcon.write(_T(""), i_iconPath) ); + + Registry regFileTypeComand(HKEY_CLASSES_ROOT, + i_fileType + _T("\\shell\\open\\command")); + if (! regFileTypeComand.read (_T(""), &dummy)) + CHECK_TRUE( regFileTypeComand.write(_T(""), i_command) ); +} + + +// remove file extension information +void removeFileExtension(const tstringi &i_ext, const tstringi &i_fileType) +{ + Registry::remove(HKEY_CLASSES_ROOT, i_ext); + Registry::remove(HKEY_CLASSES_ROOT, + i_fileType + _T("\\shell\\open\\command")); + Registry::remove(HKEY_CLASSES_ROOT, i_fileType + _T("\\shell\\open")); + Registry::remove(HKEY_CLASSES_ROOT, i_fileType + _T("\\shell")); + Registry::remove(HKEY_CLASSES_ROOT, i_fileType); +} + + +// create uninstallation information +void createUninstallInformation(const tstringi &i_name, + const tstring &i_displayName, + const tstring &i_commandLine) +{ + Registry reg( + HKEY_LOCAL_MACHINE, + _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\") + + i_name); + + CHECK_TRUE( reg.write(_T("DisplayName"), i_displayName) ); + CHECK_TRUE( reg.write(_T("UninstallString"), i_commandLine) ); +} + + +// remove uninstallation information +void removeUninstallInformation(const tstringi &i_name) +{ + Registry:: + remove(HKEY_LOCAL_MACHINE, + _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\") + + i_name); +} + + +// normalize path +tstringi normalizePath(tstringi i_path) +{ + tregex regSlash(_T("^(.*)/(.*)$")); + tsmatch what; + while (boost::regex_search(i_path, what, regSlash)) + i_path = what.str(1) + _T("\\") + what.str(2); + + tregex regTailBackSlash(_T("^(.*)\\\\$")); + while (boost::regex_search(i_path, what, regTailBackSlash)) + i_path = what.str(1); + + return i_path; +} + + +// create deep directory +bool createDirectories(const _TCHAR *i_folder) +{ + const _TCHAR *s = _tcschr(i_folder, _T('\\')); // TODO: '/' + if (s && s - i_folder == 2 && i_folder[1] == _T(':')) + s = _tcschr(s + 1, _T('\\')); + + struct _stat sbuf; + while (s) { + tstringi f(i_folder, 0, s - i_folder); + if (_tstat(f.c_str(), &sbuf) < 0) + if (!CreateDirectory(f.c_str(), NULL)) + return false; + s = _tcschr(s + 1, _T('\\')); + } + if (_tstat(i_folder, &sbuf) < 0) + if (!CreateDirectory(i_folder, NULL)) + return false; + return true; +} + + +// get driver directory +tstringi getDriverDirectory() +{ + _TCHAR buf[GANA_MAX_PATH]; + CHECK_TRUE( GetSystemDirectory(buf, NUMBER_OF(buf)) ); + return tstringi(buf) + _T("\\drivers"); +} + + +// get current directory +tstringi getModuleDirectory() +{ + _TCHAR buf[GANA_MAX_PATH]; + CHECK_TRUE( GetModuleFileName(g_hInst, buf, NUMBER_OF(buf)) ); + tregex reg(_T("^(.*)\\\\[^\\\\]*$")); + tsmatch what; + tstringi path(buf); + if (boost::regex_search(path, what, reg)) + return what.str(1); + else + return path; +} + + +// get start menu name +tstringi getStartMenuName(const tstringi &i_shortcutName) +{ #if 0 - char programDir[GANA_MAX_PATH]; - if (SUCCEEDED(SHGetSpecialFolderPath(NULL, programDir, - CSIDL_COMMON_PROGRAMS, FALSE))) - return tstringi(programDir) + "\\" + shortcutName + ".lnk"; + char programDir[GANA_MAX_PATH]; + if (SUCCEEDED(SHGetSpecialFolderPath(NULL, programDir, + CSIDL_COMMON_PROGRAMS, FALSE))) + return tstringi(programDir) + "\\" + shortcutName + ".lnk"; #else - tstringi programDir; - if (Registry::read(HKEY_LOCAL_MACHINE, - _T("Software\\Microsoft\\Windows\\CurrentVersion\\") - _T("Explorer\\Shell Folders"), _T("Common Programs"), - &programDir)) - return programDir + _T("\\") + i_shortcutName + _T(".lnk"); + tstringi programDir; + if (Registry::read(HKEY_LOCAL_MACHINE, + _T("Software\\Microsoft\\Windows\\CurrentVersion\\") + _T("Explorer\\Shell Folders"), _T("Common Programs"), + &programDir)) + return programDir + _T("\\") + i_shortcutName + _T(".lnk"); #endif - return _T(""); - } + return _T(""); +} - // get start up name - tstringi getStartUpName(const tstringi &i_shortcutName) - { - tstringi startupDir; - if (Registry::read(HKEY_CURRENT_USER, - _T("Software\\Microsoft\\Windows\\CurrentVersion\\") - _T("Explorer\\Shell Folders"), _T("Startup"), - &startupDir)) - return startupDir + _T("\\") + i_shortcutName + _T(".lnk"); - return _T(""); - } +// get start up name +tstringi getStartUpName(const tstringi &i_shortcutName) +{ + tstringi startupDir; + if (Registry::read(HKEY_CURRENT_USER, + _T("Software\\Microsoft\\Windows\\CurrentVersion\\") + _T("Explorer\\Shell Folders"), _T("Startup"), + &startupDir)) + return startupDir + _T("\\") + i_shortcutName + _T(".lnk"); + return _T(""); +} #if defined(_WINNT) # define MAYUD_FILTER_KEY _T("System\\CurrentControlSet\\Control\\Class\\{4D36E96B-E325-11CE-BFC1-08002BE10318}") - // create driver service - DWORD createDriverService(const tstringi &i_serviceName, - const tstring &i_serviceDescription, - const tstringi &i_driverPath, - const _TCHAR *i_preloadedGroups, - bool forUsb) - { - SC_HANDLE hscm = - OpenSCManager(NULL, NULL, - SC_MANAGER_CREATE_SERVICE | SC_MANAGER_CONNECT); - if (!hscm) - return false; - - SC_HANDLE hs = - CreateService(hscm, i_serviceName.c_str(), i_serviceDescription.c_str(), - SERVICE_START | SERVICE_STOP, SERVICE_KERNEL_DRIVER, - forUsb == true ? SERVICE_DEMAND_START : SERVICE_AUTO_START, - SERVICE_ERROR_IGNORE, - i_driverPath.c_str(), NULL, NULL, - i_preloadedGroups, NULL, NULL); - DWORD err = GetLastError(); - if (hs == NULL) - { - switch (err) - { - case ERROR_SERVICE_EXISTS: - { +// create driver service +DWORD createDriverService(const tstringi &i_serviceName, + const tstring &i_serviceDescription, + const tstringi &i_driverPath, + const _TCHAR *i_preloadedGroups, + bool forUsb) +{ + SC_HANDLE hscm = + OpenSCManager(NULL, NULL, + SC_MANAGER_CREATE_SERVICE | SC_MANAGER_CONNECT); + if (!hscm) + return false; + + SC_HANDLE hs = + CreateService(hscm, i_serviceName.c_str(), i_serviceDescription.c_str(), + SERVICE_START | SERVICE_STOP, SERVICE_KERNEL_DRIVER, + forUsb == true ? SERVICE_DEMAND_START : SERVICE_AUTO_START, + SERVICE_ERROR_IGNORE, + i_driverPath.c_str(), NULL, NULL, + i_preloadedGroups, NULL, NULL); + DWORD err = GetLastError(); + if (hs == NULL) { + switch (err) { + case ERROR_SERVICE_EXISTS: { #if 0 - hs = OpenService(hscm, i_serviceName.c_str(), SERVICE_CHANGE_CONFIG); - if (hs == NULL) { - CloseServiceHandle(hscm); - return GetLastError(); - } - if (!ChangeServiceConfig( - hscm, SERVICE_KERNEL_DRIVER, - forUsb == true ? SERVICE_DEMAND_START : SERVICE_AUTO_START, - SERVICE_ERROR_IGNORE, - i_driverPath.c_str(), NULL, NULL, - i_preloadedGroups, NULL, NULL, - i_serviceDescription.c_str())) { - CloseServiceHandle(hs); - CloseServiceHandle(hscm); - return GetLastError(); // ERROR_IO_PENDING! - // this code always reaches here. why? - } + hs = OpenService(hscm, i_serviceName.c_str(), SERVICE_CHANGE_CONFIG); + if (hs == NULL) { + CloseServiceHandle(hscm); + return GetLastError(); + } + if (!ChangeServiceConfig( + hscm, SERVICE_KERNEL_DRIVER, + forUsb == true ? SERVICE_DEMAND_START : SERVICE_AUTO_START, + SERVICE_ERROR_IGNORE, + i_driverPath.c_str(), NULL, NULL, + i_preloadedGroups, NULL, NULL, + i_serviceDescription.c_str())) { + CloseServiceHandle(hs); + CloseServiceHandle(hscm); + return GetLastError(); // ERROR_IO_PENDING! + // this code always reaches here. why? + } #else - Registry reg(HKEY_LOCAL_MACHINE, - _T("SYSTEM\\CurrentControlSet\\Services\\mayud")); - reg.write(_T("Start"), - forUsb ? SERVICE_DEMAND_START : SERVICE_AUTO_START); + Registry reg(HKEY_LOCAL_MACHINE, + _T("SYSTEM\\CurrentControlSet\\Services\\mayud")); + reg.write(_T("Start"), + forUsb ? SERVICE_DEMAND_START : SERVICE_AUTO_START); #endif - break; + break; + } + default: { + CloseServiceHandle(hscm); + return err; + } + } } - default: - { - CloseServiceHandle(hscm); - return err; + CloseServiceHandle(hs); + CloseServiceHandle(hscm); + + if (forUsb == true) { + Registry reg(HKEY_LOCAL_MACHINE, MAYUD_FILTER_KEY); + typedef std::list Filters; + Filters filters; + if (!reg.read(_T("UpperFilters"), &filters)) + return false; + for (Filters::iterator i = filters.begin(); i != filters.end(); ) { + Filters::iterator next = i; + ++ next; + if (*i == _T("mayud")) { + filters.erase(i); + } + i = next; + } + filters.push_back(_T("mayud")); + if (!reg.write(_T("UpperFilters"), filters)) + return false; } - } - } - CloseServiceHandle(hs); - CloseServiceHandle(hscm); - - if (forUsb == true) { - Registry reg(HKEY_LOCAL_MACHINE, MAYUD_FILTER_KEY); - typedef std::list Filters; - Filters filters; - if (!reg.read(_T("UpperFilters"), &filters)) - return false; - for (Filters::iterator i = filters.begin(); i != filters.end(); ) { - Filters::iterator next = i; - ++ next; - if (*i == _T("mayud")) { - filters.erase(i); - } - i = next; - } - filters.push_back(_T("mayud")); - if (!reg.write(_T("UpperFilters"), filters)) - return false; - } - - return ERROR_SUCCESS; - } + + return ERROR_SUCCESS; +} #endif // _WINNT #if defined(_WINNT) - // remove driver service - DWORD removeDriverService(const tstringi &i_serviceName) - { - DWORD err = ERROR_SUCCESS; - - Registry reg(HKEY_LOCAL_MACHINE, MAYUD_FILTER_KEY); - std::list filters; - if (reg.read(_T("UpperFilters"), &filters)) - { - filters.remove(_T("mayud")); - reg.write(_T("UpperFilters"), filters); - } - - SC_HANDLE hscm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); - SC_HANDLE hs = - OpenService(hscm, i_serviceName.c_str(), - SERVICE_START | SERVICE_STOP | DELETE); - if (!hs) - { - err = GetLastError(); - goto error; - } - - SERVICE_STATUS ss; - ControlService(hs, SERVICE_CONTROL_STOP, &ss); - - if (!DeleteService(hs)) - { - err = GetLastError(); - goto error; - } - error: - CloseServiceHandle(hs); - CloseServiceHandle(hscm); - return err; - } -#endif // _WINNT +// remove driver service +DWORD removeDriverService(const tstringi &i_serviceName) +{ + DWORD err = ERROR_SUCCESS; + Registry reg(HKEY_LOCAL_MACHINE, MAYUD_FILTER_KEY); + std::list filters; + if (reg.read(_T("UpperFilters"), &filters)) { + filters.remove(_T("mayud")); + reg.write(_T("UpperFilters"), filters); + } - // check operating system - bool checkOs(SetupFile::OS os) - { - OSVERSIONINFO ver; - ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - GetVersionEx(&ver); - - switch (os) - { - default: - case SetupFile::ALL: - return true; - case SetupFile::W9x: - return (ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && - 4 <= ver.dwMajorVersion); - case SetupFile::NT : - return (ver.dwPlatformId == VER_PLATFORM_WIN32_NT && - 4 <= ver.dwMajorVersion); - case SetupFile::NT4: - return (ver.dwPlatformId == VER_PLATFORM_WIN32_NT && - ver.dwMajorVersion == 4); - case SetupFile::W2k: // W2k, XP, ... - return (ver.dwPlatformId == VER_PLATFORM_WIN32_NT && - 5 <= ver.dwMajorVersion); - } - } - - - // install files - bool installFiles(const SetupFile::Data *i_setupFiles, - size_t i_setupFilesSize, u_int32 i_flags, - const tstringi &i_srcDir, const tstringi &i_destDir) - { - tstringi to, from; - tstringi destDriverDir = getDriverDirectory(); - - for (size_t i = 0; i < i_setupFilesSize; ++ i) - { - const SetupFile::Data &s = i_setupFiles[i]; - const tstringi &fromDir = i_srcDir; - const tstringi &toDir = - (s.m_destination == SetupFile::ToDriver) ? destDriverDir : i_destDir; - - if (!s.m_from) - continue; // remove only - - if (fromDir == toDir) - continue; // same directory - - if (!checkOs(s.m_os)) // check operating system - continue; - - if ((s.m_flags & i_flags) != i_flags) // check flags - continue; - - // type - switch (s.m_kind) - { - case SetupFile::Dll: - { - // rename driver - tstringi from_ = toDir + _T("\\") + s.m_to; - tstringi to_ = toDir + _T("\\deleted.") + s.m_to; - DeleteFile(to_.c_str()); - MoveFile(from_.c_str(), to_.c_str()); - DeleteFile(to_.c_str()); + SC_HANDLE hscm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); + SC_HANDLE hs = + OpenService(hscm, i_serviceName.c_str(), + SERVICE_START | SERVICE_STOP | DELETE); + if (!hs) { + err = GetLastError(); + goto error; + } + + SERVICE_STATUS ss; + ControlService(hs, SERVICE_CONTROL_STOP, &ss); + + if (!DeleteService(hs)) { + err = GetLastError(); + goto error; } - // fall through +error: + CloseServiceHandle(hs); + CloseServiceHandle(hscm); + return err; +} +#endif // _WINNT + + +// check operating system +bool checkOs(SetupFile::OS os) +{ + OSVERSIONINFO ver; + ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx(&ver); + + switch (os) { default: - case SetupFile::File: - { - from += fromDir + _T('\\') + s.m_from + _T('\0'); - to += toDir + _T('\\') + s.m_to + _T('\0'); - break; + case SetupFile::ALL: + return true; + case SetupFile::W9x: + return (ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && + 4 <= ver.dwMajorVersion); + case SetupFile::NT : + return (ver.dwPlatformId == VER_PLATFORM_WIN32_NT && + 4 <= ver.dwMajorVersion); + case SetupFile::NT4: + return (ver.dwPlatformId == VER_PLATFORM_WIN32_NT && + ver.dwMajorVersion == 4); + case SetupFile::W2k: // W2k, XP, ... + return (ver.dwPlatformId == VER_PLATFORM_WIN32_NT && + 5 <= ver.dwMajorVersion); } - case SetupFile::Dir: - { - createDirectories((toDir + _T('\\') + s.m_to).c_str()); - break; +} + + +// install files +bool installFiles(const SetupFile::Data *i_setupFiles, + size_t i_setupFilesSize, u_int32 i_flags, + const tstringi &i_srcDir, const tstringi &i_destDir) +{ + tstringi to, from; + tstringi destDriverDir = getDriverDirectory(); + + for (size_t i = 0; i < i_setupFilesSize; ++ i) { + const SetupFile::Data &s = i_setupFiles[i]; + const tstringi &fromDir = i_srcDir; + const tstringi &toDir = + (s.m_destination == SetupFile::ToDriver) ? destDriverDir : i_destDir; + + if (!s.m_from) + continue; // remove only + + if (fromDir == toDir) + continue; // same directory + + if (!checkOs(s.m_os)) // check operating system + continue; + + if ((s.m_flags & i_flags) != i_flags) // check flags + continue; + + // type + switch (s.m_kind) { + case SetupFile::Dll: { + // rename driver + tstringi from_ = toDir + _T("\\") + s.m_to; + tstringi to_ = toDir + _T("\\deleted.") + s.m_to; + DeleteFile(to_.c_str()); + MoveFile(from_.c_str(), to_.c_str()); + DeleteFile(to_.c_str()); + } + // fall through + default: + case SetupFile::File: { + from += fromDir + _T('\\') + s.m_from + _T('\0'); + to += toDir + _T('\\') + s.m_to + _T('\0'); + break; + } + case SetupFile::Dir: { + createDirectories((toDir + _T('\\') + s.m_to).c_str()); + break; + } + } } - } - } #if 0 - { - tstringi to_(to), from_(from); - for (size_t i = 0; i < to_.size(); ++ i) - if (!to_[i]) - to_[i] = ' '; - for (size_t i = 0; i < from_.size(); ++ i) - if (!from_[i]) - from_[i] = ' '; - MessageBox(NULL, to_.c_str(), from_.c_str(), MB_OK); - } + { + tstringi to_(to), from_(from); + for (size_t i = 0; i < to_.size(); ++ i) + if (!to_[i]) + to_[i] = ' '; + for (size_t i = 0; i < from_.size(); ++ i) + if (!from_[i]) + from_[i] = ' '; + MessageBox(NULL, to_.c_str(), from_.c_str(), MB_OK); + } #endif - SHFILEOPSTRUCT fo; - ::ZeroMemory(&fo, sizeof(fo)); - fo.wFunc = FO_COPY; - fo.fFlags = FOF_MULTIDESTFILES; - fo.pFrom = from.c_str(); - fo.pTo = to.c_str(); - if (SHFileOperation(&fo) || fo.fAnyOperationsAborted) - return false; - return true; - } - - - // remove files from src - bool removeSrcFiles(const SetupFile::Data *i_setupFiles, - size_t i_setupFilesSize, u_int32 i_flags, - const tstringi &i_srcDir) - { - tstringi destDriverDir = getDriverDirectory(); - - for (size_t i = 0; i < i_setupFilesSize; ++ i) - { - const SetupFile::Data &s = i_setupFiles[i_setupFilesSize - i - 1]; - const tstringi &fromDir = i_srcDir; - - if (!s.m_from) - continue; // remove only - - if (!checkOs(s.m_os)) // check operating system - continue; - - if ((s.m_flags & i_flags) != i_flags) // check flags - continue; - - // type - switch (s.m_kind) - { - default: - case SetupFile::Dll: - case SetupFile::File: - DeleteFile((fromDir + _T('\\') + s.m_from).c_str()); - break; - case SetupFile::Dir: - RemoveDirectory((fromDir + _T('\\') + s.m_from).c_str()); - break; - } - } - RemoveDirectory(i_srcDir.c_str()); - return true; - } - - - // remove files - void removeFiles(const SetupFile::Data *i_setupFiles, - size_t i_setupFilesSize, u_int32 i_flags, - const tstringi &i_destDir) - { - tstringi destDriverDir = getDriverDirectory(); - - for (size_t i = 0; i < i_setupFilesSize; ++ i) - { - const SetupFile::Data &s = i_setupFiles[i_setupFilesSize - i - 1]; - const tstringi &toDir = - (s.m_destination == SetupFile::ToDriver) ? destDriverDir : i_destDir; - - if (!checkOs(s.m_os)) // check operating system - continue; - - if ((s.m_flags & i_flags) != i_flags) // check flags - continue; - - // type - switch (s.m_kind) - { - case SetupFile::Dll: - DeleteFile((toDir + _T("\\deleted.") + s.m_to).c_str()); - // fall through - default: - case SetupFile::File: - DeleteFile((toDir + _T('\\') + s.m_to).c_str()); - break; - case SetupFile::Dir: - RemoveDirectory((toDir + _T('\\') + s.m_to).c_str()); - break; - } - } - RemoveDirectory(i_destDir.c_str()); - } - - - // uninstall step1 - int uninstallStep1(const _TCHAR *i_uninstallOption) - { - // copy this EXEcutable image into the user's temp directory - _TCHAR setup_exe[GANA_MAX_PATH], tmp_setup_exe[GANA_MAX_PATH]; - GetModuleFileName(NULL, setup_exe, NUMBER_OF(setup_exe)); - GetTempPath(NUMBER_OF(tmp_setup_exe), tmp_setup_exe); - GetTempFileName(tmp_setup_exe, _T("del"), 0, tmp_setup_exe); - CopyFile(setup_exe, tmp_setup_exe, FALSE); - - // open the clone EXE using FILE_FLAG_DELETE_ON_CLOSE - HANDLE hfile = CreateFile(tmp_setup_exe, 0, FILE_SHARE_READ, NULL, - OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, NULL); - - // spawn the clone EXE passing it our EXE's process handle - // and the full path name to the original EXE file. - _TCHAR commandLine[512]; - HANDLE hProcessOrig = - OpenProcess(SYNCHRONIZE, TRUE, GetCurrentProcessId()); - _sntprintf(commandLine, NUMBER_OF(commandLine), _T("%s %s %d"), - tmp_setup_exe, i_uninstallOption, hProcessOrig); - STARTUPINFO si; - ::ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - PROCESS_INFORMATION pi; - CreateProcess(NULL, commandLine, NULL, NULL, TRUE, 0, NULL, NULL, &si,&pi); - Sleep(2000); // important - CloseHandle(hProcessOrig); - CloseHandle(hfile); - - return 0; - } - - // uninstall step2 - // (after this function, we cannot use any resource) - void uninstallStep2(const _TCHAR *argByStep1) - { - // clone EXE: When original EXE terminates, delete it - HANDLE hProcessOrig = (HANDLE)_ttoi(argByStep1); - WaitForSingleObject(hProcessOrig, INFINITE); - CloseHandle(hProcessOrig); - } - - - ///////////////////////////////////////////////////////////////////////////// - // Locale / StringResource - - - // constructor - Resource::Resource(const StringResource *i_stringResources) - : m_stringResources(i_stringResources), - m_locale(LOCALE_C) - { - struct LocaleInformaton - { - const _TCHAR *m_localeString; - Locale m_locale; - }; - - // set locale information - const _TCHAR *localeString = ::_tsetlocale(LC_ALL, _T("")); - - static const LocaleInformaton locales[] = - { - { _T("Japanese_Japan.932"), LOCALE_Japanese_Japan_932 }, - }; - - for (size_t i = 0; i < NUMBER_OF(locales); ++ i) - if (_tcsicmp(localeString, locales[i].m_localeString) == 0) - { - m_locale = locales[i].m_locale; - break; - } - } - - - // get resource string - const _TCHAR *Resource::loadString(UINT i_id) - { - int n = static_cast(m_locale); - int index = -1; - for (int i = 0; m_stringResources[i].m_str; ++ i) - if (m_stringResources[i].m_id == i_id) - { - if (n == 0) - return m_stringResources[i].m_str; - index = i; - n --; - } - if (0 <= index) - return m_stringResources[index].m_str; - else - return _T(""); - } + SHFILEOPSTRUCT fo; + ::ZeroMemory(&fo, sizeof(fo)); + fo.wFunc = FO_COPY; + fo.fFlags = FOF_MULTIDESTFILES; + fo.pFrom = from.c_str(); + fo.pTo = to.c_str(); + if (SHFileOperation(&fo) || fo.fAnyOperationsAborted) + return false; + return true; +} + + +// remove files from src +bool removeSrcFiles(const SetupFile::Data *i_setupFiles, + size_t i_setupFilesSize, u_int32 i_flags, + const tstringi &i_srcDir) +{ + tstringi destDriverDir = getDriverDirectory(); + + for (size_t i = 0; i < i_setupFilesSize; ++ i) { + const SetupFile::Data &s = i_setupFiles[i_setupFilesSize - i - 1]; + const tstringi &fromDir = i_srcDir; + + if (!s.m_from) + continue; // remove only + + if (!checkOs(s.m_os)) // check operating system + continue; + + if ((s.m_flags & i_flags) != i_flags) // check flags + continue; + + // type + switch (s.m_kind) { + default: + case SetupFile::Dll: + case SetupFile::File: + DeleteFile((fromDir + _T('\\') + s.m_from).c_str()); + break; + case SetupFile::Dir: + RemoveDirectory((fromDir + _T('\\') + s.m_from).c_str()); + break; + } + } + RemoveDirectory(i_srcDir.c_str()); + return true; +} + + +// remove files +void removeFiles(const SetupFile::Data *i_setupFiles, + size_t i_setupFilesSize, u_int32 i_flags, + const tstringi &i_destDir) +{ + tstringi destDriverDir = getDriverDirectory(); + + for (size_t i = 0; i < i_setupFilesSize; ++ i) { + const SetupFile::Data &s = i_setupFiles[i_setupFilesSize - i - 1]; + const tstringi &toDir = + (s.m_destination == SetupFile::ToDriver) ? destDriverDir : i_destDir; + + if (!checkOs(s.m_os)) // check operating system + continue; + + if ((s.m_flags & i_flags) != i_flags) // check flags + continue; + + // type + switch (s.m_kind) { + case SetupFile::Dll: + DeleteFile((toDir + _T("\\deleted.") + s.m_to).c_str()); + // fall through + default: + case SetupFile::File: + DeleteFile((toDir + _T('\\') + s.m_to).c_str()); + break; + case SetupFile::Dir: + RemoveDirectory((toDir + _T('\\') + s.m_to).c_str()); + break; + } + } + RemoveDirectory(i_destDir.c_str()); +} + + +// uninstall step1 +int uninstallStep1(const _TCHAR *i_uninstallOption) +{ + // copy this EXEcutable image into the user's temp directory + _TCHAR setup_exe[GANA_MAX_PATH], tmp_setup_exe[GANA_MAX_PATH]; + GetModuleFileName(NULL, setup_exe, NUMBER_OF(setup_exe)); + GetTempPath(NUMBER_OF(tmp_setup_exe), tmp_setup_exe); + GetTempFileName(tmp_setup_exe, _T("del"), 0, tmp_setup_exe); + CopyFile(setup_exe, tmp_setup_exe, FALSE); + + // open the clone EXE using FILE_FLAG_DELETE_ON_CLOSE + HANDLE hfile = CreateFile(tmp_setup_exe, 0, FILE_SHARE_READ, NULL, + OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, NULL); + + // spawn the clone EXE passing it our EXE's process handle + // and the full path name to the original EXE file. + _TCHAR commandLine[512]; + HANDLE hProcessOrig = + OpenProcess(SYNCHRONIZE, TRUE, GetCurrentProcessId()); + _sntprintf(commandLine, NUMBER_OF(commandLine), _T("%s %s %d"), + tmp_setup_exe, i_uninstallOption, hProcessOrig); + STARTUPINFO si; + ::ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + PROCESS_INFORMATION pi; + CreateProcess(NULL, commandLine, NULL, NULL, TRUE, 0, NULL, NULL, &si,&pi); + Sleep(2000); // important + CloseHandle(hProcessOrig); + CloseHandle(hfile); + + return 0; +} + +// uninstall step2 +// (after this function, we cannot use any resource) +void uninstallStep2(const _TCHAR *argByStep1) +{ + // clone EXE: When original EXE terminates, delete it + HANDLE hProcessOrig = (HANDLE)_ttoi(argByStep1); + WaitForSingleObject(hProcessOrig, INFINITE); + CloseHandle(hProcessOrig); +} + + +///////////////////////////////////////////////////////////////////////////// +// Locale / StringResource + + +// constructor +Resource::Resource(const StringResource *i_stringResources) + : m_stringResources(i_stringResources), + m_locale(LOCALE_C) +{ + struct LocaleInformaton { + const _TCHAR *m_localeString; + Locale m_locale; + }; + + // set locale information + const _TCHAR *localeString = ::_tsetlocale(LC_ALL, _T("")); + + static const LocaleInformaton locales[] = { + { _T("Japanese_Japan.932"), LOCALE_Japanese_Japan_932 }, + }; + + for (size_t i = 0; i < NUMBER_OF(locales); ++ i) + if (_tcsicmp(localeString, locales[i].m_localeString) == 0) { + m_locale = locales[i].m_locale; + break; + } +} + + +// get resource string +const _TCHAR *Resource::loadString(UINT i_id) +{ + int n = static_cast(m_locale); + int index = -1; + for (int i = 0; m_stringResources[i].m_str; ++ i) + if (m_stringResources[i].m_id == i_id) { + if (n == 0) + return m_stringResources[i].m_str; + index = i; + n --; + } + if (0 <= index) + return m_stringResources[index].m_str; + else + return _T(""); +} } diff --git a/s/installer.h b/s/installer.h index 5d48bb2..bff8bcc 100644 --- a/s/installer.h +++ b/s/installer.h @@ -8,162 +8,156 @@ namespace Installer { - ///////////////////////////////////////////////////////////////////////////// - // SetupFile - - // files to copy - namespace SetupFile - { - enum Kind - { - File, - Dir, - Dll, - }; - - enum OS - { - ALL, - W9x, // W95, W98, - NT, NT4, W2k, // W2k includes XP - }; - - enum Destination - { - ToDest, - ToDriver, - }; - - enum Flag - { - Normal = 1, - }; - - struct Data - { - Kind m_kind; - OS m_os; - u_int32 m_flags; /// user defined flags - const _TCHAR *m_from; - Destination m_destination; - const _TCHAR *m_to; - }; - } - - - ///////////////////////////////////////////////////////////////////////////// - // Locale / StringResource - - enum Locale - { - LOCALE_Japanese_Japan_932 = 0, - LOCALE_C = 1, - }; - - struct StringResource - { - UINT m_id; - _TCHAR *m_str; - }; - - class Resource - { - const StringResource *m_stringResources; - - Locale m_locale; - - public: - // constructor - Resource(const StringResource *i_stringResources); - Resource(const StringResource *i_stringResources, Locale i_locale) - : m_stringResources(i_stringResources), m_locale(i_locale) { } - - // get resource string - const _TCHAR *loadString(UINT i_id); - - // locale - Locale getLocale() const { return m_locale; } - }; - - - ///////////////////////////////////////////////////////////////////////////// - // Utility Functions - - // createLink - uses the shell's IShellLink and IPersistFile interfaces - // to create and store a shortcut to the specified object. - HRESULT createLink(LPCTSTR i_pathObj, LPCTSTR i_pathLink, LPCTSTR i_desc, - LPCTSTR i_workingDirectory = NULL); - - // create file extension information - void createFileExtension(const tstringi &i_ext, const tstring &i_contentType, - const tstringi &i_fileType, - const tstring &i_fileTypeName, - const tstringi &i_iconPath, - const tstring &i_command); - - // remove file extension information - void removeFileExtension(const tstringi &i_ext, const tstringi &i_fileType); - - // create uninstallation information - void createUninstallInformation(const tstringi &i_name, - const tstring &i_displayName, - const tstring &i_commandLine); - - // remove uninstallation information - void removeUninstallInformation(const tstringi &i_name); - - // normalize path - tstringi normalizePath(tstringi i_path); - - // create deep directory - bool createDirectories(const _TCHAR *i_folder); - - // get driver directory - tstringi getDriverDirectory(); - - // get current directory - tstringi getModuleDirectory(); - - // get start menu name - tstringi getStartMenuName(const tstringi &i_shortcutName); - - // get start up name - tstringi getStartUpName(const tstringi &i_shortcutName); - - // create driver service - DWORD createDriverService(const tstringi &i_serviceName, - const tstring &i_serviceDescription, - const tstringi &i_driverPath, - const _TCHAR *i_preloadedGroups, - bool forUsb); - - // remove driver service - DWORD removeDriverService(const tstringi &i_serviceName); - - // check operating system - bool checkOs(SetupFile::OS i_os); - - // install files - bool installFiles(const SetupFile::Data *i_setupFiles, - size_t i_setupFilesSize, u_int32 i_flags, - const tstringi &i_srcDir, const tstringi &i_destDir); - - // remove files from src - bool removeSrcFiles(const SetupFile::Data *i_setupFiles, - size_t i_setupFilesSize, u_int32 i_flags, - const tstringi &i_srcDir); - - // remove files - void removeFiles(const SetupFile::Data *i_setupFiles, - size_t i_setupFilesSize, u_int32 i_flags, - const tstringi &i_destDir); - - // uninstall step1 - int uninstallStep1(const _TCHAR *i_uninstallOption); - - // uninstall step2 - // (after this function, we cannot use any resource) - void uninstallStep2(const _TCHAR *i_argByStep1); +///////////////////////////////////////////////////////////////////////////// +// SetupFile + +// files to copy +namespace SetupFile { +enum Kind { + File, + Dir, + Dll, +}; + +enum OS { + ALL, + W9x, // W95, W98, + NT, NT4, W2k, // W2k includes XP +}; + +enum Destination { + ToDest, + ToDriver, +}; + +enum Flag { + Normal = 1, +}; + +struct Data { + Kind m_kind; + OS m_os; + u_int32 m_flags; /// user defined flags + const _TCHAR *m_from; + Destination m_destination; + const _TCHAR *m_to; +}; +} + + +///////////////////////////////////////////////////////////////////////////// +// Locale / StringResource + +enum Locale { + LOCALE_Japanese_Japan_932 = 0, + LOCALE_C = 1, +}; + +struct StringResource { + UINT m_id; + _TCHAR *m_str; +}; + +class Resource +{ + const StringResource *m_stringResources; + + Locale m_locale; + +public: + // constructor + Resource(const StringResource *i_stringResources); + Resource(const StringResource *i_stringResources, Locale i_locale) + : m_stringResources(i_stringResources), m_locale(i_locale) { } + + // get resource string + const _TCHAR *loadString(UINT i_id); + + // locale + Locale getLocale() const { + return m_locale; + } +}; + + +///////////////////////////////////////////////////////////////////////////// +// Utility Functions + +// createLink - uses the shell's IShellLink and IPersistFile interfaces +// to create and store a shortcut to the specified object. +HRESULT createLink(LPCTSTR i_pathObj, LPCTSTR i_pathLink, LPCTSTR i_desc, + LPCTSTR i_workingDirectory = NULL); + +// create file extension information +void createFileExtension(const tstringi &i_ext, const tstring &i_contentType, + const tstringi &i_fileType, + const tstring &i_fileTypeName, + const tstringi &i_iconPath, + const tstring &i_command); + +// remove file extension information +void removeFileExtension(const tstringi &i_ext, const tstringi &i_fileType); + +// create uninstallation information +void createUninstallInformation(const tstringi &i_name, + const tstring &i_displayName, + const tstring &i_commandLine); + +// remove uninstallation information +void removeUninstallInformation(const tstringi &i_name); + +// normalize path +tstringi normalizePath(tstringi i_path); + +// create deep directory +bool createDirectories(const _TCHAR *i_folder); + +// get driver directory +tstringi getDriverDirectory(); + +// get current directory +tstringi getModuleDirectory(); + +// get start menu name +tstringi getStartMenuName(const tstringi &i_shortcutName); + +// get start up name +tstringi getStartUpName(const tstringi &i_shortcutName); + +// create driver service +DWORD createDriverService(const tstringi &i_serviceName, + const tstring &i_serviceDescription, + const tstringi &i_driverPath, + const _TCHAR *i_preloadedGroups, + bool forUsb); + +// remove driver service +DWORD removeDriverService(const tstringi &i_serviceName); + +// check operating system +bool checkOs(SetupFile::OS i_os); + +// install files +bool installFiles(const SetupFile::Data *i_setupFiles, + size_t i_setupFilesSize, u_int32 i_flags, + const tstringi &i_srcDir, const tstringi &i_destDir); + +// remove files from src +bool removeSrcFiles(const SetupFile::Data *i_setupFiles, + size_t i_setupFilesSize, u_int32 i_flags, + const tstringi &i_srcDir); + +// remove files +void removeFiles(const SetupFile::Data *i_setupFiles, + size_t i_setupFilesSize, u_int32 i_flags, + const tstringi &i_destDir); + +// uninstall step1 +int uninstallStep1(const _TCHAR *i_uninstallOption); + +// uninstall step2 +// (after this function, we cannot use any resource) +void uninstallStep2(const _TCHAR *i_argByStep1); } diff --git a/s/setup.cpp b/s/setup.cpp index 846bdec..9d4daad 100644 --- a/s/setup.cpp +++ b/s/setup.cpp @@ -30,93 +30,89 @@ using namespace Installer; // Globals -enum -{ - Flag_Usb = 1 << 1, +enum { + Flag_Usb = 1 << 1, }; u_int32 g_flags = SetupFile::Normal; using namespace SetupFile; -const SetupFile::Data g_setupFiles[] = -{ - // same name +const SetupFile::Data g_setupFiles[] = { + // same name #define SN(i_kind, i_os, i_from, i_destination) \ { i_kind, i_os, Normal|Flag_Usb, _T(i_from), i_destination, _T(i_from) } - // different name + // different name #define DN(i_kind, i_os, i_from, i_destination, i_to) \ { i_kind, i_os, Normal|Flag_Usb, _T(i_from), i_destination, _T(i_to) } - - // executables - SN(Dll , ALL, "mayu.dll" , ToDest), - SN(File, ALL, "mayu.exe" , ToDest), - SN(File, ALL, "setup.exe" , ToDest), - - // drivers + + // executables + SN(Dll , ALL, "mayu.dll" , ToDest), + SN(File, ALL, "mayu.exe" , ToDest), + SN(File, ALL, "setup.exe" , ToDest), + + // drivers #if defined(_WINNT) - SN(File, NT , "mayud.sys" , ToDest), - SN(File, NT , "mayudnt4.sys" , ToDest), - SN(File, W2k, "mayudrsc.sys" , ToDest), - SN(File, W2k, "mayud.sys" , ToDriver), - DN(File, NT4, "mayudnt4.sys" , ToDriver, "mayud.sys"), - SN(File, W2k, "mayudrsc.sys" , ToDriver), + SN(File, NT , "mayud.sys" , ToDest), + SN(File, NT , "mayudnt4.sys" , ToDest), + SN(File, W2k, "mayudrsc.sys" , ToDest), + SN(File, W2k, "mayud.sys" , ToDriver), + DN(File, NT4, "mayudnt4.sys" , ToDriver, "mayud.sys"), + SN(File, W2k, "mayudrsc.sys" , ToDriver), #elif defined(_WIN95) - SN(File, W9x, "mayud.vxd" , ToDest), + SN(File, W9x, "mayud.vxd" , ToDest), #else # error #endif - // setting files - SN(File, ALL, "104.mayu" , ToDest), - SN(File, ALL, "104on109.mayu" , ToDest), - SN(File, ALL, "109.mayu" , ToDest), - SN(File, ALL, "109on104.mayu" , ToDest), - SN(File, ALL, "default.mayu" , ToDest), - SN(File, ALL, "dot.mayu" , ToDest), - SN(File, ALL, "emacsedit.mayu" , ToDest), - - // documents - SN(Dir , ALL, "doc" , ToDest), // mkdir - DN(File, ALL, "banner-ja.gif" , ToDest, "doc\\banner-ja.gif" ), - DN(File, ALL, "edit-setting-ja.png", ToDest, "doc\\edit-setting-ja.png"), - DN(File, ALL, "investigate-ja.png" , ToDest, "doc\\investigate-ja.png" ), - DN(File, ALL, "log-ja.png" , ToDest, "doc\\log-ja.png" ), - DN(File, ALL, "menu-ja.png" , ToDest, "doc\\menu-ja.png" ), - DN(File, ALL, "pause-ja.png" , ToDest, "doc\\pause-ja.png" ), - DN(File, ALL, "setting-ja.png" , ToDest, "doc\\setting-ja.png" ), - DN(File, ALL, "target.png" , ToDest, "doc\\target.png" ), - DN(File, ALL, "version-ja.png" , ToDest, "doc\\version-ja.png" ), - DN(File, ALL, "CONTENTS-ja.html" , ToDest, "doc\\CONTENTS-ja.html" ), - DN(File, ALL, "CUSTOMIZE-ja.html" , ToDest, "doc\\CUSTOMIZE-ja.html" ), - DN(File, ALL, "MANUAL-ja.html" , ToDest, "doc\\MANUAL-ja.html" ), - DN(File, ALL, "README-ja.html" , ToDest, "doc\\README-ja.html" ), - DN(File, ALL, "README.css" , ToDest, "doc\\README.css" ), - DN(File, ALL, "syntax.txt" , ToDest, "doc\\syntax.txt" ), - - SN(File, ALL, "mayu-mode.el" , ToDest), - - SN(Dir , ALL, "contrib" , ToDest), // mkdir - DN(File, ALL, "mayu-settings.txt" , ToDest, "contrib\\mayu-settings.txt"), - DN(File, ALL, "dvorak.mayu" , ToDest, "contrib\\dvorak.mayu" ), - DN(File, ALL, "DVORAKon109.mayu" , ToDest, "contrib\\DVORAKon109.mayu" ), - DN(File, ALL, "keitai.mayu" , ToDest, "contrib\\keitai.mayu" ), - DN(File, ALL, "ax.mayu" , ToDest, "contrib\\ax.mayu" ), - DN(File, ALL, "98x1.mayu" , ToDest, "contrib\\98x1.mayu" ), - DN(File, ALL, "109onAX.mayu" , ToDest, "contrib\\109onAX.mayu" ), - - SN(Dir , ALL, "Plugins" , ToDest), // mkdir + // setting files + SN(File, ALL, "104.mayu" , ToDest), + SN(File, ALL, "104on109.mayu" , ToDest), + SN(File, ALL, "109.mayu" , ToDest), + SN(File, ALL, "109on104.mayu" , ToDest), + SN(File, ALL, "default.mayu" , ToDest), + SN(File, ALL, "dot.mayu" , ToDest), + SN(File, ALL, "emacsedit.mayu" , ToDest), + + // documents + SN(Dir , ALL, "doc" , ToDest), // mkdir + DN(File, ALL, "banner-ja.gif" , ToDest, "doc\\banner-ja.gif" ), + DN(File, ALL, "edit-setting-ja.png", ToDest, "doc\\edit-setting-ja.png"), + DN(File, ALL, "investigate-ja.png" , ToDest, "doc\\investigate-ja.png" ), + DN(File, ALL, "log-ja.png" , ToDest, "doc\\log-ja.png" ), + DN(File, ALL, "menu-ja.png" , ToDest, "doc\\menu-ja.png" ), + DN(File, ALL, "pause-ja.png" , ToDest, "doc\\pause-ja.png" ), + DN(File, ALL, "setting-ja.png" , ToDest, "doc\\setting-ja.png" ), + DN(File, ALL, "target.png" , ToDest, "doc\\target.png" ), + DN(File, ALL, "version-ja.png" , ToDest, "doc\\version-ja.png" ), + DN(File, ALL, "CONTENTS-ja.html" , ToDest, "doc\\CONTENTS-ja.html" ), + DN(File, ALL, "CUSTOMIZE-ja.html" , ToDest, "doc\\CUSTOMIZE-ja.html" ), + DN(File, ALL, "MANUAL-ja.html" , ToDest, "doc\\MANUAL-ja.html" ), + DN(File, ALL, "README-ja.html" , ToDest, "doc\\README-ja.html" ), + DN(File, ALL, "README.css" , ToDest, "doc\\README.css" ), + DN(File, ALL, "syntax.txt" , ToDest, "doc\\syntax.txt" ), + + SN(File, ALL, "mayu-mode.el" , ToDest), + + SN(Dir , ALL, "contrib" , ToDest), // mkdir + DN(File, ALL, "mayu-settings.txt" , ToDest, "contrib\\mayu-settings.txt"), + DN(File, ALL, "dvorak.mayu" , ToDest, "contrib\\dvorak.mayu" ), + DN(File, ALL, "DVORAKon109.mayu" , ToDest, "contrib\\DVORAKon109.mayu" ), + DN(File, ALL, "keitai.mayu" , ToDest, "contrib\\keitai.mayu" ), + DN(File, ALL, "ax.mayu" , ToDest, "contrib\\ax.mayu" ), + DN(File, ALL, "98x1.mayu" , ToDest, "contrib\\98x1.mayu" ), + DN(File, ALL, "109onAX.mayu" , ToDest, "contrib\\109onAX.mayu" ), + + SN(Dir , ALL, "Plugins" , ToDest), // mkdir }; -enum KeyboardKind -{ - KEYBOARD_KIND_109, - KEYBOARD_KIND_104, +enum KeyboardKind { + KEYBOARD_KIND_109, + KEYBOARD_KIND_104, } g_keyboardKind; -static const StringResource g_strres[] = -{ +static const StringResource g_strres[] = { #include "strres.h" }; @@ -133,45 +129,43 @@ tstringi g_destDir; // destination directory // show message int message(int i_id, int i_flag, HWND i_hwnd = NULL) { - return MessageBox(i_hwnd, g_resource->loadString(i_id), - g_resource->loadString(IDS_mayuSetup), i_flag); + return MessageBox(i_hwnd, g_resource->loadString(i_id), + g_resource->loadString(IDS_mayuSetup), i_flag); } // driver service error void driverServiceError(DWORD i_err) { - switch (i_err) - { - case ERROR_ACCESS_DENIED: - message(IDS_notAdministrator, MB_OK | MB_ICONSTOP); - break; - case ERROR_SERVICE_MARKED_FOR_DELETE: - message(IDS_alreadyUninstalled, MB_OK | MB_ICONSTOP); - break; - default: - { - TCHAR *errmsg; - int err = int(i_err); - if (err < 0) { - i_err = -err; - } - if (FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, i_err, 0, (LPTSTR)&errmsg, 0, NULL)) { - TCHAR buf[1024]; - _sntprintf(buf, NUMBER_OF(buf), _T("%s: %d: %s\n"), - g_resource->loadString(IDS_error), - err, errmsg); - LocalFree(errmsg); - MessageBox(NULL, buf, g_resource->loadString(IDS_mayuSetup), - MB_OK | MB_ICONSTOP); - } else { - message(IDS_error, MB_OK | MB_ICONSTOP); - } - break; - } - } + switch (i_err) { + case ERROR_ACCESS_DENIED: + message(IDS_notAdministrator, MB_OK | MB_ICONSTOP); + break; + case ERROR_SERVICE_MARKED_FOR_DELETE: + message(IDS_alreadyUninstalled, MB_OK | MB_ICONSTOP); + break; + default: { + TCHAR *errmsg; + int err = int(i_err); + if (err < 0) { + i_err = -err; + } + if (FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, i_err, 0, (LPTSTR)&errmsg, 0, NULL)) { + TCHAR buf[1024]; + _sntprintf(buf, NUMBER_OF(buf), _T("%s: %d: %s\n"), + g_resource->loadString(IDS_error), + err, errmsg); + LocalFree(errmsg); + MessageBox(NULL, buf, g_resource->loadString(IDS_mayuSetup), + MB_OK | MB_ICONSTOP); + } else { + message(IDS_error, MB_OK | MB_ICONSTOP); + } + break; + } + } } /////////////////////////////////////////////////////////////////////////////// @@ -181,301 +175,279 @@ void driverServiceError(DWORD i_err) // dialog box class DlgMain { - HWND m_hwnd; - bool m_doRegisterToStartMenu; // if register to the start menu - bool m_doRegisterToStartUp; // if register to the start up + HWND m_hwnd; + bool m_doRegisterToStartMenu; // if register to the start menu + bool m_doRegisterToStartUp; // if register to the start up private: - // install - int install() - { - Registry reg(DIR_REGISTRY_ROOT); - CHECK_TRUE( reg.write(_T("dir"), g_destDir) ); - tstringi srcDir = getModuleDirectory(); - - if (!installFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, srcDir, - g_destDir)) - { - removeFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, g_destDir); - if (g_wasExecutedBySFX) - removeSrcFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, srcDir); - return 1; - } - if (g_wasExecutedBySFX) - removeSrcFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, srcDir); + // install + int install() { + Registry reg(DIR_REGISTRY_ROOT); + CHECK_TRUE( reg.write(_T("dir"), g_destDir) ); + tstringi srcDir = getModuleDirectory(); + + if (!installFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, srcDir, + g_destDir)) { + removeFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, g_destDir); + if (g_wasExecutedBySFX) + removeSrcFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, srcDir); + return 1; + } + if (g_wasExecutedBySFX) + removeSrcFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, srcDir); #if defined(_WINNT) - DWORD err = - createDriverService(_T("mayud"), - g_resource->loadString(IDS_mayud), - getDriverDirectory() + _T("\\mayud.sys"), - _T("+Keyboard Class\0"), - g_flags & Flag_Usb ? true : false); - - if (err != ERROR_SUCCESS) - { - driverServiceError(err); - removeFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, g_destDir); - return 1; - } - - if (g_flags == Flag_Usb) - CHECK_TRUE( reg.write(_T("isUsbDriver"), DWORD(1)) ); + DWORD err = + createDriverService(_T("mayud"), + g_resource->loadString(IDS_mayud), + getDriverDirectory() + _T("\\mayud.sys"), + _T("+Keyboard Class\0"), + g_flags & Flag_Usb ? true : false); + + if (err != ERROR_SUCCESS) { + driverServiceError(err); + removeFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, g_destDir); + return 1; + } + + if (g_flags == Flag_Usb) + CHECK_TRUE( reg.write(_T("isUsbDriver"), DWORD(1)) ); #endif // _WINNT - - // create shortcut - if (m_doRegisterToStartMenu) - { - tstringi shortcut = getStartMenuName(loadString(IDS_shortcutName)); - if (!shortcut.empty()) - createLink((g_destDir + _T("\\mayu.exe")).c_str(), shortcut.c_str(), - g_resource->loadString(IDS_shortcutName), - g_destDir.c_str()); - } - if (m_doRegisterToStartUp) - { - tstringi shortcut = getStartUpName(loadString(IDS_shortcutName)); - if (!shortcut.empty()) - createLink((g_destDir + _T("\\mayu.exe")).c_str(), shortcut.c_str(), - g_resource->loadString(IDS_shortcutName), - g_destDir.c_str()); - } - - // set registry - reg.write(_T("layout"), - (g_keyboardKind == KEYBOARD_KIND_109) ? _T("109") : _T("104")); - - // file extension - createFileExtension(_T(".mayu"), _T("text/plain"), - _T("mayu file"), g_resource->loadString(IDS_mayuFile), - g_destDir + _T("\\mayu.exe,1"), - g_resource->loadString(IDS_mayuShellOpen)); - - // uninstall - createUninstallInformation(_T("mayu"), g_resource->loadString(IDS_mayu), - g_destDir + _T("\\setup.exe -u")); - - if (g_flags == Flag_Usb) - { - if (message(IDS_copyFinishUsb, MB_YESNO | MB_ICONQUESTION, m_hwnd) - == IDYES) - { - // reboot ... - HANDLE hToken; - // Get a token for this process. - if (!OpenProcessToken(GetCurrentProcess(), - TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) - { - message(IDS_failedToReboot, MB_OK | MB_ICONSTOP); - return 0; - } - // Get the LUID for the shutdown privilege. - TOKEN_PRIVILEGES tkp; - LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); - tkp.PrivilegeCount = 1; // one privilege to set - tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - // Get the shutdown privilege for this process. - AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, - (PTOKEN_PRIVILEGES)NULL, 0); - // Cannot test the return value of AdjustTokenPrivileges. - if (GetLastError() != ERROR_SUCCESS) - { - message(IDS_failedToReboot, MB_OK | MB_ICONSTOP); - return 0; - } - // Shut down the system and force all applications to close. - if (!ExitWindowsEx(EWX_REBOOT | EWX_FORCE, 0)) - { - message(IDS_failedToReboot, MB_OK | MB_ICONSTOP); - return 0; + + // create shortcut + if (m_doRegisterToStartMenu) { + tstringi shortcut = getStartMenuName(loadString(IDS_shortcutName)); + if (!shortcut.empty()) + createLink((g_destDir + _T("\\mayu.exe")).c_str(), shortcut.c_str(), + g_resource->loadString(IDS_shortcutName), + g_destDir.c_str()); + } + if (m_doRegisterToStartUp) { + tstringi shortcut = getStartUpName(loadString(IDS_shortcutName)); + if (!shortcut.empty()) + createLink((g_destDir + _T("\\mayu.exe")).c_str(), shortcut.c_str(), + g_resource->loadString(IDS_shortcutName), + g_destDir.c_str()); + } + + // set registry + reg.write(_T("layout"), + (g_keyboardKind == KEYBOARD_KIND_109) ? _T("109") : _T("104")); + + // file extension + createFileExtension(_T(".mayu"), _T("text/plain"), + _T("mayu file"), g_resource->loadString(IDS_mayuFile), + g_destDir + _T("\\mayu.exe,1"), + g_resource->loadString(IDS_mayuShellOpen)); + + // uninstall + createUninstallInformation(_T("mayu"), g_resource->loadString(IDS_mayu), + g_destDir + _T("\\setup.exe -u")); + + if (g_flags == Flag_Usb) { + if (message(IDS_copyFinishUsb, MB_YESNO | MB_ICONQUESTION, m_hwnd) + == IDYES) { + // reboot ... + HANDLE hToken; + // Get a token for this process. + if (!OpenProcessToken(GetCurrentProcess(), + TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { + message(IDS_failedToReboot, MB_OK | MB_ICONSTOP); + return 0; + } + // Get the LUID for the shutdown privilege. + TOKEN_PRIVILEGES tkp; + LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); + tkp.PrivilegeCount = 1; // one privilege to set + tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + // Get the shutdown privilege for this process. + AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, + (PTOKEN_PRIVILEGES)NULL, 0); + // Cannot test the return value of AdjustTokenPrivileges. + if (GetLastError() != ERROR_SUCCESS) { + message(IDS_failedToReboot, MB_OK | MB_ICONSTOP); + return 0; + } + // Shut down the system and force all applications to close. + if (!ExitWindowsEx(EWX_REBOOT | EWX_FORCE, 0)) { + message(IDS_failedToReboot, MB_OK | MB_ICONSTOP); + return 0; + } + } + } else { + if (message(IDS_copyFinish, MB_YESNO | MB_ICONQUESTION, m_hwnd) + == IDYES) + ExitWindows(0, 0); // logoff + } + return 0; } - } - } - else - { - if (message(IDS_copyFinish, MB_YESNO | MB_ICONQUESTION, m_hwnd) - == IDYES) - ExitWindows(0, 0); // logoff - } - return 0; - } - + private: - // WM_INITDIALOG - BOOL wmInitDialog(HWND /* focus */, LPARAM /* lParam */) - { - setSmallIcon(m_hwnd, IDI_ICON_mayu); - setBigIcon(m_hwnd, IDI_ICON_mayu); - Edit_SetText(GetDlgItem(m_hwnd, IDC_EDIT_path), g_destDir.c_str()); - HWND hwndCombo = GetDlgItem(m_hwnd, IDC_COMBO_keyboard); + // WM_INITDIALOG + BOOL wmInitDialog(HWND /* focus */, LPARAM /* lParam */) { + setSmallIcon(m_hwnd, IDI_ICON_mayu); + setBigIcon(m_hwnd, IDI_ICON_mayu); + Edit_SetText(GetDlgItem(m_hwnd, IDC_EDIT_path), g_destDir.c_str()); + HWND hwndCombo = GetDlgItem(m_hwnd, IDC_COMBO_keyboard); #if 0 - if (checkOs(SetupFile::W2k)) + if (checkOs(SetupFile::W2k)) #endif - { - ComboBox_AddString(hwndCombo, - g_resource->loadString(IDS_keyboard109usb)); - ComboBox_AddString(hwndCombo, - g_resource->loadString(IDS_keyboard104usb)); - } + { + ComboBox_AddString(hwndCombo, + g_resource->loadString(IDS_keyboard109usb)); + ComboBox_AddString(hwndCombo, + g_resource->loadString(IDS_keyboard104usb)); + } #if 0 - ComboBox_AddString(hwndCombo, g_resource->loadString(IDS_keyboard109)); - ComboBox_AddString(hwndCombo, g_resource->loadString(IDS_keyboard104)); + ComboBox_AddString(hwndCombo, g_resource->loadString(IDS_keyboard109)); + ComboBox_AddString(hwndCombo, g_resource->loadString(IDS_keyboard104)); #endif - ComboBox_SetCurSel(hwndCombo, - (g_keyboardKind == KEYBOARD_KIND_109) ? 0 : 1); - tstring note; - for (int i = IDS_note01; i <= IDS_note13; ++ i) { - note += g_resource->loadString(i); - } - Edit_SetText(GetDlgItem(m_hwnd, IDC_EDIT_note), note.c_str()); - return TRUE; - } - - // WM_CLOSE - BOOL wmClose() - { - EndDialog(m_hwnd, 0); - return TRUE; - } - - // WM_COMMAND - BOOL wmCommand(int /* notify_code */, int i_id, HWND /* hwnd_control */) - { - switch (i_id) - { - case IDC_BUTTON_browse: - { - _TCHAR folder[GANA_MAX_PATH]; - - BROWSEINFO bi; - ZeroMemory(&bi, sizeof(bi)); - bi.hwndOwner = m_hwnd; - bi.pidlRoot = NULL; - bi.pszDisplayName = folder; - bi.lpszTitle = g_resource->loadString(IDS_selectDir); - ITEMIDLIST *browse = SHBrowseForFolder(&bi); - if (browse != NULL) - { - if (SHGetPathFromIDList(browse, folder)) - { - if (createDirectories(folder)) - Edit_SetText(GetDlgItem(m_hwnd, IDC_EDIT_path), folder); - } - IMalloc *imalloc = NULL; - if (SHGetMalloc(&imalloc) == NOERROR) - imalloc->Free((void *)browse); + ComboBox_SetCurSel(hwndCombo, + (g_keyboardKind == KEYBOARD_KIND_109) ? 0 : 1); + tstring note; + for (int i = IDS_note01; i <= IDS_note13; ++ i) { + note += g_resource->loadString(i); + } + Edit_SetText(GetDlgItem(m_hwnd, IDC_EDIT_note), note.c_str()); + return TRUE; + } + + // WM_CLOSE + BOOL wmClose() { + EndDialog(m_hwnd, 0); + return TRUE; } - return TRUE; - } - - case IDOK: - { - _TCHAR buf[GANA_MAX_PATH]; - Edit_GetText(GetDlgItem(m_hwnd, IDC_EDIT_path), buf, NUMBER_OF(buf)); - if (buf[0]) - { - g_destDir = normalizePath(buf); - m_doRegisterToStartMenu = - (IsDlgButtonChecked(m_hwnd, IDC_CHECK_registerStartMenu) == - BST_CHECKED); - m_doRegisterToStartUp = - (IsDlgButtonChecked(m_hwnd, IDC_CHECK_registerStartUp) == - BST_CHECKED); - - int curSel = - ComboBox_GetCurSel(GetDlgItem(m_hwnd, IDC_COMBO_keyboard)); - g_flags = SetupFile::Normal; + + // WM_COMMAND + BOOL wmCommand(int /* notify_code */, int i_id, HWND /* hwnd_control */) { + switch (i_id) { + case IDC_BUTTON_browse: { + _TCHAR folder[GANA_MAX_PATH]; + + BROWSEINFO bi; + ZeroMemory(&bi, sizeof(bi)); + bi.hwndOwner = m_hwnd; + bi.pidlRoot = NULL; + bi.pszDisplayName = folder; + bi.lpszTitle = g_resource->loadString(IDS_selectDir); + ITEMIDLIST *browse = SHBrowseForFolder(&bi); + if (browse != NULL) { + if (SHGetPathFromIDList(browse, folder)) { + if (createDirectories(folder)) + Edit_SetText(GetDlgItem(m_hwnd, IDC_EDIT_path), folder); + } + IMalloc *imalloc = NULL; + if (SHGetMalloc(&imalloc) == NOERROR) + imalloc->Free((void *)browse); + } + return TRUE; + } + + case IDOK: { + _TCHAR buf[GANA_MAX_PATH]; + Edit_GetText(GetDlgItem(m_hwnd, IDC_EDIT_path), buf, NUMBER_OF(buf)); + if (buf[0]) { + g_destDir = normalizePath(buf); + m_doRegisterToStartMenu = + (IsDlgButtonChecked(m_hwnd, IDC_CHECK_registerStartMenu) == + BST_CHECKED); + m_doRegisterToStartUp = + (IsDlgButtonChecked(m_hwnd, IDC_CHECK_registerStartUp) == + BST_CHECKED); + + int curSel = + ComboBox_GetCurSel(GetDlgItem(m_hwnd, IDC_COMBO_keyboard)); + g_flags = SetupFile::Normal; #if 0 - if (checkOs(SetupFile::W2k)) + if (checkOs(SetupFile::W2k)) #endif - { - switch (curSel) - { - case 0: - g_keyboardKind = KEYBOARD_KIND_109; - g_flags = Flag_Usb; - break; - case 1: - g_keyboardKind = KEYBOARD_KIND_104; - g_flags = Flag_Usb; - break; + { + switch (curSel) { + case 0: + g_keyboardKind = KEYBOARD_KIND_109; + g_flags = Flag_Usb; + break; + case 1: + g_keyboardKind = KEYBOARD_KIND_104; + g_flags = Flag_Usb; + break; #if 0 - case 2: g_keyboardKind = KEYBOARD_KIND_109; break; - case 3: g_keyboardKind = KEYBOARD_KIND_104; break; + case 2: + g_keyboardKind = KEYBOARD_KIND_109; + break; + case 3: + g_keyboardKind = KEYBOARD_KIND_104; + break; #endif - }; - } + }; + } #if 0 - else - { - switch (curSel) - { - case 0: g_keyboardKind = KEYBOARD_KIND_109; break; - case 1: g_keyboardKind = KEYBOARD_KIND_104; break; - }; - } + else { + switch (curSel) { + case 0: + g_keyboardKind = KEYBOARD_KIND_109; + break; + case 1: + g_keyboardKind = KEYBOARD_KIND_104; + break; + }; + } #endif #if 0 - if (g_flags == Flag_Usb) - if (message(IDS_usbWarning, MB_OKCANCEL | MB_ICONWARNING, m_hwnd) - == IDCANCEL) - return TRUE; + if (g_flags == Flag_Usb) + if (message(IDS_usbWarning, MB_OKCANCEL | MB_ICONWARNING, m_hwnd) + == IDCANCEL) + return TRUE; #endif - - if (createDirectories(g_destDir.c_str())) - EndDialog(m_hwnd, install()); - else - message(IDS_invalidDirectory, MB_OK | MB_ICONSTOP, m_hwnd); + + if (createDirectories(g_destDir.c_str())) + EndDialog(m_hwnd, install()); + else + message(IDS_invalidDirectory, MB_OK | MB_ICONSTOP, m_hwnd); + } else + message(IDS_mayuEmpty, MB_OK, m_hwnd); + return TRUE; + } + + case IDCANCEL: { + CHECK_TRUE( EndDialog(m_hwnd, 0) ); + return TRUE; + } + } + return FALSE; } - else - message(IDS_mayuEmpty, MB_OK, m_hwnd); - return TRUE; - } - - case IDCANCEL: - { - CHECK_TRUE( EndDialog(m_hwnd, 0) ); - return TRUE; - } - } - return FALSE; - } public: - DlgMain(HWND i_hwnd) - : m_hwnd(i_hwnd), - m_doRegisterToStartMenu(false), - m_doRegisterToStartUp(false) - { - } - - static BOOL CALLBACK dlgProc(HWND i_hwnd, UINT i_message, - WPARAM i_wParam, LPARAM i_lParam) - { - DlgMain *wc; - getUserData(i_hwnd, &wc); - if (!wc) - switch (i_message) - { - case WM_INITDIALOG: - wc = setUserData(i_hwnd, new DlgMain(i_hwnd)); - return wc->wmInitDialog(reinterpret_cast(i_wParam), i_lParam); - } - else - switch (i_message) - { - case WM_COMMAND: - return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam), - reinterpret_cast(i_lParam)); - case WM_CLOSE: - return wc->wmClose(); - case WM_NCDESTROY: - delete wc; - return TRUE; - } - return FALSE; - } + DlgMain(HWND i_hwnd) + : m_hwnd(i_hwnd), + m_doRegisterToStartMenu(false), + m_doRegisterToStartUp(false) { + } + + static BOOL CALLBACK dlgProc(HWND i_hwnd, UINT i_message, + WPARAM i_wParam, LPARAM i_lParam) { + DlgMain *wc; + getUserData(i_hwnd, &wc); + if (!wc) + switch (i_message) { + case WM_INITDIALOG: + wc = setUserData(i_hwnd, new DlgMain(i_hwnd)); + return wc->wmInitDialog(reinterpret_cast(i_wParam), i_lParam); + } + else + switch (i_message) { + case WM_COMMAND: + return wc->wmCommand(HIWORD(i_wParam), LOWORD(i_wParam), + reinterpret_cast(i_lParam)); + case WM_CLOSE: + return wc->wmClose(); + case WM_NCDESTROY: + delete wc; + return TRUE; + } + return FALSE; + } }; @@ -483,105 +455,102 @@ public: // (in this function, we cannot use any resource, so we use strres[]) int uninstall() { - if (IDYES != message(IDS_removeOk, MB_YESNO | MB_ICONQUESTION)) - return 1; + if (IDYES != message(IDS_removeOk, MB_YESNO | MB_ICONQUESTION)) + return 1; #if defined(_WINNT) - DWORD err = removeDriverService(_T("mayud")); - if (err != ERROR_SUCCESS) - { - driverServiceError(err); - return 1; - } + DWORD err = removeDriverService(_T("mayud")); + if (err != ERROR_SUCCESS) { + driverServiceError(err); + return 1; + } #endif // _WINNT - DeleteFile(getStartMenuName( - g_resource->loadString(IDS_shortcutName)).c_str()); - DeleteFile(getStartUpName( - g_resource->loadString(IDS_shortcutName)).c_str()); - - removeFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, g_destDir); - removeFileExtension(_T(".mayu"), _T("mayu file")); - removeUninstallInformation(_T("mayu")); - - Registry::remove(DIR_REGISTRY_ROOT); - Registry::remove(HKEY_CURRENT_USER, _T("Software\\GANAware\\mayu")); - - message(IDS_removeFinish, MB_OK | MB_ICONINFORMATION); - return 0; + DeleteFile(getStartMenuName( + g_resource->loadString(IDS_shortcutName)).c_str()); + DeleteFile(getStartUpName( + g_resource->loadString(IDS_shortcutName)).c_str()); + + removeFiles(g_setupFiles, NUMBER_OF(g_setupFiles), g_flags, g_destDir); + removeFileExtension(_T(".mayu"), _T("mayu file")); + removeUninstallInformation(_T("mayu")); + + Registry::remove(DIR_REGISTRY_ROOT); + Registry::remove(HKEY_CURRENT_USER, _T("Software\\GANAware\\mayu")); + + message(IDS_removeFinish, MB_OK | MB_ICONINFORMATION); + return 0; } int WINAPI _tWinMain(HINSTANCE i_hInstance, HINSTANCE /* hPrevInstance */, - LPTSTR /* lpszCmdLine */, int /* nCmdShow */) + LPTSTR /* lpszCmdLine */, int /* nCmdShow */) { - CoInitialize(NULL); - - g_hInst = i_hInstance; - Resource resource(g_strres); - g_resource = &resource; - - // check OS - if ( + CoInitialize(NULL); + + g_hInst = i_hInstance; + Resource resource(g_strres); + g_resource = &resource; + + // check OS + if ( #if defined(_WINNT) - !checkOs(SetupFile::NT) + !checkOs(SetupFile::NT) #elif defined(_WIN95) - !checkOs(SetupFile::W9x) + !checkOs(SetupFile::W9x) #else # error #endif - ) - { - message(IDS_invalidOS, MB_OK | MB_ICONSTOP); - return 1; - } - - // keyboard kind - g_keyboardKind = - (resource.getLocale() == LOCALE_Japanese_Japan_932) ? - KEYBOARD_KIND_109 : KEYBOARD_KIND_104; - - // read registry - tstringi programFiles; // "Program Files" directory - Registry::read(HKEY_LOCAL_MACHINE, - _T("Software\\Microsoft\\Windows\\CurrentVersion"), - _T("ProgramFilesDir"), &programFiles); - Registry::read(DIR_REGISTRY_ROOT, _T("dir"), &g_destDir, - programFiles + _T("\\mayu")); - - int retval = 1; - - if (__argc == 2 && _tcsicmp(__targv[1], _T("-u")) == 0) - retval = uninstallStep1(_T("-u")); - else - { - HANDLE mutexPrevVer = CreateMutex( - (SECURITY_ATTRIBUTES *)NULL, TRUE, - MUTEX_MAYU_EXCLUSIVE_RUNNING); - if (GetLastError() == ERROR_ALREADY_EXISTS) { // mayu is running - message(IDS_mayuRunning, MB_OK | MB_ICONSTOP); - } else { - // is mayu running ? - HANDLE mutex = CreateMutex( - (SECURITY_ATTRIBUTES *)NULL, TRUE, - addSessionId(MUTEX_MAYU_EXCLUSIVE_RUNNING).c_str()); - if (GetLastError() == ERROR_ALREADY_EXISTS) { // mayu is running - message(IDS_mayuRunning, MB_OK | MB_ICONSTOP); - } else if (__argc == 3 && _tcsicmp(__targv[1], _T("-u")) == 0) { - uninstallStep2(__targv[2]); - retval = uninstall(); - } else if (__argc == 2 && _tcsicmp(__targv[1], _T("-s")) == 0) { - g_wasExecutedBySFX = true; - retval = DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_main), NULL, - DlgMain::dlgProc); - } else if (__argc == 1) { - retval = DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_main), NULL, - DlgMain::dlgProc); - } - CloseHandle(mutex); - } - CloseHandle(mutexPrevVer); - } - - return retval; + ) { + message(IDS_invalidOS, MB_OK | MB_ICONSTOP); + return 1; + } + + // keyboard kind + g_keyboardKind = + (resource.getLocale() == LOCALE_Japanese_Japan_932) ? + KEYBOARD_KIND_109 : KEYBOARD_KIND_104; + + // read registry + tstringi programFiles; // "Program Files" directory + Registry::read(HKEY_LOCAL_MACHINE, + _T("Software\\Microsoft\\Windows\\CurrentVersion"), + _T("ProgramFilesDir"), &programFiles); + Registry::read(DIR_REGISTRY_ROOT, _T("dir"), &g_destDir, + programFiles + _T("\\mayu")); + + int retval = 1; + + if (__argc == 2 && _tcsicmp(__targv[1], _T("-u")) == 0) + retval = uninstallStep1(_T("-u")); + else { + HANDLE mutexPrevVer = CreateMutex( + (SECURITY_ATTRIBUTES *)NULL, TRUE, + MUTEX_MAYU_EXCLUSIVE_RUNNING); + if (GetLastError() == ERROR_ALREADY_EXISTS) { // mayu is running + message(IDS_mayuRunning, MB_OK | MB_ICONSTOP); + } else { + // is mayu running ? + HANDLE mutex = CreateMutex( + (SECURITY_ATTRIBUTES *)NULL, TRUE, + addSessionId(MUTEX_MAYU_EXCLUSIVE_RUNNING).c_str()); + if (GetLastError() == ERROR_ALREADY_EXISTS) { // mayu is running + message(IDS_mayuRunning, MB_OK | MB_ICONSTOP); + } else if (__argc == 3 && _tcsicmp(__targv[1], _T("-u")) == 0) { + uninstallStep2(__targv[2]); + retval = uninstall(); + } else if (__argc == 2 && _tcsicmp(__targv[1], _T("-s")) == 0) { + g_wasExecutedBySFX = true; + retval = DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_main), NULL, + DlgMain::dlgProc); + } else if (__argc == 1) { + retval = DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_main), NULL, + DlgMain::dlgProc); + } + CloseHandle(mutex); + } + CloseHandle(mutexPrevVer); + } + + return retval; } diff --git a/s/setuprc.h b/s/setuprc.h index 8273554..fdd0c87 100644 --- a/s/setuprc.h +++ b/s/setuprc.h @@ -47,7 +47,7 @@ #define IDC_EDIT_note 1005 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 diff --git a/setting.cpp b/setting.cpp index e33139f..ae14912 100644 --- a/setting.cpp +++ b/setting.cpp @@ -22,94 +22,90 @@ namespace Event { - Key prefixed(_T("prefixed")); - Key before_key_down(_T("before-key-down")); - Key after_key_up(_T("after-key-up")); - Key *events[] = - { - &prefixed, - &before_key_down, - &after_key_up, - NULL, - }; +Key prefixed(_T("prefixed")); +Key before_key_down(_T("before-key-down")); +Key after_key_up(_T("after-key-up")); +Key *events[] = { + &prefixed, + &before_key_down, + &after_key_up, + NULL, +}; } // get mayu filename static bool getFilenameFromRegistry( - tstringi *o_name, tstringi *o_filename, Setting::Symbols *o_symbols) -{ - Registry reg(MAYU_REGISTRY_ROOT); - int index; - reg.read(_T(".mayuIndex"), &index, 0); - _TCHAR buf[100]; - _sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index); - - tstringi entry; - if (!reg.read(buf, &entry)) - return false; - - tregex getFilename(_T("^([^;]*);([^;]*);(.*)$")); - tsmatch getFilenameResult; - if (!boost::regex_match(entry, getFilenameResult, getFilename)) - return false; - - if (o_name) - *o_name = getFilenameResult.str(1); - if (o_filename) - *o_filename = getFilenameResult.str(2); - if (o_symbols) - { - tstringi symbols = getFilenameResult.str(3); - tregex symbol(_T("-D([^;]*)(.*)$")); - tsmatch symbolResult; - while (boost::regex_search(symbols, symbolResult, symbol)) - { - o_symbols->insert(symbolResult.str(1)); - symbols = symbolResult.str(2); - } - } - return true; + tstringi *o_name, tstringi *o_filename, Setting::Symbols *o_symbols) +{ + Registry reg(MAYU_REGISTRY_ROOT); + int index; + reg.read(_T(".mayuIndex"), &index, 0); + _TCHAR buf[100]; + _sntprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index); + + tstringi entry; + if (!reg.read(buf, &entry)) + return false; + + tregex getFilename(_T("^([^;]*);([^;]*);(.*)$")); + tsmatch getFilenameResult; + if (!boost::regex_match(entry, getFilenameResult, getFilename)) + return false; + + if (o_name) + *o_name = getFilenameResult.str(1); + if (o_filename) + *o_filename = getFilenameResult.str(2); + if (o_symbols) { + tstringi symbols = getFilenameResult.str(3); + tregex symbol(_T("-D([^;]*)(.*)$")); + tsmatch symbolResult; + while (boost::regex_search(symbols, symbolResult, symbol)) { + o_symbols->insert(symbolResult.str(1)); + symbols = symbolResult.str(2); + } + } + return true; } // get home directory path void getHomeDirectories(HomeDirectories *o_pathes) { - tstringi filename; + tstringi filename; #ifndef USE_INI - if (getFilenameFromRegistry(NULL, &filename, NULL) && - !filename.empty()) - { - tregex getPath(_T("^(.*[/\\\\])[^/\\\\]*$")); - tsmatch getPathResult; - if (boost::regex_match(filename, getPathResult, getPath)) - o_pathes->push_back(getPathResult.str(1)); - } - - const _TCHAR *home = _tgetenv(_T("HOME")); - if (home) - o_pathes->push_back(home); - - const _TCHAR *homedrive = _tgetenv(_T("HOMEDRIVE")); - const _TCHAR *homepath = _tgetenv(_T("HOMEPATH")); - if (homedrive && homepath) - o_pathes->push_back(tstringi(homedrive) + homepath); - - const _TCHAR *userprofile = _tgetenv(_T("USERPROFILE")); - if (userprofile) - o_pathes->push_back(userprofile); - - _TCHAR buf[GANA_MAX_PATH]; - DWORD len = GetCurrentDirectory(NUMBER_OF(buf), buf); - if (0 < len && len < NUMBER_OF(buf)) - o_pathes->push_back(buf); + if (getFilenameFromRegistry(NULL, &filename, NULL) && + !filename.empty()) { + tregex getPath(_T("^(.*[/\\\\])[^/\\\\]*$")); + tsmatch getPathResult; + if (boost::regex_match(filename, getPathResult, getPath)) + o_pathes->push_back(getPathResult.str(1)); + } + + const _TCHAR *home = _tgetenv(_T("HOME")); + if (home) + o_pathes->push_back(home); + + const _TCHAR *homedrive = _tgetenv(_T("HOMEDRIVE")); + const _TCHAR *homepath = _tgetenv(_T("HOMEPATH")); + if (homedrive && homepath) + o_pathes->push_back(tstringi(homedrive) + homepath); + + const _TCHAR *userprofile = _tgetenv(_T("USERPROFILE")); + if (userprofile) + o_pathes->push_back(userprofile); + + _TCHAR buf[GANA_MAX_PATH]; + DWORD len = GetCurrentDirectory(NUMBER_OF(buf), buf); + if (0 < len && len < NUMBER_OF(buf)) + o_pathes->push_back(buf); #else //USE_INI - _TCHAR buf[GANA_MAX_PATH]; + _TCHAR buf[GANA_MAX_PATH]; #endif //USE_INI - if (GetModuleFileName(GetModuleHandle(NULL), buf, NUMBER_OF(buf))) - o_pathes->push_back(pathRemoveFileSpec(buf)); + if (GetModuleFileName(GetModuleHandle(NULL), buf, NUMBER_OF(buf))) + o_pathes->push_back(pathRemoveFileSpec(buf)); } @@ -120,266 +116,255 @@ void getHomeDirectories(HomeDirectories *o_pathes) // is there no more tokens ? bool SettingLoader::isEOL() { - return m_ti == m_tokens.end(); + return m_ti == m_tokens.end(); } // get next token Token *SettingLoader::getToken() { - if (isEOL()) - throw ErrorMessage() << _T("too few words."); - return &*(m_ti ++); + if (isEOL()) + throw ErrorMessage() << _T("too few words."); + return &*(m_ti ++); } - + // look next token Token *SettingLoader::lookToken() { - if (isEOL()) - throw ErrorMessage() << _T("too few words."); - return &*m_ti; + if (isEOL()) + throw ErrorMessage() << _T("too few words."); + return &*m_ti; } // argument "(" bool SettingLoader::getOpenParen(bool i_doesThrow, const _TCHAR *i_name) { - if (!isEOL() && lookToken()->isOpenParen()) - { - getToken(); - return true; - } - if (i_doesThrow) - throw ErrorMessage() << _T("there must be `(' after `&") - << i_name << _T("'."); - return false; + if (!isEOL() && lookToken()->isOpenParen()) { + getToken(); + return true; + } + if (i_doesThrow) + throw ErrorMessage() << _T("there must be `(' after `&") + << i_name << _T("'."); + return false; } // argument ")" bool SettingLoader::getCloseParen(bool i_doesThrow, const _TCHAR *i_name) { - if (!isEOL() && lookToken()->isCloseParen()) - { - getToken(); - return true; - } - if (i_doesThrow) - throw ErrorMessage() << _T("`&") << i_name - << _T("': too many arguments."); - return false; + if (!isEOL() && lookToken()->isCloseParen()) { + getToken(); + return true; + } + if (i_doesThrow) + throw ErrorMessage() << _T("`&") << i_name + << _T("': too many arguments."); + return false; } // argument "," bool SettingLoader::getComma(bool i_doesThrow, const _TCHAR *i_name) { - if (!isEOL() && lookToken()->isComma()) - { - getToken(); - return true; - } - if (i_doesThrow) - throw ErrorMessage() << _T("`&") << i_name - << _T("': comma expected."); - return false; + if (!isEOL() && lookToken()->isComma()) { + getToken(); + return true; + } + if (i_doesThrow) + throw ErrorMessage() << _T("`&") << i_name + << _T("': comma expected."); + return false; } // void SettingLoader::load_INCLUDE() { - SettingLoader loader(m_soLog, m_log); - loader.m_defaultAssignModifier = m_defaultAssignModifier; - loader.m_defaultKeySeqModifier = m_defaultKeySeqModifier; - if (!loader.load(m_setting, (*getToken()).getString())) - m_isThereAnyError = true; + SettingLoader loader(m_soLog, m_log); + loader.m_defaultAssignModifier = m_defaultAssignModifier; + loader.m_defaultKeySeqModifier = m_defaultKeySeqModifier; + if (!loader.load(m_setting, (*getToken()).getString())) + m_isThereAnyError = true; } // void SettingLoader::load_SCAN_CODES(Key *o_key) { - for (int j = 0; j < Key::MAX_SCAN_CODES_SIZE && !isEOL(); ++ j) - { - ScanCode sc; - sc.m_flags = 0; - while (true) - { - Token *t = getToken(); - if (t->isNumber()) - { - sc.m_scan = (u_char)t->getNumber(); - o_key->addScanCode(sc); - break; - } - if (*t == _T("E0-")) sc.m_flags |= ScanCode::E0; - else if (*t == _T("E1-")) sc.m_flags |= ScanCode::E1; - else throw ErrorMessage() << _T("`") << *t - << _T("': invalid modifier."); - } - } + for (int j = 0; j < Key::MAX_SCAN_CODES_SIZE && !isEOL(); ++ j) { + ScanCode sc; + sc.m_flags = 0; + while (true) { + Token *t = getToken(); + if (t->isNumber()) { + sc.m_scan = (u_char)t->getNumber(); + o_key->addScanCode(sc); + break; + } + if (*t == _T("E0-")) sc.m_flags |= ScanCode::E0; + else if (*t == _T("E1-")) sc.m_flags |= ScanCode::E1; + else throw ErrorMessage() << _T("`") << *t + << _T("': invalid modifier."); + } + } } // void SettingLoader::load_DEFINE_KEY() { - Token *t = getToken(); - Key key; - - // - if (*t == _T('(')) - { - key.addName(getToken()->getString()); - while (t = getToken(), *t != _T(')')) - key.addName(t->getString()); - if (*getToken() != _T("=")) - throw ErrorMessage() << _T("there must be `=' after `)'."); - } - else - { - key.addName(t->getString()); - while (t = getToken(), *t != _T("=")) - key.addName(t->getString()); - } - - load_SCAN_CODES(&key); - m_setting->m_keyboard.addKey(key); + Token *t = getToken(); + Key key; + + // + if (*t == _T('(')) { + key.addName(getToken()->getString()); + while (t = getToken(), *t != _T(')')) + key.addName(t->getString()); + if (*getToken() != _T("=")) + throw ErrorMessage() << _T("there must be `=' after `)'."); + } else { + key.addName(t->getString()); + while (t = getToken(), *t != _T("=")) + key.addName(t->getString()); + } + + load_SCAN_CODES(&key); + m_setting->m_keyboard.addKey(key); } // void SettingLoader::load_DEFINE_MODIFIER() { - Token *t = getToken(); - Modifier::Type mt; - if (*t == _T("shift") ) mt = Modifier::Type_Shift; - else if (*t == _T("alt") || - *t == _T("meta") || - *t == _T("menu") ) mt = Modifier::Type_Alt; - else if (*t == _T("control") || - *t == _T("ctrl") ) mt = Modifier::Type_Control; - else if (*t == _T("windows") || - *t == _T("win") ) mt = Modifier::Type_Windows; - else throw ErrorMessage() << _T("`") << *t - << _T("': invalid modifier name."); - - if (*getToken() != _T("=")) - throw ErrorMessage() << _T("there must be `=' after modifier name."); - - while (!isEOL()) - { - t = getToken(); - Key *key = - m_setting->m_keyboard.searchKeyByNonAliasName(t->getString()); - if (!key) - throw ErrorMessage() << _T("`") << *t << _T("': invalid key name."); - m_setting->m_keyboard.addModifier(mt, key); - } + Token *t = getToken(); + Modifier::Type mt; + if (*t == _T("shift") ) mt = Modifier::Type_Shift; + else if (*t == _T("alt") || + *t == _T("meta") || + *t == _T("menu") ) mt = Modifier::Type_Alt; + else if (*t == _T("control") || + *t == _T("ctrl") ) mt = Modifier::Type_Control; + else if (*t == _T("windows") || + *t == _T("win") ) mt = Modifier::Type_Windows; + else throw ErrorMessage() << _T("`") << *t + << _T("': invalid modifier name."); + + if (*getToken() != _T("=")) + throw ErrorMessage() << _T("there must be `=' after modifier name."); + + while (!isEOL()) { + t = getToken(); + Key *key = + m_setting->m_keyboard.searchKeyByNonAliasName(t->getString()); + if (!key) + throw ErrorMessage() << _T("`") << *t << _T("': invalid key name."); + m_setting->m_keyboard.addModifier(mt, key); + } } // void SettingLoader::load_DEFINE_SYNC_KEY() { - Key *key = m_setting->m_keyboard.getSyncKey(); - key->initialize(); - key->addName(_T("sync")); - - if (*getToken() != _T("=")) - throw ErrorMessage() << _T("there must be `=' after `sync'."); - - load_SCAN_CODES(key); + Key *key = m_setting->m_keyboard.getSyncKey(); + key->initialize(); + key->addName(_T("sync")); + + if (*getToken() != _T("=")) + throw ErrorMessage() << _T("there must be `=' after `sync'."); + + load_SCAN_CODES(key); } // void SettingLoader::load_DEFINE_ALIAS() { - Token *name = getToken(); - - if (*getToken() != _T("=")) - throw ErrorMessage() << _T("there must be `=' after `alias'."); + Token *name = getToken(); - Token *t = getToken(); - Key *key = m_setting->m_keyboard.searchKeyByNonAliasName(t->getString()); - if (!key) - throw ErrorMessage() << _T("`") << *t << _T("': invalid key name."); - m_setting->m_keyboard.addAlias(name->getString(), key); + if (*getToken() != _T("=")) + throw ErrorMessage() << _T("there must be `=' after `alias'."); + + Token *t = getToken(); + Key *key = m_setting->m_keyboard.searchKeyByNonAliasName(t->getString()); + if (!key) + throw ErrorMessage() << _T("`") << *t << _T("': invalid key name."); + m_setting->m_keyboard.addAlias(name->getString(), key); } // void SettingLoader::load_DEFINE_SUBSTITUTE() { - typedef std::list AssignedKeys; - AssignedKeys assignedKeys; - do - { - ModifiedKey mkey; - mkey.m_modifier = - load_MODIFIER(Modifier::Type_ASSIGN, m_defaultAssignModifier); - mkey.m_key = load_KEY_NAME(); - assignedKeys.push_back(mkey); - } while (!(*lookToken() == _T("=>") || *lookToken() == _T("="))); - getToken(); - - KeySeq *keySeq = load_KEY_SEQUENCE(_T(""), false, Modifier::Type_ASSIGN); - ModifiedKey mkey = keySeq->getFirstModifiedKey(); - if (!mkey.m_key) - throw ErrorMessage() << _T("no key is specified for substitute."); - - for (AssignedKeys::iterator i = assignedKeys.begin(); - i != assignedKeys.end(); ++ i) - m_setting->m_keyboard.addSubstitute(*i, mkey); + typedef std::list AssignedKeys; + AssignedKeys assignedKeys; + do { + ModifiedKey mkey; + mkey.m_modifier = + load_MODIFIER(Modifier::Type_ASSIGN, m_defaultAssignModifier); + mkey.m_key = load_KEY_NAME(); + assignedKeys.push_back(mkey); + } while (!(*lookToken() == _T("=>") || *lookToken() == _T("="))); + getToken(); + + KeySeq *keySeq = load_KEY_SEQUENCE(_T(""), false, Modifier::Type_ASSIGN); + ModifiedKey mkey = keySeq->getFirstModifiedKey(); + if (!mkey.m_key) + throw ErrorMessage() << _T("no key is specified for substitute."); + + for (AssignedKeys::iterator i = assignedKeys.begin(); + i != assignedKeys.end(); ++ i) + m_setting->m_keyboard.addSubstitute(*i, mkey); } // void SettingLoader::load_DEFINE_OPTION() { - Token *t = getToken(); - if (*t == _T("KL-")) { - if (*getToken() != _T("=")) { - throw ErrorMessage() << _T("there must be `=' after `def option KL-'."); - } - - load_ARGUMENT(&m_setting->m_correctKanaLockHandling); - - } else if (*t == _T("delay-of")) { - if (*getToken() != _T("!!!")) { - throw ErrorMessage() - << _T("there must be `!!!' after `def option delay-of'."); - } - - if (*getToken() != _T("=")) { - throw ErrorMessage() - << _T("there must be `=' after `def option delay-of !!!'."); - } - - load_ARGUMENT(&m_setting->m_oneShotRepeatableDelay); - - } else if (*t == _T("sts4mayu")) { - if (*getToken() != _T("=")) { - throw ErrorMessage() - << _T("there must be `=' after `def option sts4mayu'."); - } - - load_ARGUMENT(&m_setting->m_sts4mayu); - - } else if (*t == _T("cts4mayu")) { - if (*getToken() != _T("=")) { - throw ErrorMessage() - << _T("there must be `=' after `def option cts4mayu'."); - } - - load_ARGUMENT(&m_setting->m_cts4mayu); - - } else { - throw ErrorMessage() << _T("syntax error `def option ") << *t << _T("'."); - } + Token *t = getToken(); + if (*t == _T("KL-")) { + if (*getToken() != _T("=")) { + throw ErrorMessage() << _T("there must be `=' after `def option KL-'."); + } + + load_ARGUMENT(&m_setting->m_correctKanaLockHandling); + + } else if (*t == _T("delay-of")) { + if (*getToken() != _T("!!!")) { + throw ErrorMessage() + << _T("there must be `!!!' after `def option delay-of'."); + } + + if (*getToken() != _T("=")) { + throw ErrorMessage() + << _T("there must be `=' after `def option delay-of !!!'."); + } + + load_ARGUMENT(&m_setting->m_oneShotRepeatableDelay); + + } else if (*t == _T("sts4mayu")) { + if (*getToken() != _T("=")) { + throw ErrorMessage() + << _T("there must be `=' after `def option sts4mayu'."); + } + + load_ARGUMENT(&m_setting->m_sts4mayu); + + } else if (*t == _T("cts4mayu")) { + if (*getToken() != _T("=")) { + throw ErrorMessage() + << _T("there must be `=' after `def option cts4mayu'."); + } + + load_ARGUMENT(&m_setting->m_cts4mayu); + + } else { + throw ErrorMessage() << _T("syntax error `def option ") << *t << _T("'."); + } } @@ -387,915 +372,879 @@ void SettingLoader::load_DEFINE_OPTION() // void SettingLoader::load_KEYBOARD_DEFINITION() { - Token *t = getToken(); - - // - if (*t == _T("key")) load_DEFINE_KEY(); + Token *t = getToken(); + + // + if (*t == _T("key")) load_DEFINE_KEY(); + + // + else if (*t == _T("mod")) load_DEFINE_MODIFIER(); + + // + else if (*t == _T("sync")) load_DEFINE_SYNC_KEY(); - // - else if (*t == _T("mod")) load_DEFINE_MODIFIER(); - - // - else if (*t == _T("sync")) load_DEFINE_SYNC_KEY(); - - // - else if (*t == _T("alias")) load_DEFINE_ALIAS(); - - // - else if (*t == _T("subst")) load_DEFINE_SUBSTITUTE(); + // + else if (*t == _T("alias")) load_DEFINE_ALIAS(); - // - else if (*t == _T("option")) load_DEFINE_OPTION(); - - // - else throw ErrorMessage() << _T("syntax error `") << *t << _T("'."); + // + else if (*t == _T("subst")) load_DEFINE_SUBSTITUTE(); + + // + else if (*t == _T("option")) load_DEFINE_OPTION(); + + // + else throw ErrorMessage() << _T("syntax error `") << *t << _T("'."); } // <..._MODIFIER> Modifier SettingLoader::load_MODIFIER( - Modifier::Type i_mode, Modifier i_modifier, Modifier::Type *o_mode) -{ - if (o_mode) - *o_mode = Modifier::Type_begin; - - Modifier isModifierSpecified; - enum { PRESS, RELEASE, DONTCARE } flag = PRESS; - - int i; - for (i = i_mode; i < Modifier::Type_ASSIGN; ++ i) - { - i_modifier.dontcare(Modifier::Type(i)); - isModifierSpecified.on(Modifier::Type(i)); - } - - Token *t = NULL; - - continue_loop: - while (!isEOL()) - { - t = lookToken(); - - const static struct { const _TCHAR *m_s; Modifier::Type m_mt; } map[] = - { - // - { _T("S-"), Modifier::Type_Shift }, - { _T("A-"), Modifier::Type_Alt }, - { _T("M-"), Modifier::Type_Alt }, - { _T("C-"), Modifier::Type_Control }, - { _T("W-"), Modifier::Type_Windows }, - // - { _T("U-"), Modifier::Type_Up }, - { _T("D-"), Modifier::Type_Down }, - // - { _T("R-"), Modifier::Type_Repeat }, - { _T("IL-"), Modifier::Type_ImeLock }, - { _T("IC-"), Modifier::Type_ImeComp }, - { _T("I-"), Modifier::Type_ImeComp }, - { _T("NL-"), Modifier::Type_NumLock }, - { _T("CL-"), Modifier::Type_CapsLock }, - { _T("SL-"), Modifier::Type_ScrollLock }, - { _T("KL-"), Modifier::Type_KanaLock }, - { _T("MAX-"), Modifier::Type_Maximized }, - { _T("MIN-"), Modifier::Type_Minimized }, - { _T("MMAX-"), Modifier::Type_MdiMaximized }, - { _T("MMIN-"), Modifier::Type_MdiMinimized }, - { _T("T-"), Modifier::Type_Touchpad }, - { _T("TS-"), Modifier::Type_TouchpadSticky }, - { _T("M0-"), Modifier::Type_Mod0 }, - { _T("M1-"), Modifier::Type_Mod1 }, - { _T("M2-"), Modifier::Type_Mod2 }, - { _T("M3-"), Modifier::Type_Mod3 }, - { _T("M4-"), Modifier::Type_Mod4 }, - { _T("M5-"), Modifier::Type_Mod5 }, - { _T("M6-"), Modifier::Type_Mod6 }, - { _T("M7-"), Modifier::Type_Mod7 }, - { _T("M8-"), Modifier::Type_Mod8 }, - { _T("M9-"), Modifier::Type_Mod9 }, - { _T("L0-"), Modifier::Type_Lock0 }, - { _T("L1-"), Modifier::Type_Lock1 }, - { _T("L2-"), Modifier::Type_Lock2 }, - { _T("L3-"), Modifier::Type_Lock3 }, - { _T("L4-"), Modifier::Type_Lock4 }, - { _T("L5-"), Modifier::Type_Lock5 }, - { _T("L6-"), Modifier::Type_Lock6 }, - { _T("L7-"), Modifier::Type_Lock7 }, - { _T("L8-"), Modifier::Type_Lock8 }, - { _T("L9-"), Modifier::Type_Lock9 }, - }; - - for (int i = 0; i < NUMBER_OF(map); ++ i) - if (*t == map[i].m_s) - { - getToken(); - Modifier::Type mt = map[i].m_mt; - if (static_cast(i_mode) <= static_cast(mt)) - throw ErrorMessage() << _T("`") << *t - << _T("': invalid modifier at this context."); - switch (flag) - { - case PRESS: i_modifier.press(mt); break; - case RELEASE: i_modifier.release(mt); break; - case DONTCARE: i_modifier.dontcare(mt); break; + Modifier::Type i_mode, Modifier i_modifier, Modifier::Type *o_mode) +{ + if (o_mode) + *o_mode = Modifier::Type_begin; + + Modifier isModifierSpecified; + enum { PRESS, RELEASE, DONTCARE } flag = PRESS; + + int i; + for (i = i_mode; i < Modifier::Type_ASSIGN; ++ i) { + i_modifier.dontcare(Modifier::Type(i)); + isModifierSpecified.on(Modifier::Type(i)); } - isModifierSpecified.on(mt); - flag = PRESS; - - if (o_mode && *o_mode < mt) - { - if (mt < Modifier::Type_BASIC) - *o_mode = Modifier::Type_BASIC; - else if (mt < Modifier::Type_KEYSEQ) - *o_mode = Modifier::Type_KEYSEQ; - else if (mt < Modifier::Type_ASSIGN) - *o_mode = Modifier::Type_ASSIGN; + + Token *t = NULL; + +continue_loop: + while (!isEOL()) { + t = lookToken(); + + const static struct { + const _TCHAR *m_s; + Modifier::Type m_mt; + } map[] = { + // + { _T("S-"), Modifier::Type_Shift }, + { _T("A-"), Modifier::Type_Alt }, + { _T("M-"), Modifier::Type_Alt }, + { _T("C-"), Modifier::Type_Control }, + { _T("W-"), Modifier::Type_Windows }, + // + { _T("U-"), Modifier::Type_Up }, + { _T("D-"), Modifier::Type_Down }, + // + { _T("R-"), Modifier::Type_Repeat }, + { _T("IL-"), Modifier::Type_ImeLock }, + { _T("IC-"), Modifier::Type_ImeComp }, + { _T("I-"), Modifier::Type_ImeComp }, + { _T("NL-"), Modifier::Type_NumLock }, + { _T("CL-"), Modifier::Type_CapsLock }, + { _T("SL-"), Modifier::Type_ScrollLock }, + { _T("KL-"), Modifier::Type_KanaLock }, + { _T("MAX-"), Modifier::Type_Maximized }, + { _T("MIN-"), Modifier::Type_Minimized }, + { _T("MMAX-"), Modifier::Type_MdiMaximized }, + { _T("MMIN-"), Modifier::Type_MdiMinimized }, + { _T("T-"), Modifier::Type_Touchpad }, + { _T("TS-"), Modifier::Type_TouchpadSticky }, + { _T("M0-"), Modifier::Type_Mod0 }, + { _T("M1-"), Modifier::Type_Mod1 }, + { _T("M2-"), Modifier::Type_Mod2 }, + { _T("M3-"), Modifier::Type_Mod3 }, + { _T("M4-"), Modifier::Type_Mod4 }, + { _T("M5-"), Modifier::Type_Mod5 }, + { _T("M6-"), Modifier::Type_Mod6 }, + { _T("M7-"), Modifier::Type_Mod7 }, + { _T("M8-"), Modifier::Type_Mod8 }, + { _T("M9-"), Modifier::Type_Mod9 }, + { _T("L0-"), Modifier::Type_Lock0 }, + { _T("L1-"), Modifier::Type_Lock1 }, + { _T("L2-"), Modifier::Type_Lock2 }, + { _T("L3-"), Modifier::Type_Lock3 }, + { _T("L4-"), Modifier::Type_Lock4 }, + { _T("L5-"), Modifier::Type_Lock5 }, + { _T("L6-"), Modifier::Type_Lock6 }, + { _T("L7-"), Modifier::Type_Lock7 }, + { _T("L8-"), Modifier::Type_Lock8 }, + { _T("L9-"), Modifier::Type_Lock9 }, + }; + + for (int i = 0; i < NUMBER_OF(map); ++ i) + if (*t == map[i].m_s) { + getToken(); + Modifier::Type mt = map[i].m_mt; + if (static_cast(i_mode) <= static_cast(mt)) + throw ErrorMessage() << _T("`") << *t + << _T("': invalid modifier at this context."); + switch (flag) { + case PRESS: + i_modifier.press(mt); + break; + case RELEASE: + i_modifier.release(mt); + break; + case DONTCARE: + i_modifier.dontcare(mt); + break; + } + isModifierSpecified.on(mt); + flag = PRESS; + + if (o_mode && *o_mode < mt) { + if (mt < Modifier::Type_BASIC) + *o_mode = Modifier::Type_BASIC; + else if (mt < Modifier::Type_KEYSEQ) + *o_mode = Modifier::Type_KEYSEQ; + else if (mt < Modifier::Type_ASSIGN) + *o_mode = Modifier::Type_ASSIGN; + } + goto continue_loop; + } + + if (*t == _T("*")) { + getToken(); + flag = DONTCARE; + continue; + } + + if (*t == _T("~")) { + getToken(); + flag = RELEASE; + continue; + } + + break; } - goto continue_loop; - } - - if (*t == _T("*")) - { - getToken(); - flag = DONTCARE; - continue; - } - - if (*t == _T("~")) - { - getToken(); - flag = RELEASE; - continue; - } - - break; - } - - for (i = Modifier::Type_begin; i != Modifier::Type_end; ++ i) - if (!isModifierSpecified.isOn(Modifier::Type(i))) - switch (flag) - { - case PRESS: break; - case RELEASE: i_modifier.release(Modifier::Type(i)); break; - case DONTCARE: i_modifier.dontcare(Modifier::Type(i)); break; - } - - // fix up and down - bool isDontcareUp = i_modifier.isDontcare(Modifier::Type_Up); - bool isDontcareDown = i_modifier.isDontcare(Modifier::Type_Down); - bool isOnUp = i_modifier.isOn(Modifier::Type_Up); - bool isOnDown = i_modifier.isOn(Modifier::Type_Down); - if (isDontcareUp && isDontcareDown) - ; - else if (isDontcareUp) - i_modifier.on(Modifier::Type_Up, !isOnDown); - else if (isDontcareDown) - i_modifier.on(Modifier::Type_Down, !isOnUp); - else if (isOnUp == isOnDown) - { - i_modifier.dontcare(Modifier::Type_Up); - i_modifier.dontcare(Modifier::Type_Down); - } - - // fix repeat - if (!isModifierSpecified.isOn(Modifier::Type_Repeat)) - i_modifier.dontcare(Modifier::Type_Repeat); - return i_modifier; + + for (i = Modifier::Type_begin; i != Modifier::Type_end; ++ i) + if (!isModifierSpecified.isOn(Modifier::Type(i))) + switch (flag) { + case PRESS: + break; + case RELEASE: + i_modifier.release(Modifier::Type(i)); + break; + case DONTCARE: + i_modifier.dontcare(Modifier::Type(i)); + break; + } + + // fix up and down + bool isDontcareUp = i_modifier.isDontcare(Modifier::Type_Up); + bool isDontcareDown = i_modifier.isDontcare(Modifier::Type_Down); + bool isOnUp = i_modifier.isOn(Modifier::Type_Up); + bool isOnDown = i_modifier.isOn(Modifier::Type_Down); + if (isDontcareUp && isDontcareDown) + ; + else if (isDontcareUp) + i_modifier.on(Modifier::Type_Up, !isOnDown); + else if (isDontcareDown) + i_modifier.on(Modifier::Type_Down, !isOnUp); + else if (isOnUp == isOnDown) { + i_modifier.dontcare(Modifier::Type_Up); + i_modifier.dontcare(Modifier::Type_Down); + } + + // fix repeat + if (!isModifierSpecified.isOn(Modifier::Type_Repeat)) + i_modifier.dontcare(Modifier::Type_Repeat); + return i_modifier; } // Key *SettingLoader::load_KEY_NAME() { - Token *t = getToken(); - Key *key = m_setting->m_keyboard.searchKey(t->getString()); - if (!key) - throw ErrorMessage() << _T("`") << *t << _T("': invalid key name."); - return key; + Token *t = getToken(); + Key *key = m_setting->m_keyboard.searchKey(t->getString()); + if (!key) + throw ErrorMessage() << _T("`") << *t << _T("': invalid key name."); + return key; } // void SettingLoader::load_KEYMAP_DEFINITION(const Token *i_which) { - Keymap::Type type = Keymap::Type_keymap; - Token *name = getToken(); // - tstringi windowClassName; - tstringi windowTitleName; - KeySeq *keySeq = NULL; - Keymap *parentKeymap = NULL; - bool isKeymap2 = false; - bool doesLoadDefaultKeySeq = false; - - if (!isEOL()) - { - Token *t = lookToken(); - if (*i_which == _T("window")) // - { - if (t->isOpenParen()) - // "(" "&&" ")" - // "(" "||" ")" - { - getToken(); - windowClassName = getToken()->getRegexp(); - t = getToken(); - if (*t == _T("&&")) - type = Keymap::Type_windowAnd; - else if (*t == _T("||")) - type = Keymap::Type_windowOr; - else - throw ErrorMessage() << _T("`") << *t << _T("': unknown operator."); - windowTitleName = getToken()->getRegexp(); - if (!getToken()->isCloseParen()) - throw ErrorMessage() << _T("there must be `)'."); - } - else if (t->isRegexp()) // - { - getToken(); - type = Keymap::Type_windowAnd; - windowClassName = t->getRegexp(); - } - } - else if (*i_which == _T("keymap")) - ; - else if (*i_which == _T("keymap2")) - isKeymap2 = true; - else - ASSERT(false); - - if (!isEOL()) - doesLoadDefaultKeySeq = true; - } - - m_currentKeymap = m_setting->m_keymaps.add( - Keymap(type, name->getString(), windowClassName, windowTitleName, - NULL, NULL)); - - if (doesLoadDefaultKeySeq) - { - Token *t = lookToken(); - // - if (*t == _T(":")) - { - getToken(); - t = getToken(); - parentKeymap = m_setting->m_keymaps.searchByName(t->getString()); - if (!parentKeymap) - throw ErrorMessage() << _T("`") << *t - << _T("': unknown keymap name."); - } - if (!isEOL()) - { - t = getToken(); - if (!(*t == _T("=>") || *t == _T("="))) - throw ErrorMessage() << _T("`") << *t << _T("': syntax error."); - keySeq = SettingLoader::load_KEY_SEQUENCE(); - } - } - if (keySeq == NULL) - { - FunctionData *fd; - if (type == Keymap::Type_keymap && !isKeymap2) - fd = createFunctionData(_T("KeymapParent")); - else if (type == Keymap::Type_keymap && !isKeymap2) - fd = createFunctionData(_T("Undefined")); - else // (type == Keymap::Type_windowAnd || type == Keymap::Type_windowOr) - fd = createFunctionData(_T("KeymapParent")); - ASSERT( fd ); - keySeq = m_setting->m_keySeqs.add( - KeySeq(name->getString()).add(ActionFunction(fd))); - } - - m_currentKeymap->setIfNotYet(keySeq, parentKeymap); + Keymap::Type type = Keymap::Type_keymap; + Token *name = getToken(); // + tstringi windowClassName; + tstringi windowTitleName; + KeySeq *keySeq = NULL; + Keymap *parentKeymap = NULL; + bool isKeymap2 = false; + bool doesLoadDefaultKeySeq = false; + + if (!isEOL()) { + Token *t = lookToken(); + if (*i_which == _T("window")) { // + if (t->isOpenParen()) + // "(" "&&" ")" + // "(" "||" ")" + { + getToken(); + windowClassName = getToken()->getRegexp(); + t = getToken(); + if (*t == _T("&&")) + type = Keymap::Type_windowAnd; + else if (*t == _T("||")) + type = Keymap::Type_windowOr; + else + throw ErrorMessage() << _T("`") << *t << _T("': unknown operator."); + windowTitleName = getToken()->getRegexp(); + if (!getToken()->isCloseParen()) + throw ErrorMessage() << _T("there must be `)'."); + } else if (t->isRegexp()) { // + getToken(); + type = Keymap::Type_windowAnd; + windowClassName = t->getRegexp(); + } + } else if (*i_which == _T("keymap")) + ; + else if (*i_which == _T("keymap2")) + isKeymap2 = true; + else + ASSERT(false); + + if (!isEOL()) + doesLoadDefaultKeySeq = true; + } + + m_currentKeymap = m_setting->m_keymaps.add( + Keymap(type, name->getString(), windowClassName, windowTitleName, + NULL, NULL)); + + if (doesLoadDefaultKeySeq) { + Token *t = lookToken(); + // + if (*t == _T(":")) { + getToken(); + t = getToken(); + parentKeymap = m_setting->m_keymaps.searchByName(t->getString()); + if (!parentKeymap) + throw ErrorMessage() << _T("`") << *t + << _T("': unknown keymap name."); + } + if (!isEOL()) { + t = getToken(); + if (!(*t == _T("=>") || *t == _T("="))) + throw ErrorMessage() << _T("`") << *t << _T("': syntax error."); + keySeq = SettingLoader::load_KEY_SEQUENCE(); + } + } + if (keySeq == NULL) { + FunctionData *fd; + if (type == Keymap::Type_keymap && !isKeymap2) + fd = createFunctionData(_T("KeymapParent")); + else if (type == Keymap::Type_keymap && !isKeymap2) + fd = createFunctionData(_T("Undefined")); + else // (type == Keymap::Type_windowAnd || type == Keymap::Type_windowOr) + fd = createFunctionData(_T("KeymapParent")); + ASSERT( fd ); + keySeq = m_setting->m_keySeqs.add( + KeySeq(name->getString()).add(ActionFunction(fd))); + } + + m_currentKeymap->setIfNotYet(keySeq, parentKeymap); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(bool *o_arg) { - *o_arg = !(*getToken() == _T("false")); + *o_arg = !(*getToken() == _T("false")); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(int *o_arg) { - *o_arg = getToken()->getNumber(); + *o_arg = getToken()->getNumber(); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(unsigned int *o_arg) { - *o_arg = getToken()->getNumber(); + *o_arg = getToken()->getNumber(); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(long *o_arg) { - *o_arg = getToken()->getNumber(); + *o_arg = getToken()->getNumber(); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(unsigned __int64 *o_arg) { - *o_arg = getToken()->getNumber(); + *o_arg = getToken()->getNumber(); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(__int64 *o_arg) { - *o_arg = getToken()->getNumber(); + *o_arg = getToken()->getNumber(); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(tstringq *o_arg) { - *o_arg = getToken()->getString(); + *o_arg = getToken()->getString(); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(std::list *o_arg) { - while (true) - { - if (!lookToken()->isString()) - return; - o_arg->push_back(getToken()->getString()); - - if (!lookToken()->isComma()) - return; - getToken(); - } + while (true) { + if (!lookToken()->isString()) + return; + o_arg->push_back(getToken()->getString()); + + if (!lookToken()->isComma()) + return; + getToken(); + } } // <ARGUMENT> void SettingLoader::load_ARGUMENT(tregex *o_arg) { - *o_arg = getToken()->getRegexp(); + *o_arg = getToken()->getRegexp(); } // <ARGUMENT_VK> void SettingLoader::load_ARGUMENT(VKey *o_arg) { - Token *t = getToken(); - int vkey = 0; - while (true) - { - if (t->isNumber()) { vkey |= static_cast(t->getNumber()); break; } - else if (*t == _T("E-")) vkey |= VKey_extended; - else if (*t == _T("U-")) vkey |= VKey_released; - else if (*t == _T("D-")) vkey |= VKey_pressed; - else - { - const VKeyTable *vkt; - for (vkt = g_vkeyTable; vkt->m_name; ++ vkt) - if (*t == vkt->m_name) - break; - if (!vkt->m_name) - throw ErrorMessage() << _T("`") << *t - << _T("': unknown virtual key name."); - vkey |= vkt->m_code; - break; - } - t = getToken(); - } - if (!(vkey & VKey_released) && !(vkey & VKey_pressed)) - vkey |= VKey_released | VKey_pressed; - *o_arg = static_cast(vkey); + Token *t = getToken(); + int vkey = 0; + while (true) { + if (t->isNumber()) { + vkey |= static_cast(t->getNumber()); + break; + } else if (*t == _T("E-")) vkey |= VKey_extended; + else if (*t == _T("U-")) vkey |= VKey_released; + else if (*t == _T("D-")) vkey |= VKey_pressed; + else { + const VKeyTable *vkt; + for (vkt = g_vkeyTable; vkt->m_name; ++ vkt) + if (*t == vkt->m_name) + break; + if (!vkt->m_name) + throw ErrorMessage() << _T("`") << *t + << _T("': unknown virtual key name."); + vkey |= vkt->m_code; + break; + } + t = getToken(); + } + if (!(vkey & VKey_released) && !(vkey & VKey_pressed)) + vkey |= VKey_released | VKey_pressed; + *o_arg = static_cast(vkey); } // <ARGUMENT_WINDOW> void SettingLoader::load_ARGUMENT(ToWindowType *o_arg) { - Token *t = getToken(); - if (t->isNumber()) - { - if (ToWindowType_toBegin <= t->getNumber()) - { - *o_arg = static_cast(t->getNumber()); - return; - } - } - else if (getTypeValue(o_arg, t->getString())) - return; - throw ErrorMessage() << _T("`") << *t << _T("': invalid target window."); + Token *t = getToken(); + if (t->isNumber()) { + if (ToWindowType_toBegin <= t->getNumber()) { + *o_arg = static_cast(t->getNumber()); + return; + } + } else if (getTypeValue(o_arg, t->getString())) + return; + throw ErrorMessage() << _T("`") << *t << _T("': invalid target window."); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(GravityType *o_arg) { - Token *t = getToken(); - if (getTypeValue(o_arg, t->getString())) - return; - throw ErrorMessage() << _T("`") << *t << _T("': unknown gravity symbol."); + Token *t = getToken(); + if (getTypeValue(o_arg, t->getString())) + return; + throw ErrorMessage() << _T("`") << *t << _T("': unknown gravity symbol."); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(MouseHookType *o_arg) { - Token *t = getToken(); - if (getTypeValue(o_arg, t->getString())) - return; - throw ErrorMessage() << _T("`") << *t << _T("': unknown MouseHookType symbol."); + Token *t = getToken(); + if (getTypeValue(o_arg, t->getString())) + return; + throw ErrorMessage() << _T("`") << *t << _T("': unknown MouseHookType symbol."); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(MayuDialogType *o_arg) { - Token *t = getToken(); - if (getTypeValue(o_arg, t->getString())) - return; - throw ErrorMessage() << _T("`") << *t << _T("': unknown dialog box."); + Token *t = getToken(); + if (getTypeValue(o_arg, t->getString())) + return; + throw ErrorMessage() << _T("`") << *t << _T("': unknown dialog box."); } // <ARGUMENT_LOCK> void SettingLoader::load_ARGUMENT(ModifierLockType *o_arg) { - Token *t = getToken(); - if (getTypeValue(o_arg, t->getString())) - return; - throw ErrorMessage() << _T("`") << *t << _T("': unknown lock name."); + Token *t = getToken(); + if (getTypeValue(o_arg, t->getString())) + return; + throw ErrorMessage() << _T("`") << *t << _T("': unknown lock name."); } // <ARGUMENT_LOCK> void SettingLoader::load_ARGUMENT(ToggleType *o_arg) { - Token *t = getToken(); - if (getTypeValue(o_arg, t->getString())) - return; - throw ErrorMessage() << _T("`") << *t << _T("': unknown toggle name."); + Token *t = getToken(); + if (getTypeValue(o_arg, t->getString())) + return; + throw ErrorMessage() << _T("`") << *t << _T("': unknown toggle name."); } // <ARGUMENT_SHOW_WINDOW> void SettingLoader::load_ARGUMENT(ShowCommandType *o_arg) { - Token *t = getToken(); - if (getTypeValue(o_arg, t->getString())) - return; - throw ErrorMessage() << _T("`") << *t << _T("': unknown show command."); + Token *t = getToken(); + if (getTypeValue(o_arg, t->getString())) + return; + throw ErrorMessage() << _T("`") << *t << _T("': unknown show command."); } // <ARGUMENT_TARGET_WINDOW> void SettingLoader::load_ARGUMENT(TargetWindowType *o_arg) { - Token *t = getToken(); - if (getTypeValue(o_arg, t->getString())) - return; - throw ErrorMessage() << _T("`") << *t - << _T("': unknown target window type."); + Token *t = getToken(); + if (getTypeValue(o_arg, t->getString())) + return; + throw ErrorMessage() << _T("`") << *t + << _T("': unknown target window type."); } // <bool> void SettingLoader::load_ARGUMENT(BooleanType *o_arg) { - Token *t = getToken(); - if (getTypeValue(o_arg, t->getString())) - return; - throw ErrorMessage() << _T("`") << *t << _T("': must be true or false."); + Token *t = getToken(); + if (getTypeValue(o_arg, t->getString())) + return; + throw ErrorMessage() << _T("`") << *t << _T("': must be true or false."); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(LogicalOperatorType *o_arg) { - Token *t = getToken(); - if (getTypeValue(o_arg, t->getString())) - return; - throw ErrorMessage() << _T("`") << *t << _T("': must be 'or' or 'and'."); + Token *t = getToken(); + if (getTypeValue(o_arg, t->getString())) + return; + throw ErrorMessage() << _T("`") << *t << _T("': must be 'or' or 'and'."); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(Modifier *o_arg) { - Modifier modifier; - for (int i = Modifier::Type_begin; i != Modifier::Type_end; ++ i) - modifier.dontcare(static_cast(i)); - *o_arg = load_MODIFIER(Modifier::Type_ASSIGN, modifier); + Modifier modifier; + for (int i = Modifier::Type_begin; i != Modifier::Type_end; ++ i) + modifier.dontcare(static_cast(i)); + *o_arg = load_MODIFIER(Modifier::Type_ASSIGN, modifier); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(const Keymap **o_arg) { - Token *t = getToken(); - const Keymap *&keymap = *o_arg; - keymap = m_setting->m_keymaps.searchByName(t->getString()); - if (!keymap) - throw ErrorMessage() << _T("`") << *t << _T("': unknown keymap name."); + Token *t = getToken(); + const Keymap *&keymap = *o_arg; + keymap = m_setting->m_keymaps.searchByName(t->getString()); + if (!keymap) + throw ErrorMessage() << _T("`") << *t << _T("': unknown keymap name."); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(const KeySeq **o_arg) { - Token *t = getToken(); - const KeySeq *&keySeq = *o_arg; - if (t->isOpenParen()) - { - keySeq = load_KEY_SEQUENCE(_T(""), true); - getToken(); // close paren - } - else if (*t == _T("$")) - { - t = getToken(); - keySeq = m_setting->m_keySeqs.searchByName(t->getString()); - if (!keySeq) - throw ErrorMessage() << _T("`$") << *t << _T("': unknown keyseq name."); - } - else - throw ErrorMessage() << _T("`") << *t << _T("': it is not keyseq."); + Token *t = getToken(); + const KeySeq *&keySeq = *o_arg; + if (t->isOpenParen()) { + keySeq = load_KEY_SEQUENCE(_T(""), true); + getToken(); // close paren + } else if (*t == _T("$")) { + t = getToken(); + keySeq = m_setting->m_keySeqs.searchByName(t->getString()); + if (!keySeq) + throw ErrorMessage() << _T("`$") << *t << _T("': unknown keyseq name."); + } else + throw ErrorMessage() << _T("`") << *t << _T("': it is not keyseq."); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(StrExprArg *o_arg) { - Token *t = getToken(); - StrExprArg::Type type = StrExprArg::Literal; - if (*t == _T("$") && t->isQuoted() == false - && lookToken()->getType() == Token::Type_string) - { - type = StrExprArg::Builtin; - t = getToken(); - } - *o_arg = StrExprArg(t->getString(), type); + Token *t = getToken(); + StrExprArg::Type type = StrExprArg::Literal; + if (*t == _T("$") && t->isQuoted() == false + && lookToken()->getType() == Token::Type_string) { + type = StrExprArg::Builtin; + t = getToken(); + } + *o_arg = StrExprArg(t->getString(), type); } // <ARGUMENT> void SettingLoader::load_ARGUMENT(WindowMonitorFromType *o_arg) { - Token *t = getToken(); - if (getTypeValue(o_arg, t->getString())) - return; - throw ErrorMessage() << _T("`") << *t - << _T("': unknown monitor from type."); + Token *t = getToken(); + if (getTypeValue(o_arg, t->getString())) + return; + throw ErrorMessage() << _T("`") << *t + << _T("': unknown monitor from type."); } // KeySeq *SettingLoader::load_KEY_SEQUENCE( - const tstringi &i_name, bool i_isInParen, Modifier::Type i_mode) -{ - KeySeq keySeq(i_name); - while (!isEOL()) - { - Modifier::Type mode; - Modifier modifier = load_MODIFIER(i_mode, m_defaultKeySeqModifier, &mode); - keySeq.setMode(mode); - Token *t = lookToken(); - if (t->isCloseParen() && i_isInParen) - break; - else if (t->isOpenParen()) - { - getToken(); // open paren - KeySeq *ks = load_KEY_SEQUENCE(_T(""), true, i_mode); - getToken(); // close paren - keySeq.add(ActionKeySeq(ks)); - } - else if (*t == _T("$")) // - { - getToken(); - t = getToken(); - KeySeq *ks = m_setting->m_keySeqs.searchByName(t->getString()); - if (ks == NULL) - throw ErrorMessage() << _T("`$") << *t - << _T("': unknown keyseq name."); - if (!ks->isCorrectMode(i_mode)) - throw ErrorMessage() - << _T("`$") << *t - << _T("': Some of R-, IL-, IC-, NL-, CL-, SL-, KL-, MAX-, MIN-, MMAX-, MMIN-, T-, TS-, M0...M9- and L0...L9- are used in the keyseq. They are prohibited in this context."); - keySeq.setMode(ks->getMode()); - keySeq.add(ActionKeySeq(ks)); - } - else if (*t == _T("&")) // - { - getToken(); - t = getToken(); - - // search function - ActionFunction af(createFunctionData(t->getString()), modifier); - if (af.m_functionData == NULL) - throw ErrorMessage() << _T("`&") << *t - << _T("': unknown function name."); - af.m_functionData->load(this); - keySeq.add(af); - } - else // - { - ModifiedKey mkey; - mkey.m_modifier = modifier; - mkey.m_key = load_KEY_NAME(); - keySeq.add(ActionKey(mkey)); - } - } - return m_setting->m_keySeqs.add(keySeq); + const tstringi &i_name, bool i_isInParen, Modifier::Type i_mode) +{ + KeySeq keySeq(i_name); + while (!isEOL()) { + Modifier::Type mode; + Modifier modifier = load_MODIFIER(i_mode, m_defaultKeySeqModifier, &mode); + keySeq.setMode(mode); + Token *t = lookToken(); + if (t->isCloseParen() && i_isInParen) + break; + else if (t->isOpenParen()) { + getToken(); // open paren + KeySeq *ks = load_KEY_SEQUENCE(_T(""), true, i_mode); + getToken(); // close paren + keySeq.add(ActionKeySeq(ks)); + } else if (*t == _T("$")) { // + getToken(); + t = getToken(); + KeySeq *ks = m_setting->m_keySeqs.searchByName(t->getString()); + if (ks == NULL) + throw ErrorMessage() << _T("`$") << *t + << _T("': unknown keyseq name."); + if (!ks->isCorrectMode(i_mode)) + throw ErrorMessage() + << _T("`$") << *t + << _T("': Some of R-, IL-, IC-, NL-, CL-, SL-, KL-, MAX-, MIN-, MMAX-, MMIN-, T-, TS-, M0...M9- and L0...L9- are used in the keyseq. They are prohibited in this context."); + keySeq.setMode(ks->getMode()); + keySeq.add(ActionKeySeq(ks)); + } else if (*t == _T("&")) { // + getToken(); + t = getToken(); + + // search function + ActionFunction af(createFunctionData(t->getString()), modifier); + if (af.m_functionData == NULL) + throw ErrorMessage() << _T("`&") << *t + << _T("': unknown function name."); + af.m_functionData->load(this); + keySeq.add(af); + } else { // + ModifiedKey mkey; + mkey.m_modifier = modifier; + mkey.m_key = load_KEY_NAME(); + keySeq.add(ActionKey(mkey)); + } + } + return m_setting->m_keySeqs.add(keySeq); } // void SettingLoader::load_KEY_ASSIGN() { - typedef std::list AssignedKeys; - AssignedKeys assignedKeys; - - ModifiedKey mkey; - mkey.m_modifier = - load_MODIFIER(Modifier::Type_ASSIGN, m_defaultAssignModifier); - if (*lookToken() == _T("=")) - { - getToken(); - m_defaultKeySeqModifier = load_MODIFIER(Modifier::Type_KEYSEQ, - m_defaultKeySeqModifier); - m_defaultAssignModifier = mkey.m_modifier; - return; - } - - while (true) - { - mkey.m_key = load_KEY_NAME(); - assignedKeys.push_back(mkey); - if (*lookToken() == _T("=>") || *lookToken() == _T("=")) - break; - mkey.m_modifier = - load_MODIFIER(Modifier::Type_ASSIGN, m_defaultAssignModifier); - } - getToken(); - - ASSERT(m_currentKeymap); - KeySeq *keySeq = load_KEY_SEQUENCE(); - for (AssignedKeys::iterator i = assignedKeys.begin(); - i != assignedKeys.end(); ++ i) - m_currentKeymap->addAssignment(*i, keySeq); + typedef std::list AssignedKeys; + AssignedKeys assignedKeys; + + ModifiedKey mkey; + mkey.m_modifier = + load_MODIFIER(Modifier::Type_ASSIGN, m_defaultAssignModifier); + if (*lookToken() == _T("=")) { + getToken(); + m_defaultKeySeqModifier = load_MODIFIER(Modifier::Type_KEYSEQ, + m_defaultKeySeqModifier); + m_defaultAssignModifier = mkey.m_modifier; + return; + } + + while (true) { + mkey.m_key = load_KEY_NAME(); + assignedKeys.push_back(mkey); + if (*lookToken() == _T("=>") || *lookToken() == _T("=")) + break; + mkey.m_modifier = + load_MODIFIER(Modifier::Type_ASSIGN, m_defaultAssignModifier); + } + getToken(); + + ASSERT(m_currentKeymap); + KeySeq *keySeq = load_KEY_SEQUENCE(); + for (AssignedKeys::iterator i = assignedKeys.begin(); + i != assignedKeys.end(); ++ i) + m_currentKeymap->addAssignment(*i, keySeq); } // void SettingLoader::load_EVENT_ASSIGN() { - std::list assignedKeys; + std::list assignedKeys; - ModifiedKey mkey; - mkey.m_modifier.dontcare(); //set all modifiers to dontcare - - Token *t = getToken(); - Key **e; - for (e = Event::events; *e; ++ e) - if (*t == (*e)->getName()) - { - mkey.m_key = *e; - break; - } - if (!*e) - throw ErrorMessage() << _T("`") << *t << _T("': invalid event name."); + ModifiedKey mkey; + mkey.m_modifier.dontcare(); //set all modifiers to dontcare - t = getToken(); - if (!(*t == _T("=>") || *t == _T("="))) - throw ErrorMessage() << _T("`=' is expected."); + Token *t = getToken(); + Key **e; + for (e = Event::events; *e; ++ e) + if (*t == (*e)->getName()) { + mkey.m_key = *e; + break; + } + if (!*e) + throw ErrorMessage() << _T("`") << *t << _T("': invalid event name."); + + t = getToken(); + if (!(*t == _T("=>") || *t == _T("="))) + throw ErrorMessage() << _T("`=' is expected."); - ASSERT(m_currentKeymap); - KeySeq *keySeq = load_KEY_SEQUENCE(); - m_currentKeymap->addAssignment(mkey, keySeq); + ASSERT(m_currentKeymap); + KeySeq *keySeq = load_KEY_SEQUENCE(); + m_currentKeymap->addAssignment(mkey, keySeq); } // void SettingLoader::load_MODIFIER_ASSIGNMENT() { - // - Token *t = getToken(); - Modifier::Type mt; - - while (true) - { - Keymap::AssignMode am = Keymap::AM_notModifier; - if (*t == _T("!") ) am = Keymap::AM_true, t = getToken(); - else if (*t == _T("!!") ) am = Keymap::AM_oneShot, t = getToken(); - else if (*t == _T("!!!")) am = Keymap::AM_oneShotRepeatable, t = getToken(); - - if (*t == _T("shift")) mt = Modifier::Type_Shift; - else if (*t == _T("alt") || - *t == _T("meta") || - *t == _T("menu") ) mt = Modifier::Type_Alt; - else if (*t == _T("control") || - *t == _T("ctrl") ) mt = Modifier::Type_Control; - else if (*t == _T("windows") || - *t == _T("win") ) mt = Modifier::Type_Windows; - else if (*t == _T("mod0") ) mt = Modifier::Type_Mod0; - else if (*t == _T("mod1") ) mt = Modifier::Type_Mod1; - else if (*t == _T("mod2") ) mt = Modifier::Type_Mod2; - else if (*t == _T("mod3") ) mt = Modifier::Type_Mod3; - else if (*t == _T("mod4") ) mt = Modifier::Type_Mod4; - else if (*t == _T("mod5") ) mt = Modifier::Type_Mod5; - else if (*t == _T("mod6") ) mt = Modifier::Type_Mod6; - else if (*t == _T("mod7") ) mt = Modifier::Type_Mod7; - else if (*t == _T("mod8") ) mt = Modifier::Type_Mod8; - else if (*t == _T("mod9") ) mt = Modifier::Type_Mod9; - else throw ErrorMessage() << _T("`") << *t - << _T("': invalid modifier name."); - - if (am == Keymap::AM_notModifier) - break; - - m_currentKeymap->addModifier(mt, Keymap::AO_overwrite, am, NULL); - if (isEOL()) - return; - t = getToken(); - } - - // - t = getToken(); - Keymap::AssignOperator ao; - if (*t == _T("=") ) ao = Keymap::AO_new; - else if (*t == _T("+=")) ao = Keymap::AO_add; - else if (*t == _T("-=")) ao = Keymap::AO_sub; - else throw ErrorMessage() << _T("`") << *t << _T("': is unknown operator."); - - // ? - while (!isEOL()) - { - // ? - t = getToken(); - Keymap::AssignMode am = Keymap::AM_normal; - if (*t == _T("!") ) am = Keymap::AM_true, t = getToken(); - else if (*t == _T("!!") ) am = Keymap::AM_oneShot, t = getToken(); - else if (*t == _T("!!!")) am = Keymap::AM_oneShotRepeatable, t = getToken(); - - // - Key *key = m_setting->m_keyboard.searchKey(t->getString()); - if (!key) - throw ErrorMessage() << _T("`") << *t << _T("': invalid key name."); - - // we can ignore warning C4701 - m_currentKeymap->addModifier(mt, ao, am, key); - if (ao == Keymap::AO_new) - ao = Keymap::AO_add; - } + // + Token *t = getToken(); + Modifier::Type mt; + + while (true) { + Keymap::AssignMode am = Keymap::AM_notModifier; + if (*t == _T("!") ) am = Keymap::AM_true, t = getToken(); + else if (*t == _T("!!") ) am = Keymap::AM_oneShot, t = getToken(); + else if (*t == _T("!!!")) am = Keymap::AM_oneShotRepeatable, t = getToken(); + + if (*t == _T("shift")) mt = Modifier::Type_Shift; + else if (*t == _T("alt") || + *t == _T("meta") || + *t == _T("menu") ) mt = Modifier::Type_Alt; + else if (*t == _T("control") || + *t == _T("ctrl") ) mt = Modifier::Type_Control; + else if (*t == _T("windows") || + *t == _T("win") ) mt = Modifier::Type_Windows; + else if (*t == _T("mod0") ) mt = Modifier::Type_Mod0; + else if (*t == _T("mod1") ) mt = Modifier::Type_Mod1; + else if (*t == _T("mod2") ) mt = Modifier::Type_Mod2; + else if (*t == _T("mod3") ) mt = Modifier::Type_Mod3; + else if (*t == _T("mod4") ) mt = Modifier::Type_Mod4; + else if (*t == _T("mod5") ) mt = Modifier::Type_Mod5; + else if (*t == _T("mod6") ) mt = Modifier::Type_Mod6; + else if (*t == _T("mod7") ) mt = Modifier::Type_Mod7; + else if (*t == _T("mod8") ) mt = Modifier::Type_Mod8; + else if (*t == _T("mod9") ) mt = Modifier::Type_Mod9; + else throw ErrorMessage() << _T("`") << *t + << _T("': invalid modifier name."); + + if (am == Keymap::AM_notModifier) + break; + + m_currentKeymap->addModifier(mt, Keymap::AO_overwrite, am, NULL); + if (isEOL()) + return; + t = getToken(); + } + + // + t = getToken(); + Keymap::AssignOperator ao; + if (*t == _T("=") ) ao = Keymap::AO_new; + else if (*t == _T("+=")) ao = Keymap::AO_add; + else if (*t == _T("-=")) ao = Keymap::AO_sub; + else throw ErrorMessage() << _T("`") << *t << _T("': is unknown operator."); + + // ? + while (!isEOL()) { + // ? + t = getToken(); + Keymap::AssignMode am = Keymap::AM_normal; + if (*t == _T("!") ) am = Keymap::AM_true, t = getToken(); + else if (*t == _T("!!") ) am = Keymap::AM_oneShot, t = getToken(); + else if (*t == _T("!!!")) am = Keymap::AM_oneShotRepeatable, t = getToken(); + + // + Key *key = m_setting->m_keyboard.searchKey(t->getString()); + if (!key) + throw ErrorMessage() << _T("`") << *t << _T("': invalid key name."); + + // we can ignore warning C4701 + m_currentKeymap->addModifier(mt, ao, am, key); + if (ao == Keymap::AO_new) + ao = Keymap::AO_add; + } } // void SettingLoader::load_KEYSEQ_DEFINITION() { - if (*getToken() != _T("$")) - throw ErrorMessage() << _T("there must be `$' after `keyseq'"); - Token *name = getToken(); - if (*getToken() != _T("=")) - throw ErrorMessage() << _T("there must be `=' after keyseq naem"); - load_KEY_SEQUENCE(name->getString(), false, Modifier::Type_ASSIGN); + if (*getToken() != _T("$")) + throw ErrorMessage() << _T("there must be `$' after `keyseq'"); + Token *name = getToken(); + if (*getToken() != _T("=")) + throw ErrorMessage() << _T("there must be `=' after keyseq naem"); + load_KEY_SEQUENCE(name->getString(), false, Modifier::Type_ASSIGN); } // void SettingLoader::load_DEFINE() { - m_setting->m_symbols.insert(getToken()->getString()); + m_setting->m_symbols.insert(getToken()->getString()); } // void SettingLoader::load_IF() { - if (!getToken()->isOpenParen()) - throw ErrorMessage() << _T("there must be `(' after `if'."); - Token *t = getToken(); // or ! - bool not = false; - if (*t == _T("!")) - { - not = true; - t = getToken(); // - } - - bool doesSymbolExist = (m_setting->m_symbols.find(t->getString()) - != m_setting->m_symbols.end()); - bool doesRead = ((doesSymbolExist && !not) || - (!doesSymbolExist && not)); - if (0 < m_canReadStack.size()) - doesRead = doesRead && m_canReadStack.back(); - - if (!getToken()->isCloseParen()) - throw ErrorMessage() << _T("there must be `)'."); - - m_canReadStack.push_back(doesRead); - if (!isEOL()) - { - size_t len = m_canReadStack.size(); - load_LINE(); - if (len < m_canReadStack.size()) - { - bool r = m_canReadStack.back(); - m_canReadStack.pop_back(); - m_canReadStack[len - 1] = r && doesRead; - } - else if (len == m_canReadStack.size()) - m_canReadStack.pop_back(); - else - ; // `end' found - } + if (!getToken()->isOpenParen()) + throw ErrorMessage() << _T("there must be `(' after `if'."); + Token *t = getToken(); // or ! + bool not = false; + if (*t == _T("!")) { + not = true; + t = getToken(); // + } + + bool doesSymbolExist = (m_setting->m_symbols.find(t->getString()) + != m_setting->m_symbols.end()); + bool doesRead = ((doesSymbolExist && !not) || + (!doesSymbolExist && not)); + if (0 < m_canReadStack.size()) + doesRead = doesRead && m_canReadStack.back(); + + if (!getToken()->isCloseParen()) + throw ErrorMessage() << _T("there must be `)'."); + + m_canReadStack.push_back(doesRead); + if (!isEOL()) { + size_t len = m_canReadStack.size(); + load_LINE(); + if (len < m_canReadStack.size()) { + bool r = m_canReadStack.back(); + m_canReadStack.pop_back(); + m_canReadStack[len - 1] = r && doesRead; + } else if (len == m_canReadStack.size()) + m_canReadStack.pop_back(); + else + ; // `end' found + } } // void SettingLoader::load_ELSE(bool i_isElseIf, const tstringi &i_token) { - bool doesRead = !load_ENDIF(i_token); - if (0 < m_canReadStack.size()) - doesRead = doesRead && m_canReadStack.back(); - m_canReadStack.push_back(doesRead); - if (!isEOL()) - { - size_t len = m_canReadStack.size(); - if (i_isElseIf) - load_IF(); - else - load_LINE(); - if (len < m_canReadStack.size()) - { - bool r = m_canReadStack.back(); - m_canReadStack.pop_back(); - m_canReadStack[len - 1] = doesRead && r; - } - else if (len == m_canReadStack.size()) - m_canReadStack.pop_back(); - else - ; // `end' found - } + bool doesRead = !load_ENDIF(i_token); + if (0 < m_canReadStack.size()) + doesRead = doesRead && m_canReadStack.back(); + m_canReadStack.push_back(doesRead); + if (!isEOL()) { + size_t len = m_canReadStack.size(); + if (i_isElseIf) + load_IF(); + else + load_LINE(); + if (len < m_canReadStack.size()) { + bool r = m_canReadStack.back(); + m_canReadStack.pop_back(); + m_canReadStack[len - 1] = doesRead && r; + } else if (len == m_canReadStack.size()) + m_canReadStack.pop_back(); + else + ; // `end' found + } } // bool SettingLoader::load_ENDIF(const tstringi &i_token) { - if (m_canReadStack.size() == 0) - throw ErrorMessage() << _T("unbalanced `") << i_token << _T("'"); - bool r = m_canReadStack.back(); - m_canReadStack.pop_back(); - return r; + if (m_canReadStack.size() == 0) + throw ErrorMessage() << _T("unbalanced `") << i_token << _T("'"); + bool r = m_canReadStack.back(); + m_canReadStack.pop_back(); + return r; } // void SettingLoader::load_LINE() { - Token *i_token = getToken(); - - // - if (*i_token == _T("if") || - *i_token == _T("and")) load_IF(); - else if (*i_token == _T("else")) load_ELSE(false, i_token->getString()); - else if (*i_token == _T("elseif") || - *i_token == _T("elsif") || - *i_token == _T("elif") || - *i_token == _T("or")) load_ELSE(true, i_token->getString()); - else if (*i_token == _T("endif")) load_ENDIF(_T("endif")); - else if (0 < m_canReadStack.size() && !m_canReadStack.back()) - { - while (!isEOL()) - getToken(); - } - else if (*i_token == _T("define")) load_DEFINE(); - // - else if (*i_token == _T("include")) load_INCLUDE(); - // - else if (*i_token == _T("def")) load_KEYBOARD_DEFINITION(); - // - else if (*i_token == _T("keymap") || - *i_token == _T("keymap2") || - *i_token == _T("window")) load_KEYMAP_DEFINITION(i_token); - // - else if (*i_token == _T("key")) load_KEY_ASSIGN(); - // - else if (*i_token == _T("event")) load_EVENT_ASSIGN(); - // - else if (*i_token == _T("mod")) load_MODIFIER_ASSIGNMENT(); - // - else if (*i_token == _T("keyseq")) load_KEYSEQ_DEFINITION(); - else - throw ErrorMessage() << _T("syntax error `") << *i_token << _T("'."); -} - - + Token *i_token = getToken(); + + // + if (*i_token == _T("if") || + *i_token == _T("and")) load_IF(); + else if (*i_token == _T("else")) load_ELSE(false, i_token->getString()); + else if (*i_token == _T("elseif") || + *i_token == _T("elsif") || + *i_token == _T("elif") || + *i_token == _T("or")) load_ELSE(true, i_token->getString()); + else if (*i_token == _T("endif")) load_ENDIF(_T("endif")); + else if (0 < m_canReadStack.size() && !m_canReadStack.back()) { + while (!isEOL()) + getToken(); + } else if (*i_token == _T("define")) load_DEFINE(); + // + else if (*i_token == _T("include")) load_INCLUDE(); + // + else if (*i_token == _T("def")) load_KEYBOARD_DEFINITION(); + // + else if (*i_token == _T("keymap") || + *i_token == _T("keymap2") || + *i_token == _T("window")) load_KEYMAP_DEFINITION(i_token); + // + else if (*i_token == _T("key")) load_KEY_ASSIGN(); + // + else if (*i_token == _T("event")) load_EVENT_ASSIGN(); + // + else if (*i_token == _T("mod")) load_MODIFIER_ASSIGNMENT(); + // + else if (*i_token == _T("keyseq")) load_KEYSEQ_DEFINITION(); + else + throw ErrorMessage() << _T("syntax error `") << *i_token << _T("'."); +} + + // prefix sort predicate used in load(const string &) static bool prefixSortPred(const tstringi &i_a, const tstringi &i_b) { - return i_b.size() < i_a.size(); + return i_b.size() < i_a.size(); } @@ -1305,407 +1254,370 @@ static bool prefixSortPred(const tstringi &i_a, const tstringi &i_b) */ bool readFile(tstring *o_data, const tstringi &i_filename) { - // get size of file + // get size of file #if 0 - // bcc's _wstat cannot obtain file size - struct _stat sbuf; - if (_tstat(i_filename.c_str(), &sbuf) < 0 || sbuf.st_size == 0) - return false; + // bcc's _wstat cannot obtain file size + struct _stat sbuf; + if (_tstat(i_filename.c_str(), &sbuf) < 0 || sbuf.st_size == 0) + return false; #else - // so, we use _wstati64 for bcc - struct stati64_t sbuf; - if (_tstati64(i_filename.c_str(), &sbuf) < 0 || sbuf.st_size == 0) - return false; - // following check is needed to cast sbuf.st_size to size_t safely - // this cast occurs because of above workaround for bcc - if (sbuf.st_size > UINT_MAX) - return false; + // so, we use _wstati64 for bcc + struct stati64_t sbuf; + if (_tstati64(i_filename.c_str(), &sbuf) < 0 || sbuf.st_size == 0) + return false; + // following check is needed to cast sbuf.st_size to size_t safely + // this cast occurs because of above workaround for bcc + if (sbuf.st_size > UINT_MAX) + return false; #endif - - // open - FILE *fp = _tfopen(i_filename.c_str(), _T("rb")); - if (!fp) - return false; - - // read file - Array buf(static_cast(sbuf.st_size) + 1); - if (fread(buf.get(), static_cast(sbuf.st_size), 1, fp) != 1) - { - fclose(fp); - return false; - } - buf.get()[sbuf.st_size] = 0; // mbstowcs() requires null - // terminated string + + // open + FILE *fp = _tfopen(i_filename.c_str(), _T("rb")); + if (!fp) + return false; + + // read file + Array buf(static_cast(sbuf.st_size) + 1); + if (fread(buf.get(), static_cast(sbuf.st_size), 1, fp) != 1) { + fclose(fp); + return false; + } + buf.get()[sbuf.st_size] = 0; // mbstowcs() requires null + // terminated string #ifdef _UNICODE - // - if (buf.get()[0] == 0xffU && buf.get()[1] == 0xfeU && - sbuf.st_size % 2 == 0) - // UTF-16 Little Endien - { - size_t size = static_cast(sbuf.st_size) / 2; - o_data->resize(size); - BYTE *p = buf.get(); - for (size_t i = 0; i < size; ++ i) - { - wchar_t c = static_cast(*p ++); - c |= static_cast(*p ++) << 8; - (*o_data)[i] = c; - } - fclose(fp); - return true; - } - - // - if (buf.get()[0] == 0xfeU && buf.get()[1] == 0xffU && - sbuf.st_size % 2 == 0) - // UTF-16 Big Endien - { - size_t size = static_cast(sbuf.st_size) / 2; - o_data->resize(size); - BYTE *p = buf.get(); - for (size_t i = 0; i < size; ++ i) - { - wchar_t c = static_cast(*p ++) << 8; - c |= static_cast(*p ++); - (*o_data)[i] = c; - } - fclose(fp); - return true; - } - - // try multibyte charset - size_t wsize = mbstowcs(NULL, reinterpret_cast(buf.get()), 0); - if (wsize != size_t(-1)) - { - Array wbuf(wsize); - mbstowcs(wbuf.get(), reinterpret_cast(buf.get()), wsize); - o_data->assign(wbuf.get(), wbuf.get() + wsize); - fclose(fp); - return true; - } - - // try UTF-8 - { - Array wbuf(static_cast(sbuf.st_size)); - BYTE *f = buf.get(); - BYTE *end = buf.get() + sbuf.st_size; - wchar_t *d = wbuf.get(); - enum { STATE_1, STATE_2of2, STATE_2of3, STATE_3of3 } state = STATE_1; - - while (f != end) - { - switch (state) - { - case STATE_1: - if (!(*f & 0x80)) // 0xxxxxxx: 00-7F - *d++ = static_cast(*f++); - else if ((*f & 0xe0) == 0xc0) // 110xxxxx 10xxxxxx: 0080-07FF - { - *d = ((static_cast(*f++) & 0x1f) << 6); - state = STATE_2of2; - } - else if ((*f & 0xf0) == 0xe0) // 1110xxxx 10xxxxxx 10xxxxxx: - // 0800 - FFFF - { - *d = ((static_cast(*f++) & 0x0f) << 12); - state = STATE_2of3; - } - else - goto not_UTF_8; - break; - - case STATE_2of2: - case STATE_3of3: - if ((*f & 0xc0) != 0x80) - goto not_UTF_8; - *d++ |= (static_cast(*f++) & 0x3f); - state = STATE_1; - break; - - case STATE_2of3: - if ((*f & 0xc0) != 0x80) - goto not_UTF_8; - *d |= ((static_cast(*f++) & 0x3f) << 6); - state = STATE_3of3; - break; - } - } - o_data->assign(wbuf.get(), d); - fclose(fp); - return true; - - not_UTF_8: ; - } + // + if (buf.get()[0] == 0xffU && buf.get()[1] == 0xfeU && + sbuf.st_size % 2 == 0) + // UTF-16 Little Endien + { + size_t size = static_cast(sbuf.st_size) / 2; + o_data->resize(size); + BYTE *p = buf.get(); + for (size_t i = 0; i < size; ++ i) { + wchar_t c = static_cast(*p ++); + c |= static_cast(*p ++) << 8; + (*o_data)[i] = c; + } + fclose(fp); + return true; + } + + // + if (buf.get()[0] == 0xfeU && buf.get()[1] == 0xffU && + sbuf.st_size % 2 == 0) + // UTF-16 Big Endien + { + size_t size = static_cast(sbuf.st_size) / 2; + o_data->resize(size); + BYTE *p = buf.get(); + for (size_t i = 0; i < size; ++ i) { + wchar_t c = static_cast(*p ++) << 8; + c |= static_cast(*p ++); + (*o_data)[i] = c; + } + fclose(fp); + return true; + } + + // try multibyte charset + size_t wsize = mbstowcs(NULL, reinterpret_cast(buf.get()), 0); + if (wsize != size_t(-1)) { + Array wbuf(wsize); + mbstowcs(wbuf.get(), reinterpret_cast(buf.get()), wsize); + o_data->assign(wbuf.get(), wbuf.get() + wsize); + fclose(fp); + return true; + } + + // try UTF-8 + { + Array wbuf(static_cast(sbuf.st_size)); + BYTE *f = buf.get(); + BYTE *end = buf.get() + sbuf.st_size; + wchar_t *d = wbuf.get(); + enum { STATE_1, STATE_2of2, STATE_2of3, STATE_3of3 } state = STATE_1; + + while (f != end) { + switch (state) { + case STATE_1: + if (!(*f & 0x80)) // 0xxxxxxx: 00-7F + *d++ = static_cast(*f++); + else if ((*f & 0xe0) == 0xc0) { // 110xxxxx 10xxxxxx: 0080-07FF + *d = ((static_cast(*f++) & 0x1f) << 6); + state = STATE_2of2; + } else if ((*f & 0xf0) == 0xe0) // 1110xxxx 10xxxxxx 10xxxxxx: + // 0800 - FFFF + { + *d = ((static_cast(*f++) & 0x0f) << 12); + state = STATE_2of3; + } else + goto not_UTF_8; + break; + + case STATE_2of2: + case STATE_3of3: + if ((*f & 0xc0) != 0x80) + goto not_UTF_8; + *d++ |= (static_cast(*f++) & 0x3f); + state = STATE_1; + break; + + case STATE_2of3: + if ((*f & 0xc0) != 0x80) + goto not_UTF_8; + *d |= ((static_cast(*f++) & 0x3f) << 6); + state = STATE_3of3; + break; + } + } + o_data->assign(wbuf.get(), d); + fclose(fp); + return true; + +not_UTF_8: + ; + } #endif // _UNICODE - // assume ascii - o_data->resize(static_cast(sbuf.st_size)); - for (off_t i = 0; i < sbuf.st_size; ++ i) - (*o_data)[i] = buf.get()[i]; - fclose(fp); - return true; + // assume ascii + o_data->resize(static_cast(sbuf.st_size)); + for (off_t i = 0; i < sbuf.st_size; ++ i) + (*o_data)[i] = buf.get()[i]; + fclose(fp); + return true; } // load (called from load(Setting *, const tstringi &) only) void SettingLoader::load(const tstringi &i_filename) { - m_currentFilename = i_filename; - - tstring data; - if (!readFile(&data, m_currentFilename)) - { - Acquire a(m_soLog); - *m_log << m_currentFilename << _T(" : error: file not found") << std::endl; + m_currentFilename = i_filename; + + tstring data; + if (!readFile(&data, m_currentFilename)) { + Acquire a(m_soLog); + *m_log << m_currentFilename << _T(" : error: file not found") << std::endl; #if 1 - *m_log << data << std::endl; + *m_log << data << std::endl; #endif - m_isThereAnyError = true; - return; - } - - // prefix - if (m_prefixesRefCcount == 0) - { - static const _TCHAR *prefixes[] = - { - _T("="), _T("=>"), _T("&&"), _T("||"), _T(":"), _T("$"), _T("&"), - _T("-="), _T("+="), _T("!!!"), _T("!!"), _T("!"), - _T("E0-"), _T("E1-"), // - _T("S-"), _T("A-"), _T("M-"), _T("C-"), // - _T("W-"), _T("*"), _T("~"), - _T("U-"), _T("D-"), // - _T("R-"), _T("IL-"), _T("IC-"), _T("I-"), // - _T("NL-"), _T("CL-"), _T("SL-"), _T("KL-"), - _T("MAX-"), _T("MIN-"), _T("MMAX-"), _T("MMIN-"), - _T("T-"), _T("TS-"), - _T("M0-"), _T("M1-"), _T("M2-"), _T("M3-"), _T("M4-"), - _T("M5-"), _T("M6-"), _T("M7-"), _T("M8-"), _T("M9-"), - _T("L0-"), _T("L1-"), _T("L2-"), _T("L3-"), _T("L4-"), - _T("L5-"), _T("L6-"), _T("L7-"), _T("L8-"), _T("L9-"), - }; - m_prefixes = new std::vector; - for (size_t i = 0; i < NUMBER_OF(prefixes); ++ i) - m_prefixes->push_back(prefixes[i]); - std::sort(m_prefixes->begin(), m_prefixes->end(), prefixSortPred); - } - m_prefixesRefCcount ++; - - // create parser - Parser parser(data.c_str(), data.size()); - parser.setPrefixes(m_prefixes); - - while (true) - { - try - { - if (!parser.getLine(&m_tokens)) - break; - m_ti = m_tokens.begin(); - } - catch (ErrorMessage &e) - { - if (m_log && m_soLog) - { - Acquire a(m_soLog); - *m_log << m_currentFilename << _T("(") << parser.getLineNumber() - << _T(") : error: ") << e << std::endl; - } - m_isThereAnyError = true; - continue; - } - - try - { - load_LINE(); - if (!isEOL()) - throw WarningMessage() << _T("back garbage is ignored."); - } - catch (WarningMessage &w) - { - if (m_log && m_soLog) - { - Acquire a(m_soLog); - *m_log << i_filename << _T("(") << parser.getLineNumber() - << _T(") : warning: ") << w << std::endl; - } - } - catch (ErrorMessage &e) - { - if (m_log && m_soLog) - { - Acquire a(m_soLog); - *m_log << i_filename << _T("(") << parser.getLineNumber() - << _T(") : error: ") << e << std::endl; - } - m_isThereAnyError = true; - } - } - - // m_prefixes - -- m_prefixesRefCcount; - if (m_prefixesRefCcount == 0) - delete m_prefixes; - - if (0 < m_canReadStack.size()) - { - Acquire a(m_soLog); - *m_log << m_currentFilename << _T("(") << parser.getLineNumber() - << _T(") : error: unbalanced `if'. ") - << _T("you forget `endif', didn'i_token you?") - << std::endl; - m_isThereAnyError = true; - } + m_isThereAnyError = true; + return; + } + + // prefix + if (m_prefixesRefCcount == 0) { + static const _TCHAR *prefixes[] = { + _T("="), _T("=>"), _T("&&"), _T("||"), _T(":"), _T("$"), _T("&"), + _T("-="), _T("+="), _T("!!!"), _T("!!"), _T("!"), + _T("E0-"), _T("E1-"), // + _T("S-"), _T("A-"), _T("M-"), _T("C-"), // + _T("W-"), _T("*"), _T("~"), + _T("U-"), _T("D-"), // + _T("R-"), _T("IL-"), _T("IC-"), _T("I-"), // + _T("NL-"), _T("CL-"), _T("SL-"), _T("KL-"), + _T("MAX-"), _T("MIN-"), _T("MMAX-"), _T("MMIN-"), + _T("T-"), _T("TS-"), + _T("M0-"), _T("M1-"), _T("M2-"), _T("M3-"), _T("M4-"), + _T("M5-"), _T("M6-"), _T("M7-"), _T("M8-"), _T("M9-"), + _T("L0-"), _T("L1-"), _T("L2-"), _T("L3-"), _T("L4-"), + _T("L5-"), _T("L6-"), _T("L7-"), _T("L8-"), _T("L9-"), + }; + m_prefixes = new std::vector; + for (size_t i = 0; i < NUMBER_OF(prefixes); ++ i) + m_prefixes->push_back(prefixes[i]); + std::sort(m_prefixes->begin(), m_prefixes->end(), prefixSortPred); + } + m_prefixesRefCcount ++; + + // create parser + Parser parser(data.c_str(), data.size()); + parser.setPrefixes(m_prefixes); + + while (true) { + try { + if (!parser.getLine(&m_tokens)) + break; + m_ti = m_tokens.begin(); + } catch (ErrorMessage &e) { + if (m_log && m_soLog) { + Acquire a(m_soLog); + *m_log << m_currentFilename << _T("(") << parser.getLineNumber() + << _T(") : error: ") << e << std::endl; + } + m_isThereAnyError = true; + continue; + } + + try { + load_LINE(); + if (!isEOL()) + throw WarningMessage() << _T("back garbage is ignored."); + } catch (WarningMessage &w) { + if (m_log && m_soLog) { + Acquire a(m_soLog); + *m_log << i_filename << _T("(") << parser.getLineNumber() + << _T(") : warning: ") << w << std::endl; + } + } catch (ErrorMessage &e) { + if (m_log && m_soLog) { + Acquire a(m_soLog); + *m_log << i_filename << _T("(") << parser.getLineNumber() + << _T(") : error: ") << e << std::endl; + } + m_isThereAnyError = true; + } + } + + // m_prefixes + -- m_prefixesRefCcount; + if (m_prefixesRefCcount == 0) + delete m_prefixes; + + if (0 < m_canReadStack.size()) { + Acquire a(m_soLog); + *m_log << m_currentFilename << _T("(") << parser.getLineNumber() + << _T(") : error: unbalanced `if'. ") + << _T("you forget `endif', didn'i_token you?") + << std::endl; + m_isThereAnyError = true; + } } // is the filename readable ? bool SettingLoader::isReadable(const tstringi &i_filename, - int i_debugLevel) const + int i_debugLevel) const { - if (i_filename.empty()) - return false; + if (i_filename.empty()) + return false; #ifdef UNICODE - tifstream ist(to_string(i_filename).c_str()); + tifstream ist(to_string(i_filename).c_str()); #else - tifstream ist(i_filename.c_str()); + tifstream ist(i_filename.c_str()); #endif - if (ist.good()) - { - if (m_log && m_soLog) - { - Acquire a(m_soLog, 0); - *m_log << _T(" loading: ") << i_filename << std::endl; - } - return true; - } - else - { - if (m_log && m_soLog) - { - Acquire a(m_soLog, i_debugLevel); - *m_log << _T("not found: ") << i_filename << std::endl; - } - return false; - } + if (ist.good()) { + if (m_log && m_soLog) { + Acquire a(m_soLog, 0); + *m_log << _T(" loading: ") << i_filename << std::endl; + } + return true; + } else { + if (m_log && m_soLog) { + Acquire a(m_soLog, i_debugLevel); + *m_log << _T("not found: ") << i_filename << std::endl; + } + return false; + } } #if 0 // get filename from registry bool SettingLoader::getFilenameFromRegistry(tstringi *o_path) const { - // get from registry - Registry reg(MAYU_REGISTRY_ROOT); - int index; - reg.read(_T(".mayuIndex"), &index, 0); - char buf[100]; - snprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index); - if (!reg.read(buf, o_path)) - return false; - - // parse registry entry - Regexp getFilename(_T("^[^;]*;([^;]*);(.*)$")); - if (!getFilename.doesMatch(*o_path)) - return false; - - tstringi path = getFilename[1]; - tstringi options = getFilename[2]; - - if (!(0 < path.size() && isReadable(path))) - return false; - *o_path = path; - - // set symbols - Regexp symbol(_T("-D([^;]*)")); - while (symbol.doesMatch(options)) - { - m_setting->symbols.insert(symbol[1]); - options = options.substr(symbol.subBegin(1)); - } - - return true; + // get from registry + Registry reg(MAYU_REGISTRY_ROOT); + int index; + reg.read(_T(".mayuIndex"), &index, 0); + char buf[100]; + snprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index); + if (!reg.read(buf, o_path)) + return false; + + // parse registry entry + Regexp getFilename(_T("^[^;]*;([^;]*);(.*)$")); + if (!getFilename.doesMatch(*o_path)) + return false; + + tstringi path = getFilename[1]; + tstringi options = getFilename[2]; + + if (!(0 < path.size() && isReadable(path))) + return false; + *o_path = path; + + // set symbols + Regexp symbol(_T("-D([^;]*)")); + while (symbol.doesMatch(options)) { + m_setting->symbols.insert(symbol[1]); + options = options.substr(symbol.subBegin(1)); + } + + return true; } #endif // get filename bool SettingLoader::getFilename(const tstringi &i_name, tstringi *o_path, - int i_debugLevel) const -{ - // the default filename is ".mayu" - const tstringi &name = i_name.empty() ? tstringi(_T(".mayu")) : i_name; - - bool isFirstTime = true; - - while (true) - { - // find file from registry - if (i_name.empty()) // called not from 'include' - { - Setting::Symbols symbols; - if (getFilenameFromRegistry(NULL, o_path, &symbols)) - { - if (o_path->empty()) - // find file from home directory - { - HomeDirectories pathes; - getHomeDirectories(&pathes); - for (HomeDirectories::iterator - i = pathes.begin(); i != pathes.end(); ++ i) - { - *o_path = *i + _T("\\") + name; - if (isReadable(*o_path, i_debugLevel)) - goto add_symbols; - } - return false; + int i_debugLevel) const +{ + // the default filename is ".mayu" + const tstringi &name = i_name.empty() ? tstringi(_T(".mayu")) : i_name; + + bool isFirstTime = true; + + while (true) { + // find file from registry + if (i_name.empty()) { // called not from 'include' + Setting::Symbols symbols; + if (getFilenameFromRegistry(NULL, o_path, &symbols)) { + if (o_path->empty()) + // find file from home directory + { + HomeDirectories pathes; + getHomeDirectories(&pathes); + for (HomeDirectories::iterator + i = pathes.begin(); i != pathes.end(); ++ i) { + *o_path = *i + _T("\\") + name; + if (isReadable(*o_path, i_debugLevel)) + goto add_symbols; + } + return false; + } else { + if (!isReadable(*o_path, i_debugLevel)) + return false; + } +add_symbols: + for (Setting::Symbols::iterator + i = symbols.begin(); i != symbols.end(); ++ i) + m_setting->m_symbols.insert(*i); + return true; + } + } + + if (!isFirstTime) + return false; + + // find file from home directory + HomeDirectories pathes; + getHomeDirectories(&pathes); + for (HomeDirectories::iterator i = pathes.begin(); i != pathes.end(); ++ i) { + *o_path = *i + _T("\\") + name; + if (isReadable(*o_path, i_debugLevel)) + return true; + } + + if (!i_name.empty()) + return false; // called by 'include' + + if (!DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_setting), + NULL, dlgSetting_dlgProc)) + return false; } - else - { - if (!isReadable(*o_path, i_debugLevel)) - return false; - } - add_symbols: - for (Setting::Symbols::iterator - i = symbols.begin(); i != symbols.end(); ++ i) - m_setting->m_symbols.insert(*i); - return true; - } - } - - if (!isFirstTime) - return false; - - // find file from home directory - HomeDirectories pathes; - getHomeDirectories(&pathes); - for (HomeDirectories::iterator i = pathes.begin(); i != pathes.end(); ++ i) - { - *o_path = *i + _T("\\") + name; - if (isReadable(*o_path, i_debugLevel)) - return true; - } - - if (!i_name.empty()) - return false; // called by 'include' - - if (!DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_setting), - NULL, dlgSetting_dlgProc)) - return false; - } } // constructor SettingLoader::SettingLoader(SyncObject *i_soLog, tostream *i_log) - : m_setting(NULL), - m_isThereAnyError(false), - m_soLog(i_soLog), - m_log(i_log), - m_currentKeymap(NULL) + : m_setting(NULL), + m_isThereAnyError(false), + m_soLog(i_soLog), + m_log(i_log), + m_currentKeymap(NULL) { - m_defaultKeySeqModifier = - m_defaultAssignModifier.release(Modifier::Type_ImeComp); + m_defaultKeySeqModifier = + m_defaultAssignModifier.release(Modifier::Type_ImeComp); } @@ -1715,55 +1627,52 @@ SettingLoader::SettingLoader(SyncObject *i_soLog, tostream *i_log) */ bool SettingLoader::load(Setting *i_setting, const tstringi &i_filename) { - m_setting = i_setting; - m_isThereAnyError = false; - - tstringi path; - if (!getFilename(i_filename, &path)) - { - if (i_filename.empty()) - { - Acquire a(m_soLog); - getFilename(i_filename, &path, 0); // show filenames - return false; - } - else - throw ErrorMessage() << _T("`") << i_filename - << _T("': no such file or other error."); - } - - // create global keymap's default keySeq - ActionFunction af(createFunctionData(_T("OtherWindowClass"))); - KeySeq *globalDefault = m_setting->m_keySeqs.add(KeySeq(_T("")).add(af)); - - // add default keymap - m_currentKeymap = m_setting->m_keymaps.add( - Keymap(Keymap::Type_windowOr, _T("Global"), _T(""), _T(""), - globalDefault, NULL)); - - /* - // add keyboard layout name - if (filename.empty()) - { - char keyboardLayoutName[KL_NAMELENGTH]; - if (GetKeyboardLayoutName(keyboardLayoutName)) - { - tstringi kl = tstringi(_T("KeyboardLayout/")) + keyboardLayoutName; - m_setting->symbols.insert(kl); - Acquire a(m_soLog); - *m_log << _T("KeyboardLayout: ") << kl << std::endl; - } - } - */ - - // load - load(path); - - // finalize - if (i_filename.empty()) - m_setting->m_keymaps.adjustModifier(m_setting->m_keyboard); - - return !m_isThereAnyError; + m_setting = i_setting; + m_isThereAnyError = false; + + tstringi path; + if (!getFilename(i_filename, &path)) { + if (i_filename.empty()) { + Acquire a(m_soLog); + getFilename(i_filename, &path, 0); // show filenames + return false; + } else + throw ErrorMessage() << _T("`") << i_filename + << _T("': no such file or other error."); + } + + // create global keymap's default keySeq + ActionFunction af(createFunctionData(_T("OtherWindowClass"))); + KeySeq *globalDefault = m_setting->m_keySeqs.add(KeySeq(_T("")).add(af)); + + // add default keymap + m_currentKeymap = m_setting->m_keymaps.add( + Keymap(Keymap::Type_windowOr, _T("Global"), _T(""), _T(""), + globalDefault, NULL)); + + /* + // add keyboard layout name + if (filename.empty()) + { + char keyboardLayoutName[KL_NAMELENGTH]; + if (GetKeyboardLayoutName(keyboardLayoutName)) + { + tstringi kl = tstringi(_T("KeyboardLayout/")) + keyboardLayoutName; + m_setting->symbols.insert(kl); + Acquire a(m_soLog); + *m_log << _T("KeyboardLayout: ") << kl << std::endl; + } + } + */ + + // load + load(path); + + // finalize + if (i_filename.empty()) + m_setting->m_keymaps.adjustModifier(m_setting->m_keyboard); + + return !m_isThereAnyError; } diff --git a/setting.h b/setting.h index 1d0ce55..9234f66 100644 --- a/setting.h +++ b/setting.h @@ -16,39 +16,39 @@ class Setting { public: - typedef std::set Symbols; /// - typedef std::list Modifiers; /// - + typedef std::set Symbols; /// + typedef std::list Modifiers; /// + public: - Keyboard m_keyboard; /// - Keymaps m_keymaps; /// - KeySeqs m_keySeqs; /// - Symbols m_symbols; /// - bool m_correctKanaLockHandling; /// - bool m_sts4mayu; /// - bool m_cts4mayu; /// - unsigned int m_oneShotRepeatableDelay; /// + Keyboard m_keyboard; /// + Keymaps m_keymaps; /// + KeySeqs m_keySeqs; /// + Symbols m_symbols; /// + bool m_correctKanaLockHandling; /// + bool m_sts4mayu; /// + bool m_cts4mayu; /// + unsigned int m_oneShotRepeatableDelay; /// public: - Setting() - : m_correctKanaLockHandling(false), - m_sts4mayu(false), - m_cts4mayu(false), - m_oneShotRepeatableDelay(0) { } + Setting() + : m_correctKanaLockHandling(false), + m_sts4mayu(false), + m_cts4mayu(false), + m_oneShotRepeatableDelay(0) { } }; /// namespace Event { - /// - extern Key prefixed; - /// - extern Key before_key_down; - /// - extern Key after_key_up; - /// - extern Key *events[]; +/// +extern Key prefixed; +/// +extern Key before_key_down; +/// +extern Key after_key_up; +/// +extern Key *events[]; } @@ -58,125 +58,125 @@ class SettingLoader # define FUNCTION_FRIEND # include "functions.h" # undef FUNCTION_FRIEND - + public: - /// - class FunctionCreator - { - public: - const _TCHAR *m_name; /// - FunctionData *m_creator; /// - }; + /// + class FunctionCreator + { + public: + const _TCHAR *m_name; /// + FunctionData *m_creator; /// + }; private: - typedef std::vector Tokens; /// - typedef std::vector Prefixes; /// - typedef std::vector CanReadStack; /// - + typedef std::vector Tokens; /// + typedef std::vector Prefixes; /// + typedef std::vector CanReadStack; /// + private: - Setting *m_setting; /// loaded setting - bool m_isThereAnyError; /// is there any error ? + Setting *m_setting; /// loaded setting + bool m_isThereAnyError; /// is there any error ? + + SyncObject *m_soLog; /// guard log output stream + tostream *m_log; /// log output stream + + tstringi m_currentFilename; /// current filename - SyncObject *m_soLog; /// guard log output stream - tostream *m_log; /// log output stream - - tstringi m_currentFilename; /// current filename - - Tokens m_tokens; /// tokens for current line - Tokens::iterator m_ti; /// current processing token + Tokens m_tokens; /// tokens for current line + Tokens::iterator m_ti; /// current processing token - static Prefixes *m_prefixes; /// prefix terminal symbol - static size_t m_prefixesRefCcount; /// reference count of prefix + static Prefixes *m_prefixes; /// prefix terminal symbol + static size_t m_prefixesRefCcount; /// reference count of prefix - Keymap *m_currentKeymap; /// current keymap + Keymap *m_currentKeymap; /// current keymap - CanReadStack m_canReadStack; /// for <COND_SYMBOL> + CanReadStack m_canReadStack; /// for <COND_SYMBOL> - Modifier m_defaultAssignModifier; /** default + Modifier m_defaultAssignModifier; /** default <ASSIGN_MODIFIER> */ - Modifier m_defaultKeySeqModifier; /** default + Modifier m_defaultKeySeqModifier; /** default <KEYSEQ_MODIFIER> */ private: - bool isEOL(); /// is there no more tokens ? - Token *getToken(); /// get next token - Token *lookToken(); /// look next token - bool getOpenParen(bool i_doesThrow, const _TCHAR *i_name); /// argument "(" - bool getCloseParen(bool i_doesThrow, const _TCHAR *i_name); /// argument ")" - bool getComma(bool i_doesThrow, const _TCHAR *i_name); /// argument "," - - void load_LINE(); /// <LINE> - void load_DEFINE(); /// <DEFINE> - void load_IF(); /// <IF> - void load_ELSE(bool i_isElseIf, const tstringi &i_token); - /// <ELSE> <ELSEIF> - bool load_ENDIF(const tstringi &i_token); /// <ENDIF> - void load_INCLUDE(); /// <INCLUDE> - void load_SCAN_CODES(Key *o_key); /// <SCAN_CODES> - void load_DEFINE_KEY(); /// <DEFINE_KEY> - void load_DEFINE_MODIFIER(); /// <DEFINE_MODIFIER> - void load_DEFINE_SYNC_KEY(); /// <DEFINE_SYNC_KEY> - void load_DEFINE_ALIAS(); /// <DEFINE_ALIAS> - void load_DEFINE_SUBSTITUTE(); /// <DEFINE_SUBSTITUTE> - void load_DEFINE_OPTION(); /// <DEFINE_OPTION> - void load_KEYBOARD_DEFINITION(); /// <KEYBOARD_DEFINITION> - Modifier load_MODIFIER(Modifier::Type i_mode, Modifier i_modifier, - Modifier::Type *o_mode = NULL); - /// <..._MODIFIER> - Key *load_KEY_NAME(); /// <KEY_NAME> - void load_KEYMAP_DEFINITION(const Token *i_which); - /// <KEYMAP_DEFINITION> - void load_ARGUMENT(bool *o_arg); /// <ARGUMENT> - void load_ARGUMENT(int *o_arg); /// <ARGUMENT> - void load_ARGUMENT(unsigned int *o_arg); /// <ARGUMENT> - void load_ARGUMENT(long *o_arg); /// <ARGUMENT> - void load_ARGUMENT(unsigned __int64 *o_arg); /// <ARGUMENT> - void load_ARGUMENT(__int64 *o_arg); /// <ARGUMENT> - void load_ARGUMENT(tstringq *o_arg); /// <ARGUMENT> - void load_ARGUMENT(std::list *o_arg); /// <ARGUMENT> - void load_ARGUMENT(tregex *o_arg); /// <ARGUMENT> - void load_ARGUMENT(VKey *o_arg); /// <ARGUMENT_VK> - void load_ARGUMENT(ToWindowType *o_arg); /// <ARGUMENT_WINDOW> - void load_ARGUMENT(GravityType *o_arg); /// <ARGUMENT> - void load_ARGUMENT(MouseHookType *o_arg); /// <ARGUMENT> - void load_ARGUMENT(MayuDialogType *o_arg); /// <ARGUMENT> - void load_ARGUMENT(ModifierLockType *o_arg); /// <ARGUMENT_LOCK> - void load_ARGUMENT(ToggleType *o_arg); /// <ARGUMENT> - void load_ARGUMENT(ShowCommandType *o_arg); ///<ARGUMENT_SHOW_WINDOW> - void load_ARGUMENT(TargetWindowType *o_arg); - /// <ARGUMENT_TARGET_WINDOW_TYPE> - void load_ARGUMENT(BooleanType *o_arg); /// <bool> - void load_ARGUMENT(LogicalOperatorType *o_arg);/// <ARGUMENT> - void load_ARGUMENT(Modifier *o_arg); /// <ARGUMENT> - void load_ARGUMENT(const Keymap **o_arg); /// <ARGUMENT> - void load_ARGUMENT(const KeySeq **o_arg); /// <ARGUMENT> - void load_ARGUMENT(StrExprArg *o_arg); /// <ARGUMENT> - void load_ARGUMENT(WindowMonitorFromType *o_arg); /// <ARGUMENT> - KeySeq *load_KEY_SEQUENCE( - const tstringi &i_name = _T(""), bool i_isInParen = false, - Modifier::Type i_mode = Modifier::Type_KEYSEQ); /// <KEY_SEQUENCE> - void load_KEY_ASSIGN(); /// <KEY_ASSIGN> - void load_EVENT_ASSIGN(); /// <EVENT_ASSIGN> - void load_MODIFIER_ASSIGNMENT(); /// <MODIFIER_ASSIGN> - void load_LOCK_ASSIGNMENT(); /// <LOCK_ASSIGN> - void load_KEYSEQ_DEFINITION(); /// <KEYSEQ_DEFINITION> - - /// load - void load(const tstringi &i_filename); - - /// is the filename readable ? - bool isReadable(const tstringi &i_filename, int i_debugLevel = 1) const; - - /// get filename - bool getFilename(const tstringi &i_name, - tstringi *o_path, int i_debugLevel = 1) const; + bool isEOL(); /// is there no more tokens ? + Token *getToken(); /// get next token + Token *lookToken(); /// look next token + bool getOpenParen(bool i_doesThrow, const _TCHAR *i_name); /// argument "(" + bool getCloseParen(bool i_doesThrow, const _TCHAR *i_name); /// argument ")" + bool getComma(bool i_doesThrow, const _TCHAR *i_name); /// argument "," + + void load_LINE(); /// <LINE> + void load_DEFINE(); /// <DEFINE> + void load_IF(); /// <IF> + void load_ELSE(bool i_isElseIf, const tstringi &i_token); + /// <ELSE> <ELSEIF> + bool load_ENDIF(const tstringi &i_token); /// <ENDIF> + void load_INCLUDE(); /// <INCLUDE> + void load_SCAN_CODES(Key *o_key); /// <SCAN_CODES> + void load_DEFINE_KEY(); /// <DEFINE_KEY> + void load_DEFINE_MODIFIER(); /// <DEFINE_MODIFIER> + void load_DEFINE_SYNC_KEY(); /// <DEFINE_SYNC_KEY> + void load_DEFINE_ALIAS(); /// <DEFINE_ALIAS> + void load_DEFINE_SUBSTITUTE(); /// <DEFINE_SUBSTITUTE> + void load_DEFINE_OPTION(); /// <DEFINE_OPTION> + void load_KEYBOARD_DEFINITION(); /// <KEYBOARD_DEFINITION> + Modifier load_MODIFIER(Modifier::Type i_mode, Modifier i_modifier, + Modifier::Type *o_mode = NULL); + /// <..._MODIFIER> + Key *load_KEY_NAME(); /// <KEY_NAME> + void load_KEYMAP_DEFINITION(const Token *i_which); + /// <KEYMAP_DEFINITION> + void load_ARGUMENT(bool *o_arg); /// <ARGUMENT> + void load_ARGUMENT(int *o_arg); /// <ARGUMENT> + void load_ARGUMENT(unsigned int *o_arg); /// <ARGUMENT> + void load_ARGUMENT(long *o_arg); /// <ARGUMENT> + void load_ARGUMENT(unsigned __int64 *o_arg); /// <ARGUMENT> + void load_ARGUMENT(__int64 *o_arg); /// <ARGUMENT> + void load_ARGUMENT(tstringq *o_arg); /// <ARGUMENT> + void load_ARGUMENT(std::list *o_arg); /// <ARGUMENT> + void load_ARGUMENT(tregex *o_arg); /// <ARGUMENT> + void load_ARGUMENT(VKey *o_arg); /// <ARGUMENT_VK> + void load_ARGUMENT(ToWindowType *o_arg); /// <ARGUMENT_WINDOW> + void load_ARGUMENT(GravityType *o_arg); /// <ARGUMENT> + void load_ARGUMENT(MouseHookType *o_arg); /// <ARGUMENT> + void load_ARGUMENT(MayuDialogType *o_arg); /// <ARGUMENT> + void load_ARGUMENT(ModifierLockType *o_arg); /// <ARGUMENT_LOCK> + void load_ARGUMENT(ToggleType *o_arg); /// <ARGUMENT> + void load_ARGUMENT(ShowCommandType *o_arg); ///<ARGUMENT_SHOW_WINDOW> + void load_ARGUMENT(TargetWindowType *o_arg); + /// <ARGUMENT_TARGET_WINDOW_TYPE> + void load_ARGUMENT(BooleanType *o_arg); /// <bool> + void load_ARGUMENT(LogicalOperatorType *o_arg);/// <ARGUMENT> + void load_ARGUMENT(Modifier *o_arg); /// <ARGUMENT> + void load_ARGUMENT(const Keymap **o_arg); /// <ARGUMENT> + void load_ARGUMENT(const KeySeq **o_arg); /// <ARGUMENT> + void load_ARGUMENT(StrExprArg *o_arg); /// <ARGUMENT> + void load_ARGUMENT(WindowMonitorFromType *o_arg); /// <ARGUMENT> + KeySeq *load_KEY_SEQUENCE( + const tstringi &i_name = _T(""), bool i_isInParen = false, + Modifier::Type i_mode = Modifier::Type_KEYSEQ); /// <KEY_SEQUENCE> + void load_KEY_ASSIGN(); /// <KEY_ASSIGN> + void load_EVENT_ASSIGN(); /// <EVENT_ASSIGN> + void load_MODIFIER_ASSIGNMENT(); /// <MODIFIER_ASSIGN> + void load_LOCK_ASSIGNMENT(); /// <LOCK_ASSIGN> + void load_KEYSEQ_DEFINITION(); /// <KEYSEQ_DEFINITION> + + /// load + void load(const tstringi &i_filename); + + /// is the filename readable ? + bool isReadable(const tstringi &i_filename, int i_debugLevel = 1) const; + + /// get filename + bool getFilename(const tstringi &i_name, + tstringi *o_path, int i_debugLevel = 1) const; public: - /// - SettingLoader(SyncObject *i_soLog, tostream *i_log); + /// + SettingLoader(SyncObject *i_soLog, tostream *i_log); - /// load setting - bool load(Setting *o_setting, const tstringi &i_filename = _T("")); + /// load setting + bool load(Setting *o_setting, const tstringi &i_filename = _T("")); }; diff --git a/stringtool.cpp b/stringtool.cpp index 4a6f44a..5357d90 100644 --- a/stringtool.cpp +++ b/stringtool.cpp @@ -10,7 +10,7 @@ /* ************************************************************************** * - + STRLCPY(3) OpenBSD Programmer's Manual STRLCPY(3) NAME @@ -109,261 +109,291 @@ and others. template static inline size_t xstrlcpy(T *o_dest, const T *i_src, size_t i_destSize) { - T *d = o_dest; - const T *s = i_src; - size_t n = i_destSize; - - ASSERT( o_dest != NULL ); - ASSERT( i_src != NULL ); - - // Copy as many bytes as will fit - if (n != 0 && --n != 0) - { - do - { - if ((*d++ = *s++) == 0) - break; - } while (--n != 0); - } - - // Not enough room in o_dest, add NUL and traverse rest of i_src - if (n == 0) - { - if (i_destSize != 0) - *d = T(); // NUL-terminate o_dest - while (*s++) - ; - } - - return (s - i_src - 1); // count does not include NUL + T *d = o_dest; + const T *s = i_src; + size_t n = i_destSize; + + ASSERT( o_dest != NULL ); + ASSERT( i_src != NULL ); + + // Copy as many bytes as will fit + if (n != 0 && --n != 0) { + do { + if ((*d++ = *s++) == 0) + break; + } while (--n != 0); + } + + // Not enough room in o_dest, add NUL and traverse rest of i_src + if (n == 0) { + if (i_destSize != 0) + *d = T(); // NUL-terminate o_dest + while (*s++) + ; + } + + return (s - i_src - 1); // count does not include NUL } // copy size_t strlcpy(char *o_dest, const char *i_src, size_t i_destSize) { - return xstrlcpy(o_dest, i_src, i_destSize); + return xstrlcpy(o_dest, i_src, i_destSize); } // copy size_t wcslcpy(wchar_t *o_dest, const wchar_t *i_src, size_t i_destSize) { - return xstrlcpy(o_dest, i_src, i_destSize); + return xstrlcpy(o_dest, i_src, i_destSize); } -// copy +// copy size_t mbslcpy(unsigned char *o_dest, const unsigned char *i_src, - size_t i_destSize) + size_t i_destSize) { - unsigned char *d = o_dest; - const unsigned char *s = i_src; - size_t n = i_destSize; - - ASSERT( o_dest != NULL ); - ASSERT( i_src != NULL ); - - if (n == 0) - return strlen(reinterpret_cast(i_src)); - - // Copy as many bytes as will fit - for (-- n; *s && 0 < n; -- n) - { - if (_ismbblead(*s)) - { - if (!(s[1] && 2 <= n)) - break; - *d++ = *s++; - -- n; - } - *d++ = *s++; - } - *d = '\0'; - - for (; *s; ++ s) - ; - - return s - i_src; + unsigned char *d = o_dest; + const unsigned char *s = i_src; + size_t n = i_destSize; + + ASSERT( o_dest != NULL ); + ASSERT( i_src != NULL ); + + if (n == 0) + return strlen(reinterpret_cast(i_src)); + + // Copy as many bytes as will fit + for (-- n; *s && 0 < n; -- n) { + if (_ismbblead(*s)) { + if (!(s[1] && 2 <= n)) + break; + *d++ = *s++; + -- n; + } + *d++ = *s++; + } + *d = '\0'; + + for (; *s; ++ s) + ; + + return s - i_src; } /// stream output tostream &operator<<(tostream &i_ost, const tstringq &i_data) { - i_ost << _T("\""); - for (const _TCHAR *s = i_data.c_str(); *s; ++ s) - { - switch (*s) - { - case _T('\a'): i_ost << _T("\\a"); break; - case _T('\f'): i_ost << _T("\\f"); break; - case _T('\n'): i_ost << _T("\\n"); break; - case _T('\r'): i_ost << _T("\\r"); break; - case _T('\t'): i_ost << _T("\\t"); break; - case _T('\v'): i_ost << _T("\\v"); break; - case _T('"'): i_ost << _T("\\\""); break; - default: - if (_istlead(*s)) - { - _TCHAR buf[3] = { s[0], s[1], 0 }; - i_ost << buf; - ++ s; - } - else if (_istprint(*s)) - { - _TCHAR buf[2] = { *s, 0 }; - i_ost << buf; - } - else - { - i_ost << _T("\\x"); - _TCHAR buf[5]; + i_ost << _T("\""); + for (const _TCHAR *s = i_data.c_str(); *s; ++ s) { + switch (*s) { + case _T('\a'): + i_ost << _T("\\a"); + break; + case _T('\f'): + i_ost << _T("\\f"); + break; + case _T('\n'): + i_ost << _T("\\n"); + break; + case _T('\r'): + i_ost << _T("\\r"); + break; + case _T('\t'): + i_ost << _T("\\t"); + break; + case _T('\v'): + i_ost << _T("\\v"); + break; + case _T('"'): + i_ost << _T("\\\""); + break; + default: + if (_istlead(*s)) { + _TCHAR buf[3] = { s[0], s[1], 0 }; + i_ost << buf; + ++ s; + } else if (_istprint(*s)) { + _TCHAR buf[2] = { *s, 0 }; + i_ost << buf; + } else { + i_ost << _T("\\x"); + _TCHAR buf[5]; #ifdef _UNICODE - _sntprintf(buf, NUMBER_OF(buf), _T("%04x"), *s); + _sntprintf(buf, NUMBER_OF(buf), _T("%04x"), *s); #else - _sntprintf(buf, NUMBER_OF(buf), _T("%02x"), *s); + _sntprintf(buf, NUMBER_OF(buf), _T("%02x"), *s); #endif - i_ost << buf; + i_ost << buf; + } + break; + } } - break; - } - } - i_ost << _T("\""); - return i_ost; + i_ost << _T("\""); + return i_ost; } // interpret meta characters such as \n tstring interpretMetaCharacters(const _TCHAR *i_str, size_t i_len, - const _TCHAR *i_quote, - bool i_doesUseRegexpBackReference) + const _TCHAR *i_quote, + bool i_doesUseRegexpBackReference) { - // interpreted string is always less than i_len - Array<_TCHAR> result(i_len + 1); - // destination - _TCHAR *d = result.get(); - // end pointer - const _TCHAR *end = i_str + i_len; - - while (i_str < end && *i_str) - { - if (*i_str != _T('\\')) - { - if (_istlead(*i_str) && *(i_str + 1) && i_str + 1 < end) - *d++ = *i_str++; - *d++ = *i_str++; - } - else if (*(i_str + 1) != _T('\0')) - { - i_str ++; - if (i_quote && _tcschr(i_quote, *i_str)) - *d++ = *i_str++; - else - switch (*i_str) - { - case _T('a'): *d++ = _T('\x07'); i_str ++; break; - //case _T('b'): *d++ = _T('\b'); i_str ++; break; - case _T('e'): *d++ = _T('\x1b'); i_str ++; break; - case _T('f'): *d++ = _T('\f'); i_str ++; break; - case _T('n'): *d++ = _T('\n'); i_str ++; break; - case _T('r'): *d++ = _T('\r'); i_str ++; break; - case _T('t'): *d++ = _T('\t'); i_str ++; break; - case _T('v'): *d++ = _T('\v'); i_str ++; break; - //case _T('?'): *d++ = _T('\x7f'); i_str ++; break; - //case _T('_'): *d++ = _T(' '); i_str ++; break; - //case _T('\\'): *d++ = _T('\\'); i_str ++; break; - case _T('\''): *d++ = _T('\''); i_str ++; break; - case _T('"'): *d++ = _T('"'); i_str ++; break; - case _T('\\'): *d++ = _T('\\'); i_str ++; break; - case _T('c'): // control code, for example '\c[' is escape: '\x1b' - i_str ++; - if (i_str < end && *i_str) - { - static const _TCHAR *ctrlchar = - _T("@ABCDEFGHIJKLMNO") - _T("PQRSTUVWXYZ[\\]^_") - _T("@abcdefghijklmno") - _T("pqrstuvwxyz@@@@?"); - static const _TCHAR *ctrlcode = - _T("\00\01\02\03\04\05\06\07\10\11\12\13\14\15\16\17") - _T("\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37") - _T("\00\01\02\03\04\05\06\07\10\11\12\13\14\15\16\17") - _T("\20\21\22\23\24\25\26\27\30\31\32\00\00\00\00\177"); - if (const _TCHAR *c = _tcschr(ctrlchar, *i_str)) - *d++ = ctrlcode[c - ctrlchar], i_str ++; - } - break; - case _T('x'): case _T('X'): - { - i_str ++; - static const _TCHAR *hexchar = _T("0123456789ABCDEFabcdef"); - static int hexvalue[] = { 0, 1, 2, 3, 4, 5 ,6, 7, 8, 9, - 10, 11, 12, 13, 14, 15, - 10, 11, 12, 13, 14, 15, }; - bool brace = false; - if (i_str < end && *i_str == _T('{')) - { - i_str ++; - brace = true; - } - int n = 0; - for (; i_str < end && *i_str; i_str ++) - if (const _TCHAR *c = _tcschr(hexchar, *i_str)) - n = n * 16 + hexvalue[c - hexchar]; - else - break; - if (i_str < end && *i_str == _T('}') && brace) - i_str ++; - if (0 < n) - *d++ = static_cast<_TCHAR>(n); - break; - } - case _T('1'): case _T('2'): case _T('3'): - case _T('4'): case _T('5'): case _T('6'): case _T('7'): - if (i_doesUseRegexpBackReference) - goto case_default; - // fall through - case _T('0'): - { - static const _TCHAR *octalchar = _T("01234567"); - static int octalvalue[] = { 0, 1, 2, 3, 4, 5 ,6, 7, }; - int n = 0; - for (; i_str < end && *i_str; i_str ++) - if (const _TCHAR *c = _tcschr(octalchar, *i_str)) - n = n * 8 + octalvalue[c - octalchar]; - else - break; - if (0 < n) - *d++ = static_cast<_TCHAR>(n); - break; - } - default: - case_default: - *d++ = _T('\\'); - if (_istlead(*i_str) && *(i_str + 1) && i_str + 1 < end) - *d++ = *i_str++; - *d++ = *i_str++; - break; + // interpreted string is always less than i_len + Array<_TCHAR> result(i_len + 1); + // destination + _TCHAR *d = result.get(); + // end pointer + const _TCHAR *end = i_str + i_len; + + while (i_str < end && *i_str) { + if (*i_str != _T('\\')) { + if (_istlead(*i_str) && *(i_str + 1) && i_str + 1 < end) + *d++ = *i_str++; + *d++ = *i_str++; + } else if (*(i_str + 1) != _T('\0')) { + i_str ++; + if (i_quote && _tcschr(i_quote, *i_str)) + *d++ = *i_str++; + else + switch (*i_str) { + case _T('a'): + *d++ = _T('\x07'); + i_str ++; + break; + //case _T('b'): *d++ = _T('\b'); i_str ++; break; + case _T('e'): + *d++ = _T('\x1b'); + i_str ++; + break; + case _T('f'): + *d++ = _T('\f'); + i_str ++; + break; + case _T('n'): + *d++ = _T('\n'); + i_str ++; + break; + case _T('r'): + *d++ = _T('\r'); + i_str ++; + break; + case _T('t'): + *d++ = _T('\t'); + i_str ++; + break; + case _T('v'): + *d++ = _T('\v'); + i_str ++; + break; + //case _T('?'): *d++ = _T('\x7f'); i_str ++; break; + //case _T('_'): *d++ = _T(' '); i_str ++; break; + //case _T('\\'): *d++ = _T('\\'); i_str ++; break; + case _T('\''): + *d++ = _T('\''); + i_str ++; + break; + case _T('"'): + *d++ = _T('"'); + i_str ++; + break; + case _T('\\'): + *d++ = _T('\\'); + i_str ++; + break; + case _T('c'): // control code, for example '\c[' is escape: '\x1b' + i_str ++; + if (i_str < end && *i_str) { + static const _TCHAR *ctrlchar = + _T("@ABCDEFGHIJKLMNO") + _T("PQRSTUVWXYZ[\\]^_") + _T("@abcdefghijklmno") + _T("pqrstuvwxyz@@@@?"); + static const _TCHAR *ctrlcode = + _T("\00\01\02\03\04\05\06\07\10\11\12\13\14\15\16\17") + _T("\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37") + _T("\00\01\02\03\04\05\06\07\10\11\12\13\14\15\16\17") + _T("\20\21\22\23\24\25\26\27\30\31\32\00\00\00\00\177"); + if (const _TCHAR *c = _tcschr(ctrlchar, *i_str)) + *d++ = ctrlcode[c - ctrlchar], i_str ++; + } + break; + case _T('x'): + case _T('X'): { + i_str ++; + static const _TCHAR *hexchar = _T("0123456789ABCDEFabcdef"); + static int hexvalue[] = { 0, 1, 2, 3, 4, 5 ,6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, + 10, 11, 12, 13, 14, 15, + }; + bool brace = false; + if (i_str < end && *i_str == _T('{')) { + i_str ++; + brace = true; + } + int n = 0; + for (; i_str < end && *i_str; i_str ++) + if (const _TCHAR *c = _tcschr(hexchar, *i_str)) + n = n * 16 + hexvalue[c - hexchar]; + else + break; + if (i_str < end && *i_str == _T('}') && brace) + i_str ++; + if (0 < n) + *d++ = static_cast<_TCHAR>(n); + break; + } + case _T('1'): + case _T('2'): + case _T('3'): + case _T('4'): + case _T('5'): + case _T('6'): + case _T('7'): + if (i_doesUseRegexpBackReference) + goto case_default; + // fall through + case _T('0'): { + static const _TCHAR *octalchar = _T("01234567"); + static int octalvalue[] = { 0, 1, 2, 3, 4, 5 ,6, 7, }; + int n = 0; + for (; i_str < end && *i_str; i_str ++) + if (const _TCHAR *c = _tcschr(octalchar, *i_str)) + n = n * 8 + octalvalue[c - octalchar]; + else + break; + if (0 < n) + *d++ = static_cast<_TCHAR>(n); + break; + } + default: +case_default: + *d++ = _T('\\'); + if (_istlead(*i_str) && *(i_str + 1) && i_str + 1 < end) + *d++ = *i_str++; + *d++ = *i_str++; + break; + } + } } - } - } - *d =_T('\0'); - return result.get(); + *d =_T('\0'); + return result.get(); } // add session id to i_str tstring addSessionId(const _TCHAR *i_str) { - DWORD sessionId; - tstring s(i_str); - if (ProcessIdToSessionId(GetCurrentProcessId(), &sessionId)) { - _TCHAR buf[20]; - _sntprintf(buf, NUMBER_OF(buf), _T("%u"), sessionId); - s += buf; - } - return s; + DWORD sessionId; + tstring s(i_str); + if (ProcessIdToSessionId(GetCurrentProcessId(), &sessionId)) { + _TCHAR buf[20]; + _sntprintf(buf, NUMBER_OF(buf), _T("%u"), sessionId); + s += buf; + } + return s; } @@ -371,20 +401,18 @@ tstring addSessionId(const _TCHAR *i_str) // escape regexp special characters in MBCS trail bytes std::string guardRegexpFromMbcs(const char *i_str) { - size_t len = strlen(i_str); - Array buf(len * 2 + 1); - char *p = buf.get(); - while (*i_str) - { - if (_ismbblead(static_cast(*i_str)) && i_str[1]) - { - *p ++ = *i_str ++; - if (strchr(".*?+(){}[]^$", *i_str)) - *p ++ = '\\'; - } - *p ++ = *i_str ++; - } - return std::string(buf.get(), p); + size_t len = strlen(i_str); + Array buf(len * 2 + 1); + char *p = buf.get(); + while (*i_str) { + if (_ismbblead(static_cast(*i_str)) && i_str[1]) { + *p ++ = *i_str ++; + if (strchr(".*?+(){}[]^$", *i_str)) + *p ++ = '\\'; + } + *p ++ = *i_str ++; + } + return std::string(buf.get(), p); } #endif // !_MBCS @@ -392,89 +420,83 @@ std::string guardRegexpFromMbcs(const char *i_str) // converter std::wstring to_wstring(const std::string &i_str) { - size_t size = mbstowcs(NULL, i_str.c_str(), i_str.size() + 1); - if (size == (size_t)-1) - return std::wstring(); - Array result(size + 1); - mbstowcs(result.get(), i_str.c_str(), i_str.size() + 1); - return std::wstring(result.get()); + size_t size = mbstowcs(NULL, i_str.c_str(), i_str.size() + 1); + if (size == (size_t)-1) + return std::wstring(); + Array result(size + 1); + mbstowcs(result.get(), i_str.c_str(), i_str.size() + 1); + return std::wstring(result.get()); } // converter std::string to_string(const std::wstring &i_str) { - size_t size = wcstombs(NULL, i_str.c_str(), i_str.size() + 1); - if (size == (size_t)-1) - return std::string(); - Array result(size + 1); - wcstombs(result.get(), i_str.c_str(), i_str.size() + 1); - return std::string(result.get()); + size_t size = wcstombs(NULL, i_str.c_str(), i_str.size() + 1); + if (size == (size_t)-1) + return std::string(); + Array result(size + 1); + wcstombs(result.get(), i_str.c_str(), i_str.size() + 1); + return std::string(result.get()); } /// stream output tostream &operator<<(tostream &i_ost, const tregex &i_data) { - return i_ost << i_data.str(); + return i_ost << i_data.str(); } /// get lower string tstring toLower(const tstring &i_str) { - tstring str(i_str); - for (size_t i = 0; i < str.size(); ++ i) - { - if (_ismbblead(str[i])) - ++ i; - else - str[i] = tolower(str[i]); - } - return str; + tstring str(i_str); + for (size_t i = 0; i < str.size(); ++ i) { + if (_ismbblead(str[i])) + ++ i; + else + str[i] = tolower(str[i]); + } + return str; } // convert wstring to UTF-8 std::string to_UTF_8(const std::wstring &i_str) { - // 0xxxxxxx: 00-7F - // 110xxxxx 10xxxxxx: 0080-07FF - // 1110xxxx 10xxxxxx 10xxxxxx: 0800 - FFFF - - int size = 0; - - // count needed buffer size - for (std::wstring::const_iterator i = i_str.begin(); i != i_str.end(); ++ i) - { - if (0x0000 <= *i && *i <= 0x007f) - size += 1; - else if (0x0080 <= *i && *i <= 0x07ff) - size += 2; - else if (0x0800 <= *i && *i <= 0xffff) - size += 3; - } - - Array result(size); - int ri = 0; - - // make UTF-8 - for (std::wstring::const_iterator i = i_str.begin(); i != i_str.end(); ++ i) - { - if (0x0000 <= *i && *i <= 0x007f) - result[ri ++] = static_cast(*i); - else if (0x0080 <= *i && *i <= 0x07ff) - { - result[ri ++] = static_cast(((*i & 0x0fc0) >> 6) | 0xc0); - result[ri ++] = static_cast(( *i & 0x003f ) | 0x80); - } - else if (0x0800 <= *i && *i <= 0xffff) - { - result[ri ++] = static_cast(((*i & 0xf000) >> 12) | 0xe0); - result[ri ++] = static_cast(((*i & 0x0fc0) >> 6) | 0x80); - result[ri ++] = static_cast(( *i & 0x003f ) | 0x80); - } - } - - return std::string(result.begin(), result.end()); + // 0xxxxxxx: 00-7F + // 110xxxxx 10xxxxxx: 0080-07FF + // 1110xxxx 10xxxxxx 10xxxxxx: 0800 - FFFF + + int size = 0; + + // count needed buffer size + for (std::wstring::const_iterator i = i_str.begin(); i != i_str.end(); ++ i) { + if (0x0000 <= *i && *i <= 0x007f) + size += 1; + else if (0x0080 <= *i && *i <= 0x07ff) + size += 2; + else if (0x0800 <= *i && *i <= 0xffff) + size += 3; + } + + Array result(size); + int ri = 0; + + // make UTF-8 + for (std::wstring::const_iterator i = i_str.begin(); i != i_str.end(); ++ i) { + if (0x0000 <= *i && *i <= 0x007f) + result[ri ++] = static_cast(*i); + else if (0x0080 <= *i && *i <= 0x07ff) { + result[ri ++] = static_cast(((*i & 0x0fc0) >> 6) | 0xc0); + result[ri ++] = static_cast(( *i & 0x003f ) | 0x80); + } else if (0x0800 <= *i && *i <= 0xffff) { + result[ri ++] = static_cast(((*i & 0xf000) >> 12) | 0xe0); + result[ri ++] = static_cast(((*i & 0x0fc0) >> 6) | 0x80); + result[ri ++] = static_cast(( *i & 0x003f ) | 0x80); + } + } + + return std::string(result.begin(), result.end()); } diff --git a/stringtool.h b/stringtool.h index 5b673c2..92ad0e2 100644 --- a/stringtool.h +++ b/stringtool.h @@ -40,21 +40,21 @@ typedef boost::match_results tsmatch; class tstringq : public tstring { public: - /// - tstringq() { } - /// - tstringq(const tstringq &i_str) : tstring(i_str) { } - /// - tstringq(const tstring &i_str) : tstring(i_str) { } - /// - tstringq(const _TCHAR *i_str) : tstring(i_str) { } - /// - tstringq(const _TCHAR *i_str, size_t i_n) : tstring(i_str, i_n) { } - /// - tstringq(const _TCHAR *i_str, size_t i_pos, size_t i_n) - : tstring(i_str, i_pos, i_n) { } - /// - tstringq(size_t i_n, _TCHAR i_c) : tstring(i_n, i_c) { } + /// + tstringq() { } + /// + tstringq(const tstringq &i_str) : tstring(i_str) { } + /// + tstringq(const tstring &i_str) : tstring(i_str) { } + /// + tstringq(const _TCHAR *i_str) : tstring(i_str) { } + /// + tstringq(const _TCHAR *i_str, size_t i_n) : tstring(i_str, i_n) { } + /// + tstringq(const _TCHAR *i_str, size_t i_pos, size_t i_n) + : tstring(i_str, i_pos, i_n) { } + /// + tstringq(size_t i_n, _TCHAR i_c) : tstring(i_n, i_c) { } }; @@ -64,8 +64,8 @@ extern tostream &operator<<(tostream &i_ost, const tstringq &i_data); /// interpret meta characters such as \n tstring interpretMetaCharacters(const _TCHAR *i_str, size_t i_len, - const _TCHAR *i_quote = NULL, - bool i_doesUseRegexpBackReference = false); + const _TCHAR *i_quote = NULL, + bool i_doesUseRegexpBackReference = false); /// add session id to i_str tstring addSessionId(const _TCHAR *i_str); @@ -74,19 +74,25 @@ tstring addSessionId(const _TCHAR *i_str); size_t strlcpy(char *o_dest, const char *i_src, size_t i_destSize); /// copy size_t mbslcpy(unsigned char *o_dest, const unsigned char *i_src, - size_t i_destSize); + size_t i_destSize); /// copy size_t wcslcpy(wchar_t *o_dest, const wchar_t *i_src, size_t i_destSize); /// copy inline size_t tcslcpy(char *o_dest, const char *i_src, size_t i_destSize) -{ return strlcpy(o_dest, i_src, i_destSize); } +{ + return strlcpy(o_dest, i_src, i_destSize); +} /// copy inline size_t tcslcpy(unsigned char *o_dest, const unsigned char *i_src, - size_t i_destSize) -{ return mbslcpy(o_dest, i_src, i_destSize); } + size_t i_destSize) +{ + return mbslcpy(o_dest, i_src, i_destSize); +} /// copy inline size_t tcslcpy(wchar_t *o_dest, const wchar_t *i_src, size_t i_destSize) -{ return wcslcpy(o_dest, i_src, i_destSize); } +{ + return wcslcpy(o_dest, i_src, i_destSize); +} // escape regexp special characters in MBCS trail bytes std::string guardRegexpFromMbcs(const char *i_str); @@ -97,72 +103,99 @@ std::string to_string(const std::wstring &i_str); // convert wstring to UTF-8 std::string to_UTF_8(const std::wstring &i_str); - + /// case insensitive string class tstringi : public tstring { public: - /// - tstringi() { } - /// - tstringi(const tstringi &i_str) : tstring(i_str) { } - /// - tstringi(const tstring &i_str) : tstring(i_str) { } - /// - tstringi(const _TCHAR *i_str) : tstring(i_str) { } - /// - tstringi(const _TCHAR *i_str, size_t i_n) : tstring(i_str, i_n) { } - /// - tstringi(const _TCHAR *i_str, size_t i_pos, size_t i_n) - : tstring(i_str, i_pos, i_n) { } - /// - tstringi(size_t i_n, _TCHAR i_c) : tstring(i_n, i_c) { } - /// - int compare(const tstringi &i_str) const - { return compare(i_str.c_str()); } - /// - int compare(const tstring &i_str) const - { return compare(i_str.c_str()); } - /// - int compare(const _TCHAR *i_str) const - { return _tcsicmp(c_str(), i_str); } - /// - tstring &getString() { return *this; } - /// - const tstring &getString() const { return *this; } + /// + tstringi() { } + /// + tstringi(const tstringi &i_str) : tstring(i_str) { } + /// + tstringi(const tstring &i_str) : tstring(i_str) { } + /// + tstringi(const _TCHAR *i_str) : tstring(i_str) { } + /// + tstringi(const _TCHAR *i_str, size_t i_n) : tstring(i_str, i_n) { } + /// + tstringi(const _TCHAR *i_str, size_t i_pos, size_t i_n) + : tstring(i_str, i_pos, i_n) { } + /// + tstringi(size_t i_n, _TCHAR i_c) : tstring(i_n, i_c) { } + /// + int compare(const tstringi &i_str) const { + return compare(i_str.c_str()); + } + /// + int compare(const tstring &i_str) const { + return compare(i_str.c_str()); + } + /// + int compare(const _TCHAR *i_str) const { + return _tcsicmp(c_str(), i_str); + } + /// + tstring &getString() { + return *this; + } + /// + const tstring &getString() const { + return *this; + } }; /// case insensitive string comparison inline bool operator<(const tstringi &i_str1, const _TCHAR *i_str2) -{ return i_str1.compare(i_str2) < 0; } +{ + return i_str1.compare(i_str2) < 0; +} /// case insensitive string comparison inline bool operator<(const _TCHAR *i_str1, const tstringi &i_str2) -{ return 0 < i_str2.compare(i_str1); } +{ + return 0 < i_str2.compare(i_str1); +} /// case insensitive string comparison inline bool operator<(const tstringi &i_str1, const tstring &i_str2) -{ return i_str1.compare(i_str2) < 0; } +{ + return i_str1.compare(i_str2) < 0; +} /// case insensitive string comparison inline bool operator<(const tstring &i_str1, const tstringi &i_str2) -{ return 0 < i_str2.compare(i_str1); } +{ + return 0 < i_str2.compare(i_str1); +} /// case insensitive string comparison inline bool operator<(const tstringi &i_str1, const tstringi &i_str2) -{ return i_str1.compare(i_str2) < 0; } +{ + return i_str1.compare(i_str2) < 0; +} /// case insensitive string comparison inline bool operator==(const _TCHAR *i_str1, const tstringi &i_str2) -{ return i_str2.compare(i_str1) == 0; } +{ + return i_str2.compare(i_str1) == 0; +} /// case insensitive string comparison inline bool operator==(const tstringi &i_str1, const _TCHAR *i_str2) -{ return i_str1.compare(i_str2) == 0; } +{ + return i_str1.compare(i_str2) == 0; +} /// case insensitive string comparison inline bool operator==(const tstring &i_str1, const tstringi &i_str2) -{ return i_str2.compare(i_str1) == 0; } +{ + return i_str2.compare(i_str1) == 0; +} /// case insensitive string comparison inline bool operator==(const tstringi &i_str1, const tstring &i_str2) -{ return i_str1.compare(i_str2) == 0; } +{ + return i_str1.compare(i_str2) == 0; +} /// case insensitive string comparison inline bool operator==(const tstringi &i_str1, const tstringi &i_str2) -{ return i_str1.compare(i_str2) == 0; } +{ + return i_str1.compare(i_str2) == 0; +} //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -171,19 +204,29 @@ inline bool operator==(const tstringi &i_str1, const tstringi &i_str2) /// case insensitive string comparison inline bool operator!=(const _TCHAR *i_str1, const tstringi &i_str2) -{ return i_str2.compare(i_str1) != 0; } +{ + return i_str2.compare(i_str1) != 0; +} /// case insensitive string comparison inline bool operator!=(const tstringi &i_str1, const _TCHAR *i_str2) -{ return i_str1.compare(i_str2) != 0; } +{ + return i_str1.compare(i_str2) != 0; +} /// case insensitive string comparison inline bool operator!=(const tstring &i_str1, const tstringi &i_str2) -{ return i_str2.compare(i_str1) != 0; } +{ + return i_str2.compare(i_str1) != 0; +} /// case insensitive string comparison inline bool operator!=(const tstringi &i_str1, const tstring &i_str2) -{ return i_str1.compare(i_str2) != 0; } +{ + return i_str1.compare(i_str2) != 0; +} /// case insensitive string comparison inline bool operator!=(const tstringi &i_str1, const tstringi &i_str2) -{ return i_str1.compare(i_str2) != 0; } +{ + return i_str1.compare(i_str2) != 0; +} /// stream output diff --git a/target.cpp b/target.cpp index 7cee3d2..5281a10 100644 --- a/target.cpp +++ b/target.cpp @@ -12,221 +12,199 @@ /// class Target { - HWND m_hwnd; /// - HWND m_preHwnd; /// - HICON m_hCursor; /// - - /// - static void invertFrame(HWND i_hwnd) - { - HDC hdc = GetWindowDC(i_hwnd); - ASSERT(hdc); - int rop2 = SetROP2(hdc, R2_XORPEN); - if (rop2) - { - RECT rc; - CHECK_TRUE( GetWindowRect(i_hwnd, &rc) ); - int width = rcWidth(&rc); - int height = rcHeight(&rc); - - HANDLE hpen = SelectObject(hdc, GetStockObject(WHITE_PEN)); - HANDLE hbr = SelectObject(hdc, GetStockObject(NULL_BRUSH)); - CHECK_TRUE( Rectangle(hdc, 0, 0, width , height ) ); - CHECK_TRUE( Rectangle(hdc, 1, 1, width - 1, height - 1) ); - CHECK_TRUE( Rectangle(hdc, 2, 2, width - 2, height - 2) ); - SelectObject(hdc, hpen); - SelectObject(hdc, hbr); - // no need to DeleteObject StockObject - SetROP2(hdc, rop2); - } - CHECK_TRUE( ReleaseDC(i_hwnd, hdc) ); - } - - /// - Target(HWND i_hwnd) - : m_hwnd(i_hwnd), - m_preHwnd(NULL), - m_hCursor(NULL) - { - } - - /// WM_CREATE - int wmCreate(CREATESTRUCT * /* i_cs */) - { - CHECK_TRUE( m_hCursor = - LoadCursor(g_hInst, MAKEINTRESOURCE(IDC_CURSOR_target)) ); - return 0; - } - - /// WM_PAINT - int wmPaint() - { - PAINTSTRUCT ps; - HDC hdc = BeginPaint(m_hwnd, &ps); - ASSERT(hdc); - - if (GetCapture() != m_hwnd) - { - RECT rc; - CHECK_TRUE( GetClientRect(m_hwnd, &rc) ); - CHECK_TRUE( - DrawIcon(hdc, (rcWidth(&rc) - GetSystemMetrics(SM_CXICON)) / 2, - (rcHeight(&rc) - GetSystemMetrics(SM_CYICON)) / 2, - m_hCursor) ); - } - - EndPaint(m_hwnd, &ps); - return 0; - } - - /// - struct PointWindow - { - POINT m_p; /// - HWND m_hwnd; /// - RECT m_rc; /// - }; - - /// - static BOOL CALLBACK childWindowFromPoint(HWND i_hwnd, LPARAM i_lParam) - { - if (IsWindowVisible(i_hwnd)) - { - PointWindow &pw = *(PointWindow *)i_lParam; - RECT rc; - CHECK_TRUE( GetWindowRect(i_hwnd, &rc) ); - if (PtInRect(&rc, pw.m_p)) - if (isRectInRect(&rc, &pw.m_rc)) - { - pw.m_hwnd = i_hwnd; - pw.m_rc = rc; + HWND m_hwnd; /// + HWND m_preHwnd; /// + HICON m_hCursor; /// + + /// + static void invertFrame(HWND i_hwnd) { + HDC hdc = GetWindowDC(i_hwnd); + ASSERT(hdc); + int rop2 = SetROP2(hdc, R2_XORPEN); + if (rop2) { + RECT rc; + CHECK_TRUE( GetWindowRect(i_hwnd, &rc) ); + int width = rcWidth(&rc); + int height = rcHeight(&rc); + + HANDLE hpen = SelectObject(hdc, GetStockObject(WHITE_PEN)); + HANDLE hbr = SelectObject(hdc, GetStockObject(NULL_BRUSH)); + CHECK_TRUE( Rectangle(hdc, 0, 0, width , height ) ); + CHECK_TRUE( Rectangle(hdc, 1, 1, width - 1, height - 1) ); + CHECK_TRUE( Rectangle(hdc, 2, 2, width - 2, height - 2) ); + SelectObject(hdc, hpen); + SelectObject(hdc, hbr); + // no need to DeleteObject StockObject + SetROP2(hdc, rop2); + } + CHECK_TRUE( ReleaseDC(i_hwnd, hdc) ); + } + + /// + Target(HWND i_hwnd) + : m_hwnd(i_hwnd), + m_preHwnd(NULL), + m_hCursor(NULL) { + } + + /// WM_CREATE + int wmCreate(CREATESTRUCT * /* i_cs */) { + CHECK_TRUE( m_hCursor = + LoadCursor(g_hInst, MAKEINTRESOURCE(IDC_CURSOR_target)) ); + return 0; + } + + /// WM_PAINT + int wmPaint() { + PAINTSTRUCT ps; + HDC hdc = BeginPaint(m_hwnd, &ps); + ASSERT(hdc); + + if (GetCapture() != m_hwnd) { + RECT rc; + CHECK_TRUE( GetClientRect(m_hwnd, &rc) ); + CHECK_TRUE( + DrawIcon(hdc, (rcWidth(&rc) - GetSystemMetrics(SM_CXICON)) / 2, + (rcHeight(&rc) - GetSystemMetrics(SM_CYICON)) / 2, + m_hCursor) ); + } + + EndPaint(m_hwnd, &ps); + return 0; + } + + /// + struct PointWindow { + POINT m_p; /// + HWND m_hwnd; /// + RECT m_rc; /// + }; + + /// + static BOOL CALLBACK childWindowFromPoint(HWND i_hwnd, LPARAM i_lParam) { + if (IsWindowVisible(i_hwnd)) { + PointWindow &pw = *(PointWindow *)i_lParam; + RECT rc; + CHECK_TRUE( GetWindowRect(i_hwnd, &rc) ); + if (PtInRect(&rc, pw.m_p)) + if (isRectInRect(&rc, &pw.m_rc)) { + pw.m_hwnd = i_hwnd; + pw.m_rc = rc; + } + } + return TRUE; + } + + /// + static BOOL CALLBACK windowFromPoint(HWND i_hwnd, LPARAM i_lParam) { + if (IsWindowVisible(i_hwnd)) { + PointWindow &pw = *(PointWindow *)i_lParam; + RECT rc; + CHECK_TRUE( GetWindowRect(i_hwnd, &rc) ); + if (PtInRect(&rc, pw.m_p)) { + pw.m_hwnd = i_hwnd; + pw.m_rc = rc; + return FALSE; + } + } + return TRUE; + } + + /// WM_MOUSEMOVE + int wmMouseMove(WORD /* i_keys */, int /* i_x */, int /* i_y */) { + if (GetCapture() == m_hwnd) { + PointWindow pw; + CHECK_TRUE( GetCursorPos(&pw.m_p) ); + pw.m_hwnd = 0; + CHECK_TRUE( GetWindowRect(GetDesktopWindow(), &pw.m_rc) ); + EnumWindows(windowFromPoint, (LPARAM)&pw); + while (1) { + HWND hwndParent = pw.m_hwnd; + if (!EnumChildWindows(pw.m_hwnd, childWindowFromPoint, (LPARAM)&pw)) + break; + if (hwndParent == pw.m_hwnd) + break; + } + if (pw.m_hwnd != m_preHwnd) { + if (m_preHwnd) + invertFrame(m_preHwnd); + m_preHwnd = pw.m_hwnd; + invertFrame(m_preHwnd); + SendMessage(GetParent(m_hwnd), WM_APP_targetNotify, 0, + (LPARAM)m_preHwnd); + } + SetCursor(m_hCursor); + } + return 0; + } + + /// WM_LBUTTONDOWN + int wmLButtonDown(WORD /* i_keys */, int /* i_x */, int /* i_y */) { + SetCapture(m_hwnd); + SetCursor(m_hCursor); + CHECK_TRUE( InvalidateRect(m_hwnd, NULL, TRUE) ); + CHECK_TRUE( UpdateWindow(m_hwnd) ); + return 0; + } + + /// WM_LBUTTONUP + int wmLButtonUp(WORD /* i_keys */, int /* i_x */, int /* i_y */) { + if (m_preHwnd) + invertFrame(m_preHwnd); + m_preHwnd = NULL; + ReleaseCapture(); + CHECK_TRUE( InvalidateRect(m_hwnd, NULL, TRUE) ); + CHECK_TRUE( UpdateWindow(m_hwnd) ); + return 0; } - } - return TRUE; - } - - /// - static BOOL CALLBACK windowFromPoint(HWND i_hwnd, LPARAM i_lParam) - { - if (IsWindowVisible(i_hwnd)) - { - PointWindow &pw = *(PointWindow *)i_lParam; - RECT rc; - CHECK_TRUE( GetWindowRect(i_hwnd, &rc) ); - if (PtInRect(&rc, pw.m_p)) - { - pw.m_hwnd = i_hwnd; - pw.m_rc = rc; - return FALSE; - } - } - return TRUE; - } - - /// WM_MOUSEMOVE - int wmMouseMove(WORD /* i_keys */, int /* i_x */, int /* i_y */) - { - if (GetCapture() == m_hwnd) - { - PointWindow pw; - CHECK_TRUE( GetCursorPos(&pw.m_p) ); - pw.m_hwnd = 0; - CHECK_TRUE( GetWindowRect(GetDesktopWindow(), &pw.m_rc) ); - EnumWindows(windowFromPoint, (LPARAM)&pw); - while (1) - { - HWND hwndParent = pw.m_hwnd; - if (!EnumChildWindows(pw.m_hwnd, childWindowFromPoint, (LPARAM)&pw)) - break; - if (hwndParent == pw.m_hwnd) - break; - } - if (pw.m_hwnd != m_preHwnd) - { - if (m_preHwnd) - invertFrame(m_preHwnd); - m_preHwnd = pw.m_hwnd; - invertFrame(m_preHwnd); - SendMessage(GetParent(m_hwnd), WM_APP_targetNotify, 0, - (LPARAM)m_preHwnd); - } - SetCursor(m_hCursor); - } - return 0; - } - - /// WM_LBUTTONDOWN - int wmLButtonDown(WORD /* i_keys */, int /* i_x */, int /* i_y */) - { - SetCapture(m_hwnd); - SetCursor(m_hCursor); - CHECK_TRUE( InvalidateRect(m_hwnd, NULL, TRUE) ); - CHECK_TRUE( UpdateWindow(m_hwnd) ); - return 0; - } - - /// WM_LBUTTONUP - int wmLButtonUp(WORD /* i_keys */, int /* i_x */, int /* i_y */) - { - if (m_preHwnd) - invertFrame(m_preHwnd); - m_preHwnd = NULL; - ReleaseCapture(); - CHECK_TRUE( InvalidateRect(m_hwnd, NULL, TRUE) ); - CHECK_TRUE( UpdateWindow(m_hwnd) ); - return 0; - } public: - /// - static LRESULT CALLBACK WndProc(HWND i_hwnd, UINT i_message, - WPARAM i_wParam, LPARAM i_lParam) - { - Target *wc; - getUserData(i_hwnd, &wc); - if (!wc) - switch (i_message) - { - case WM_CREATE: - wc = setUserData(i_hwnd, new Target(i_hwnd)); - return wc->wmCreate((CREATESTRUCT *)i_lParam); - } - else - switch (i_message) - { - case WM_PAINT: - return wc->wmPaint(); - case WM_LBUTTONDOWN: - return wc->wmLButtonDown((WORD)i_wParam, (short)LOWORD(i_lParam), - (short)HIWORD(i_lParam)); - case WM_LBUTTONUP: - return wc->wmLButtonUp((WORD)i_wParam, (short)LOWORD(i_lParam), - (short)HIWORD(i_lParam)); - case WM_MOUSEMOVE: - return wc->wmMouseMove((WORD)i_wParam, (short)LOWORD(i_lParam), - (short)HIWORD(i_lParam)); - case WM_NCDESTROY: - delete wc; - return 0; - } - return DefWindowProc(i_hwnd, i_message, i_wParam, i_lParam); - } + /// + static LRESULT CALLBACK WndProc(HWND i_hwnd, UINT i_message, + WPARAM i_wParam, LPARAM i_lParam) { + Target *wc; + getUserData(i_hwnd, &wc); + if (!wc) + switch (i_message) { + case WM_CREATE: + wc = setUserData(i_hwnd, new Target(i_hwnd)); + return wc->wmCreate((CREATESTRUCT *)i_lParam); + } + else + switch (i_message) { + case WM_PAINT: + return wc->wmPaint(); + case WM_LBUTTONDOWN: + return wc->wmLButtonDown((WORD)i_wParam, (short)LOWORD(i_lParam), + (short)HIWORD(i_lParam)); + case WM_LBUTTONUP: + return wc->wmLButtonUp((WORD)i_wParam, (short)LOWORD(i_lParam), + (short)HIWORD(i_lParam)); + case WM_MOUSEMOVE: + return wc->wmMouseMove((WORD)i_wParam, (short)LOWORD(i_lParam), + (short)HIWORD(i_lParam)); + case WM_NCDESTROY: + delete wc; + return 0; + } + return DefWindowProc(i_hwnd, i_message, i_wParam, i_lParam); + } }; - + // ATOM Register_target() { - WNDCLASS wc; - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.lpfnWndProc = Target::WndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = g_hInst; - wc.hIcon = NULL; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); - wc.lpszMenuName = NULL; - wc.lpszClassName = _T("mayuTarget"); - return RegisterClass(&wc); + WNDCLASS wc; + wc.style = CS_HREDRAW | CS_VREDRAW; + wc.lpfnWndProc = Target::WndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = g_hInst; + wc.hIcon = NULL; + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wc.lpszMenuName = NULL; + wc.lpszClassName = _T("mayuTarget"); + return RegisterClass(&wc); } diff --git a/target.h b/target.h index a4f5fb0..b0dcc28 100644 --- a/target.h +++ b/target.h @@ -12,10 +12,9 @@ extern ATOM Register_target(); /// -enum -{ - /// - WM_APP_targetNotify = WM_APP + 102, +enum { + /// + WM_APP_targetNotify = WM_APP + 102, }; diff --git a/vkeytable.cpp b/vkeytable.cpp index 7a40695..2b188e4 100644 --- a/vkeytable.cpp +++ b/vkeytable.cpp @@ -7,322 +7,321 @@ // Vkey table (terminated by NULL) -const VKeyTable g_vkeyTable[] = -{ +const VKeyTable g_vkeyTable[] = { #define VK(name) { VK_##name, _T(#name) } -/* - * from WinUser.h - */ - - VK(LBUTTON), // 0x01 - VK(RBUTTON), // 0x02 - VK(CANCEL), // 0x03 - VK(MBUTTON), // 0x04 /* NOT contiguous with L & RBUTTON */ - - VK(XBUTTON1), // 0x05 /* NOT contiguous with L & RBUTTON */ - VK(XBUTTON2), // 0x06 /* NOT contiguous with L & RBUTTON */ - -/* - * 0x07 : unassigned - */ - - VK(BACK), // 0x08 - VK(TAB), // 0x09 - -/* - * 0x0A - 0x0B : reserved - */ - - VK(CLEAR), // 0x0C - VK(RETURN), // 0x0D - - VK(SHIFT), // 0x10 - VK(CONTROL), // 0x11 - VK(MENU), // 0x12 - VK(PAUSE), // 0x13 - VK(CAPITAL), // 0x14 - - VK(KANA), // 0x15 - VK(HANGEUL), // 0x15 /* old name - should be here for compatibility */ - VK(HANGUL), // 0x15 - VK(JUNJA), // 0x17 - VK(FINAL), // 0x18 - VK(HANJA), // 0x19 - VK(KANJI), // 0x19 - - VK(ESCAPE), // 0x1B - - VK(CONVERT), // 0x1C - VK(NONCONVERT), // 0x1D - VK(ACCEPT), // 0x1E - VK(MODECHANGE), // 0x1F - - VK(SPACE), // 0x20 - VK(PRIOR), // 0x21 - VK(NEXT), // 0x22 - VK(END), // 0x23 - VK(HOME), // 0x24 - VK(LEFT), // 0x25 - VK(UP), // 0x26 - VK(RIGHT), // 0x27 - VK(DOWN), // 0x28 - VK(SELECT), // 0x29 - VK(PRINT), // 0x2A - VK(EXECUTE), // 0x2B - VK(SNAPSHOT), // 0x2C - VK(INSERT), // 0x2D - VK(DELETE), // 0x2E - VK(HELP), // 0x2F - -/* - * VK_0 - VK_9 are the same as ASCII '0' - '9' (0x30 - 0x39) - * 0x40 : unassigned - * VK_A - VK_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A) - */ - - { _T('0'), _T("_0") }, // 30 0 - { _T('1'), _T("_1") }, // 31 1 - { _T('2'), _T("_2") }, // 32 2 - { _T('3'), _T("_3") }, // 33 3 - { _T('4'), _T("_4") }, // 34 4 - { _T('5'), _T("_5") }, // 35 5 - { _T('6'), _T("_6") }, // 36 6 - { _T('7'), _T("_7") }, // 37 7 - { _T('8'), _T("_8") }, // 38 8 - { _T('9'), _T("_9") }, // 39 9 - - { _T('A'), _T("A") }, // 41 A - { _T('B'), _T("B") }, // 42 B - { _T('C'), _T("C") }, // 43 C - { _T('D'), _T("D") }, // 44 D - { _T('E'), _T("E") }, // 45 E - { _T('F'), _T("F") }, // 46 F - { _T('G'), _T("G") }, // 47 G - { _T('H'), _T("H") }, // 48 H - { _T('I'), _T("I") }, // 49 I - { _T('J'), _T("J") }, // 4A J - { _T('K'), _T("K") }, // 4B K - { _T('L'), _T("L") }, // 4C L - { _T('M'), _T("M") }, // 4D M - { _T('N'), _T("N") }, // 4E N - { _T('O'), _T("O") }, // 4F O - { _T('P'), _T("P") }, // 50 P - { _T('Q'), _T("Q") }, // 51 Q - { _T('R'), _T("R") }, // 52 R - { _T('S'), _T("S") }, // 53 S - { _T('T'), _T("T") }, // 54 T - { _T('U'), _T("U") }, // 55 U - { _T('V'), _T("V") }, // 56 V - { _T('W'), _T("W") }, // 57 W - { _T('X'), _T("X") }, // 58 X - { _T('Y'), _T("Y") }, // 59 Y - { _T('Z'), _T("Z") }, // 5A Z - - VK(LWIN), // 0x5B - VK(RWIN), // 0x5C - VK(APPS), // 0x5D - -/* - * 0x5E : reserved - */ - - VK(SLEEP), // 0x5F - - VK(NUMPAD0), // 0x60 - VK(NUMPAD1), // 0x61 - VK(NUMPAD2), // 0x62 - VK(NUMPAD3), // 0x63 - VK(NUMPAD4), // 0x64 - VK(NUMPAD5), // 0x65 - VK(NUMPAD6), // 0x66 - VK(NUMPAD7), // 0x67 - VK(NUMPAD8), // 0x68 - VK(NUMPAD9), // 0x69 - VK(MULTIPLY), // 0x6A - VK(ADD), // 0x6B - VK(SEPARATOR), // 0x6C - VK(SUBTRACT), // 0x6D - VK(DECIMAL), // 0x6E - VK(DIVIDE), // 0x6F - VK(F1), // 0x70 - VK(F2), // 0x71 - VK(F3), // 0x72 - VK(F4), // 0x73 - VK(F5), // 0x74 - VK(F6), // 0x75 - VK(F7), // 0x76 - VK(F8), // 0x77 - VK(F9), // 0x78 - VK(F10), // 0x79 - VK(F11), // 0x7A - VK(F12), // 0x7B - VK(F13), // 0x7C - VK(F14), // 0x7D - VK(F15), // 0x7E - VK(F16), // 0x7F - VK(F17), // 0x80 - VK(F18), // 0x81 - VK(F19), // 0x82 - VK(F20), // 0x83 - VK(F21), // 0x84 - VK(F22), // 0x85 - VK(F23), // 0x86 - VK(F24), // 0x87 - -/* - * 0x88 - 0x8F : unassigned - */ - - VK(NUMLOCK), // 0x90 - VK(SCROLL), // 0x91 - -/* - * NEC PC-9800 kbd definitions - */ - VK(OEM_NEC_EQUAL), // 0x92 // '=' key on numpad - -/* - * Fujitsu/OASYS kbd definitions - */ - VK(OEM_FJ_JISHO), // 0x92 // 'Dictionary' key - VK(OEM_FJ_MASSHOU), // 0x93 // 'Unregister word' key - VK(OEM_FJ_TOUROKU), // 0x94 // 'Register word' key - VK(OEM_FJ_LOYA), // 0x95 // 'Left OYAYUBI' key - VK(OEM_FJ_ROYA), // 0x96 // 'Right OYAYUBI' key - -/* - * 0x97 - 0x9F : unassigned - */ - -/* - * VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys. - * Used only as parameters to GetAsyncKeyState() and GetKeyState(). - * No other API or message will distinguish left and right keys in this way. - */ - VK(LSHIFT), // 0xA0 - VK(RSHIFT), // 0xA1 - VK(LCONTROL), // 0xA2 - VK(RCONTROL), // 0xA3 - VK(LMENU), // 0xA4 - VK(RMENU), // 0xA5 - - VK(BROWSER_BACK), // 0xA6 - VK(BROWSER_FORWARD), // 0xA7 - VK(BROWSER_REFRESH), // 0xA8 - VK(BROWSER_STOP), // 0xA9 - VK(BROWSER_SEARCH), // 0xAA - VK(BROWSER_FAVORITES),// 0xAB - VK(BROWSER_HOME), // 0xAC - - VK(VOLUME_MUTE), // 0xAD - VK(VOLUME_DOWN), // 0xAE - VK(VOLUME_UP), // 0xAF - VK(MEDIA_NEXT_TRACK), // 0xB0 - VK(MEDIA_PREV_TRACK), // 0xB1 - VK(MEDIA_STOP), // 0xB2 - VK(MEDIA_PLAY_PAUSE), // 0xB3 - VK(LAUNCH_MAIL), // 0xB4 - VK(LAUNCH_MEDIA_SELECT), // 0xB5 - VK(LAUNCH_APP1), // 0xB6 - VK(LAUNCH_APP2), // 0xB7 - -/* - * 0xB8 - 0xB9 : reserved - */ - - VK(OEM_1), // 0xBA // ';:' for US - VK(OEM_PLUS), // 0xBB // '+' any country - VK(OEM_COMMA), // 0xBC // ',' any country - VK(OEM_MINUS), // 0xBD // '-' any country - VK(OEM_PERIOD), // 0xBE // '.' any country - VK(OEM_2), // 0xBF // '/?' for US - VK(OEM_3), // 0xC0 // '`~' for US - -/* - * 0xC1 - 0xD7 : reserved - */ - -/* - * 0xD8 - 0xDA : unassigned - */ - - VK(OEM_4), // 0xDB // '[{' for US - VK(OEM_5), // 0xDC // '\|' for US - VK(OEM_6), // 0xDD // ']}' for US - VK(OEM_7), // 0xDE // ''"' for US - VK(OEM_8), // 0xDF - -/* - * 0xE0 : reserved - */ - -/* - * Various extended or enhanced keyboards - */ - VK(OEM_AX), // 0xE1 // 'AX' key on Japanese AX kbd - VK(OEM_102), // 0xE2 // "<>" or "\|" on RT 102-key kbd. - VK(ICO_HELP), // 0xE3 // Help key on ICO - VK(ICO_00), // 0xE4 // 00 key on ICO - - VK(PROCESSKEY), // 0xE5 - - VK(ICO_CLEAR), // 0xE6 - - VK(PACKET), // 0xE7 - -/* - * 0xE8 : unassigned - */ - -/* - * Nokia/Ericsson definitions - */ - VK(OEM_RESET), // 0xE9 - VK(OEM_JUMP), // 0xEA - VK(OEM_PA1), // 0xEB - VK(OEM_PA2), // 0xEC - VK(OEM_PA3), // 0xED - VK(OEM_WSCTRL), // 0xEE - VK(OEM_CUSEL), // 0xEF - VK(OEM_ATTN), // 0xF0 - VK(OEM_FINISH), // 0xF1 - VK(OEM_COPY), // 0xF2 - VK(OEM_AUTO), // 0xF3 - VK(OEM_ENLW), // 0xF4 - VK(OEM_BACKTAB), // 0xF5 - - VK(ATTN), // 0xF6 - VK(CRSEL), // 0xF7 - VK(EXSEL), // 0xF8 - VK(EREOF), // 0xF9 - VK(PLAY), // 0xFA - VK(ZOOM), // 0xFB - VK(NONAME), // 0xFC - VK(PA1), // 0xFD - VK(OEM_CLEAR), // 0xFE - -/* - * from Ime.h - */ + /* + * from WinUser.h + */ + + VK(LBUTTON), // 0x01 + VK(RBUTTON), // 0x02 + VK(CANCEL), // 0x03 + VK(MBUTTON), // 0x04 /* NOT contiguous with L & RBUTTON */ + + VK(XBUTTON1), // 0x05 /* NOT contiguous with L & RBUTTON */ + VK(XBUTTON2), // 0x06 /* NOT contiguous with L & RBUTTON */ + + /* + * 0x07 : unassigned + */ + + VK(BACK), // 0x08 + VK(TAB), // 0x09 + + /* + * 0x0A - 0x0B : reserved + */ + + VK(CLEAR), // 0x0C + VK(RETURN), // 0x0D + + VK(SHIFT), // 0x10 + VK(CONTROL), // 0x11 + VK(MENU), // 0x12 + VK(PAUSE), // 0x13 + VK(CAPITAL), // 0x14 + + VK(KANA), // 0x15 + VK(HANGEUL), // 0x15 /* old name - should be here for compatibility */ + VK(HANGUL), // 0x15 + VK(JUNJA), // 0x17 + VK(FINAL), // 0x18 + VK(HANJA), // 0x19 + VK(KANJI), // 0x19 + + VK(ESCAPE), // 0x1B + + VK(CONVERT), // 0x1C + VK(NONCONVERT), // 0x1D + VK(ACCEPT), // 0x1E + VK(MODECHANGE), // 0x1F + + VK(SPACE), // 0x20 + VK(PRIOR), // 0x21 + VK(NEXT), // 0x22 + VK(END), // 0x23 + VK(HOME), // 0x24 + VK(LEFT), // 0x25 + VK(UP), // 0x26 + VK(RIGHT), // 0x27 + VK(DOWN), // 0x28 + VK(SELECT), // 0x29 + VK(PRINT), // 0x2A + VK(EXECUTE), // 0x2B + VK(SNAPSHOT), // 0x2C + VK(INSERT), // 0x2D + VK(DELETE), // 0x2E + VK(HELP), // 0x2F + + /* + * VK_0 - VK_9 are the same as ASCII '0' - '9' (0x30 - 0x39) + * 0x40 : unassigned + * VK_A - VK_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A) + */ + + { _T('0'), _T("_0") }, // 30 0 + { _T('1'), _T("_1") }, // 31 1 + { _T('2'), _T("_2") }, // 32 2 + { _T('3'), _T("_3") }, // 33 3 + { _T('4'), _T("_4") }, // 34 4 + { _T('5'), _T("_5") }, // 35 5 + { _T('6'), _T("_6") }, // 36 6 + { _T('7'), _T("_7") }, // 37 7 + { _T('8'), _T("_8") }, // 38 8 + { _T('9'), _T("_9") }, // 39 9 + + { _T('A'), _T("A") }, // 41 A + { _T('B'), _T("B") }, // 42 B + { _T('C'), _T("C") }, // 43 C + { _T('D'), _T("D") }, // 44 D + { _T('E'), _T("E") }, // 45 E + { _T('F'), _T("F") }, // 46 F + { _T('G'), _T("G") }, // 47 G + { _T('H'), _T("H") }, // 48 H + { _T('I'), _T("I") }, // 49 I + { _T('J'), _T("J") }, // 4A J + { _T('K'), _T("K") }, // 4B K + { _T('L'), _T("L") }, // 4C L + { _T('M'), _T("M") }, // 4D M + { _T('N'), _T("N") }, // 4E N + { _T('O'), _T("O") }, // 4F O + { _T('P'), _T("P") }, // 50 P + { _T('Q'), _T("Q") }, // 51 Q + { _T('R'), _T("R") }, // 52 R + { _T('S'), _T("S") }, // 53 S + { _T('T'), _T("T") }, // 54 T + { _T('U'), _T("U") }, // 55 U + { _T('V'), _T("V") }, // 56 V + { _T('W'), _T("W") }, // 57 W + { _T('X'), _T("X") }, // 58 X + { _T('Y'), _T("Y") }, // 59 Y + { _T('Z'), _T("Z") }, // 5A Z + + VK(LWIN), // 0x5B + VK(RWIN), // 0x5C + VK(APPS), // 0x5D + + /* + * 0x5E : reserved + */ + + VK(SLEEP), // 0x5F + + VK(NUMPAD0), // 0x60 + VK(NUMPAD1), // 0x61 + VK(NUMPAD2), // 0x62 + VK(NUMPAD3), // 0x63 + VK(NUMPAD4), // 0x64 + VK(NUMPAD5), // 0x65 + VK(NUMPAD6), // 0x66 + VK(NUMPAD7), // 0x67 + VK(NUMPAD8), // 0x68 + VK(NUMPAD9), // 0x69 + VK(MULTIPLY), // 0x6A + VK(ADD), // 0x6B + VK(SEPARATOR), // 0x6C + VK(SUBTRACT), // 0x6D + VK(DECIMAL), // 0x6E + VK(DIVIDE), // 0x6F + VK(F1), // 0x70 + VK(F2), // 0x71 + VK(F3), // 0x72 + VK(F4), // 0x73 + VK(F5), // 0x74 + VK(F6), // 0x75 + VK(F7), // 0x76 + VK(F8), // 0x77 + VK(F9), // 0x78 + VK(F10), // 0x79 + VK(F11), // 0x7A + VK(F12), // 0x7B + VK(F13), // 0x7C + VK(F14), // 0x7D + VK(F15), // 0x7E + VK(F16), // 0x7F + VK(F17), // 0x80 + VK(F18), // 0x81 + VK(F19), // 0x82 + VK(F20), // 0x83 + VK(F21), // 0x84 + VK(F22), // 0x85 + VK(F23), // 0x86 + VK(F24), // 0x87 + + /* + * 0x88 - 0x8F : unassigned + */ + + VK(NUMLOCK), // 0x90 + VK(SCROLL), // 0x91 + + /* + * NEC PC-9800 kbd definitions + */ + VK(OEM_NEC_EQUAL), // 0x92 // '=' key on numpad + + /* + * Fujitsu/OASYS kbd definitions + */ + VK(OEM_FJ_JISHO), // 0x92 // 'Dictionary' key + VK(OEM_FJ_MASSHOU), // 0x93 // 'Unregister word' key + VK(OEM_FJ_TOUROKU), // 0x94 // 'Register word' key + VK(OEM_FJ_LOYA), // 0x95 // 'Left OYAYUBI' key + VK(OEM_FJ_ROYA), // 0x96 // 'Right OYAYUBI' key + + /* + * 0x97 - 0x9F : unassigned + */ + + /* + * VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys. + * Used only as parameters to GetAsyncKeyState() and GetKeyState(). + * No other API or message will distinguish left and right keys in this way. + */ + VK(LSHIFT), // 0xA0 + VK(RSHIFT), // 0xA1 + VK(LCONTROL), // 0xA2 + VK(RCONTROL), // 0xA3 + VK(LMENU), // 0xA4 + VK(RMENU), // 0xA5 + + VK(BROWSER_BACK), // 0xA6 + VK(BROWSER_FORWARD), // 0xA7 + VK(BROWSER_REFRESH), // 0xA8 + VK(BROWSER_STOP), // 0xA9 + VK(BROWSER_SEARCH), // 0xAA + VK(BROWSER_FAVORITES),// 0xAB + VK(BROWSER_HOME), // 0xAC + + VK(VOLUME_MUTE), // 0xAD + VK(VOLUME_DOWN), // 0xAE + VK(VOLUME_UP), // 0xAF + VK(MEDIA_NEXT_TRACK), // 0xB0 + VK(MEDIA_PREV_TRACK), // 0xB1 + VK(MEDIA_STOP), // 0xB2 + VK(MEDIA_PLAY_PAUSE), // 0xB3 + VK(LAUNCH_MAIL), // 0xB4 + VK(LAUNCH_MEDIA_SELECT), // 0xB5 + VK(LAUNCH_APP1), // 0xB6 + VK(LAUNCH_APP2), // 0xB7 + + /* + * 0xB8 - 0xB9 : reserved + */ + + VK(OEM_1), // 0xBA // ';:' for US + VK(OEM_PLUS), // 0xBB // '+' any country + VK(OEM_COMMA), // 0xBC // ',' any country + VK(OEM_MINUS), // 0xBD // '-' any country + VK(OEM_PERIOD), // 0xBE // '.' any country + VK(OEM_2), // 0xBF // '/?' for US + VK(OEM_3), // 0xC0 // '`~' for US + + /* + * 0xC1 - 0xD7 : reserved + */ + + /* + * 0xD8 - 0xDA : unassigned + */ + + VK(OEM_4), // 0xDB // '[{' for US + VK(OEM_5), // 0xDC // '\|' for US + VK(OEM_6), // 0xDD // ']}' for US + VK(OEM_7), // 0xDE // ''"' for US + VK(OEM_8), // 0xDF + + /* + * 0xE0 : reserved + */ + + /* + * Various extended or enhanced keyboards + */ + VK(OEM_AX), // 0xE1 // 'AX' key on Japanese AX kbd + VK(OEM_102), // 0xE2 // "<>" or "\|" on RT 102-key kbd. + VK(ICO_HELP), // 0xE3 // Help key on ICO + VK(ICO_00), // 0xE4 // 00 key on ICO + + VK(PROCESSKEY), // 0xE5 + + VK(ICO_CLEAR), // 0xE6 + + VK(PACKET), // 0xE7 + + /* + * 0xE8 : unassigned + */ + + /* + * Nokia/Ericsson definitions + */ + VK(OEM_RESET), // 0xE9 + VK(OEM_JUMP), // 0xEA + VK(OEM_PA1), // 0xEB + VK(OEM_PA2), // 0xEC + VK(OEM_PA3), // 0xED + VK(OEM_WSCTRL), // 0xEE + VK(OEM_CUSEL), // 0xEF + VK(OEM_ATTN), // 0xF0 + VK(OEM_FINISH), // 0xF1 + VK(OEM_COPY), // 0xF2 + VK(OEM_AUTO), // 0xF3 + VK(OEM_ENLW), // 0xF4 + VK(OEM_BACKTAB), // 0xF5 + + VK(ATTN), // 0xF6 + VK(CRSEL), // 0xF7 + VK(EXSEL), // 0xF8 + VK(EREOF), // 0xF9 + VK(PLAY), // 0xFA + VK(ZOOM), // 0xFB + VK(NONAME), // 0xFC + VK(PA1), // 0xFD + VK(OEM_CLEAR), // 0xFE + + /* + * from Ime.h + */ #if !defined(VK_DBE_ALPHANUMERIC) - VK(DBE_ALPHANUMERIC), // 0x0f0 - VK(DBE_KATAKANA), // 0x0f1 - VK(DBE_HIRAGANA), // 0x0f2 - VK(DBE_SBCSCHAR), // 0x0f3 - VK(DBE_DBCSCHAR), // 0x0f4 - VK(DBE_ROMAN), // 0x0f5 - VK(DBE_NOROMAN), // 0x0f6 - VK(DBE_ENTERWORDREGISTERMODE), // 0x0f7 - VK(DBE_ENTERIMECONFIGMODE), // 0x0f8 - VK(DBE_FLUSHSTRING), // 0x0f9 - VK(DBE_CODEINPUT), // 0x0fa - VK(DBE_NOCODEINPUT), // 0x0fb - VK(DBE_DETERMINESTRING), // 0x0fc - VK(DBE_ENTERDLGCONVERSIONMODE), // 0x0fd + VK(DBE_ALPHANUMERIC), // 0x0f0 + VK(DBE_KATAKANA), // 0x0f1 + VK(DBE_HIRAGANA), // 0x0f2 + VK(DBE_SBCSCHAR), // 0x0f3 + VK(DBE_DBCSCHAR), // 0x0f4 + VK(DBE_ROMAN), // 0x0f5 + VK(DBE_NOROMAN), // 0x0f6 + VK(DBE_ENTERWORDREGISTERMODE), // 0x0f7 + VK(DBE_ENTERIMECONFIGMODE), // 0x0f8 + VK(DBE_FLUSHSTRING), // 0x0f9 + VK(DBE_CODEINPUT), // 0x0fa + VK(DBE_NOCODEINPUT), // 0x0fb + VK(DBE_DETERMINESTRING), // 0x0fc + VK(DBE_ENTERDLGCONVERSIONMODE), // 0x0fd #endif - { 0, NULL }, + { 0, NULL }, #undef VK }; diff --git a/vkeytable.h b/vkeytable.h index ed62e86..8d82e81 100644 --- a/vkeytable.h +++ b/vkeytable.h @@ -13,8 +13,8 @@ class VKeyTable { public: - u_int8 m_code; /// VKey code - const _TCHAR *m_name; /// VKey name + u_int8 m_code; /// VKey code + const _TCHAR *m_name; /// VKey name }; extern const VKeyTable g_vkeyTable[]; /** Vkey table (terminated by diff --git a/windowstool.cpp b/windowstool.cpp index 6d7ea12..5ea73e1 100644 --- a/windowstool.cpp +++ b/windowstool.cpp @@ -27,27 +27,27 @@ HINSTANCE g_hInst = NULL; // load resource string tstring loadString(UINT i_id) { - _TCHAR buf[1024]; - if (LoadString(g_hInst, i_id, buf, NUMBER_OF(buf))) - return tstring(buf); - else - return _T(""); + _TCHAR buf[1024]; + if (LoadString(g_hInst, i_id, buf, NUMBER_OF(buf))) + return tstring(buf); + else + return _T(""); } // load small icon resource HICON loadSmallIcon(UINT i_id) { - return reinterpret_cast( - LoadImage(g_hInst, MAKEINTRESOURCE(i_id), IMAGE_ICON, 16, 16, 0)); + return reinterpret_cast( + LoadImage(g_hInst, MAKEINTRESOURCE(i_id), IMAGE_ICON, 16, 16, 0)); } // load big icon resource HICON loadBigIcon(UINT i_id) { - return reinterpret_cast( - LoadImage(g_hInst, MAKEINTRESOURCE(i_id), IMAGE_ICON, 32, 32, 0)); + return reinterpret_cast( + LoadImage(g_hInst, MAKEINTRESOURCE(i_id), IMAGE_ICON, 32, 32, 0)); } @@ -55,10 +55,10 @@ HICON loadBigIcon(UINT i_id) // @return handle of previous icon or NULL HICON setSmallIcon(HWND i_hwnd, UINT i_id) { - HICON hicon = (i_id == static_cast(-1)) ? NULL : loadSmallIcon(i_id); - return reinterpret_cast( - SendMessage(i_hwnd, WM_SETICON, static_cast(ICON_SMALL), - reinterpret_cast(hicon))); + HICON hicon = (i_id == static_cast(-1)) ? NULL : loadSmallIcon(i_id); + return reinterpret_cast( + SendMessage(i_hwnd, WM_SETICON, static_cast(ICON_SMALL), + reinterpret_cast(hicon))); } @@ -66,38 +66,38 @@ HICON setSmallIcon(HWND i_hwnd, UINT i_id) // @return handle of previous icon or NULL HICON setBigIcon(HWND i_hwnd, UINT i_id) { - HICON hicon = (i_id == static_cast(-1)) ? NULL : loadBigIcon(i_id); - return reinterpret_cast( - SendMessage(i_hwnd, WM_SETICON, static_cast(ICON_BIG), - reinterpret_cast(hicon))); + HICON hicon = (i_id == static_cast(-1)) ? NULL : loadBigIcon(i_id); + return reinterpret_cast( + SendMessage(i_hwnd, WM_SETICON, static_cast(ICON_BIG), + reinterpret_cast(hicon))); } // remove icon from a window that is set by setSmallIcon void unsetSmallIcon(HWND i_hwnd) { - HICON hicon = setSmallIcon(i_hwnd, -1); - if (hicon) - CHECK_TRUE( DestroyIcon(hicon) ); + HICON hicon = setSmallIcon(i_hwnd, -1); + if (hicon) + CHECK_TRUE( DestroyIcon(hicon) ); } // remove icon from a window that is set by setBigIcon void unsetBigIcon(HWND i_hwnd) { - HICON hicon = setBigIcon(i_hwnd, -1); - if (hicon) - CHECK_TRUE( DestroyIcon(hicon) ); + HICON hicon = setBigIcon(i_hwnd, -1); + if (hicon) + CHECK_TRUE( DestroyIcon(hicon) ); } // resize the window (it does not move the window) bool resizeWindow(HWND i_hwnd, int i_w, int i_h, bool i_doRepaint) { - UINT flag = SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER; - if (!i_doRepaint) - flag |= SWP_NOREDRAW; - return !!SetWindowPos(i_hwnd, NULL, 0, 0, i_w, i_h, flag); + UINT flag = SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER; + if (!i_doRepaint) + flag |= SWP_NOREDRAW; + return !!SetWindowPos(i_hwnd, NULL, 0, 0, i_w, i_h, flag); } @@ -105,133 +105,129 @@ bool resizeWindow(HWND i_hwnd, int i_w, int i_h, bool i_doRepaint) // @return rect of the window in client coordinates bool getChildWindowRect(HWND i_hwnd, RECT *o_rc) { - if (!GetWindowRect(i_hwnd, o_rc)) - return false; - POINT p = { o_rc->left, o_rc->top }; - HWND phwnd = GetParent(i_hwnd); - if (!phwnd) - return false; - if (!ScreenToClient(phwnd, &p)) - return false; - o_rc->left = p.x; - o_rc->top = p.y; - p.x = o_rc->right; - p.y = o_rc->bottom; - ScreenToClient(phwnd, &p); - o_rc->right = p.x; - o_rc->bottom = p.y; - return true; + if (!GetWindowRect(i_hwnd, o_rc)) + return false; + POINT p = { o_rc->left, o_rc->top }; + HWND phwnd = GetParent(i_hwnd); + if (!phwnd) + return false; + if (!ScreenToClient(phwnd, &p)) + return false; + o_rc->left = p.x; + o_rc->top = p.y; + p.x = o_rc->right; + p.y = o_rc->bottom; + ScreenToClient(phwnd, &p); + o_rc->right = p.x; + o_rc->bottom = p.y; + return true; } // get toplevel (non-child) window HWND getToplevelWindow(HWND i_hwnd, bool *io_isMDI) { - while (i_hwnd) - { + while (i_hwnd) { #ifdef MAYU64 - LONG_PTR style = GetWindowLongPtr(i_hwnd, GWL_STYLE); + LONG_PTR style = GetWindowLongPtr(i_hwnd, GWL_STYLE); #else - LONG style = GetWindowLong(i_hwnd, GWL_STYLE); + LONG style = GetWindowLong(i_hwnd, GWL_STYLE); #endif - if ((style & WS_CHILD) == 0) - break; - if (io_isMDI && *io_isMDI) - { + if ((style & WS_CHILD) == 0) + break; + if (io_isMDI && *io_isMDI) { #ifdef MAYU64 - LONG_PTR exStyle = GetWindowLongPtr(i_hwnd, GWL_EXSTYLE); + LONG_PTR exStyle = GetWindowLongPtr(i_hwnd, GWL_EXSTYLE); #else - LONG exStyle = GetWindowLong(i_hwnd, GWL_EXSTYLE); + LONG exStyle = GetWindowLong(i_hwnd, GWL_EXSTYLE); #endif - if (exStyle & WS_EX_MDICHILD) + if (exStyle & WS_EX_MDICHILD) + return i_hwnd; + } + i_hwnd = GetParent(i_hwnd); + } + if (io_isMDI) + *io_isMDI = false; return i_hwnd; - } - i_hwnd = GetParent(i_hwnd); - } - if (io_isMDI) - *io_isMDI = false; - return i_hwnd; } // move window asynchronously void asyncMoveWindow(HWND i_hwnd, int i_x, int i_y) { - SetWindowPos(i_hwnd, NULL, i_x, i_y, 0, 0, - SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER | - SWP_NOSIZE | SWP_NOZORDER); + SetWindowPos(i_hwnd, NULL, i_x, i_y, 0, 0, + SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER | + SWP_NOSIZE | SWP_NOZORDER); } // move window asynchronously void asyncMoveWindow(HWND i_hwnd, int i_x, int i_y, int i_w, int i_h) { - SetWindowPos(i_hwnd, NULL, i_x, i_y, i_w, i_h, - SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER | - SWP_NOZORDER); + SetWindowPos(i_hwnd, NULL, i_x, i_y, i_w, i_h, + SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER | + SWP_NOZORDER); } // resize asynchronously void asyncResize(HWND i_hwnd, int i_w, int i_h) { - SetWindowPos(i_hwnd, NULL, 0, 0, i_w, i_h, - SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER | - SWP_NOMOVE | SWP_NOZORDER); + SetWindowPos(i_hwnd, NULL, 0, 0, i_w, i_h, + SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOOWNERZORDER | + SWP_NOMOVE | SWP_NOZORDER); } // get dll version DWORD getDllVersion(const _TCHAR *i_dllname) { - DWORD dwVersion = 0; - - if (HINSTANCE hinstDll = LoadLibrary(i_dllname)) - { - DLLGETVERSIONPROC pDllGetVersion - = (DLLGETVERSIONPROC)GetProcAddress(hinstDll, "DllGetVersion"); - /* Because some DLLs may not implement this function, you - * must test for it explicitly. Depending on the particular - * DLL, the lack of a DllGetVersion function may - * be a useful indicator of the version. - */ - if (pDllGetVersion) - { - DLLVERSIONINFO dvi; - ZeroMemory(&dvi, sizeof(dvi)); - dvi.cbSize = sizeof(dvi); - - HRESULT hr = (*pDllGetVersion)(&dvi); - if (SUCCEEDED(hr)) - dwVersion = PACKVERSION(dvi.dwMajorVersion, dvi.dwMinorVersion); - } - - FreeLibrary(hinstDll); - } - return dwVersion; + DWORD dwVersion = 0; + + if (HINSTANCE hinstDll = LoadLibrary(i_dllname)) { + DLLGETVERSIONPROC pDllGetVersion + = (DLLGETVERSIONPROC)GetProcAddress(hinstDll, "DllGetVersion"); + /* Because some DLLs may not implement this function, you + * must test for it explicitly. Depending on the particular + * DLL, the lack of a DllGetVersion function may + * be a useful indicator of the version. + */ + if (pDllGetVersion) { + DLLVERSIONINFO dvi; + ZeroMemory(&dvi, sizeof(dvi)); + dvi.cbSize = sizeof(dvi); + + HRESULT hr = (*pDllGetVersion)(&dvi); + if (SUCCEEDED(hr)) + dwVersion = PACKVERSION(dvi.dwMajorVersion, dvi.dwMinorVersion); + } + + FreeLibrary(hinstDll); + } + return dwVersion; } // workaround of SetForegroundWindow bool setForegroundWindow(HWND i_hwnd) { - int nForegroundID = GetWindowThreadProcessId(GetForegroundWindow(), NULL); - int nTargetID = GetWindowThreadProcessId(i_hwnd, NULL); - - //if (!AttachThreadInput(nTargetID, nForegroundID, TRUE)) - //return false; - AttachThreadInput(nTargetID, nForegroundID, TRUE); - - DWORD sp_time; - SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &sp_time, 0); - SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (void *)0, 0); - - SetForegroundWindow(i_hwnd); - - SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (void *)sp_time, 0); - - AttachThreadInput(nTargetID, nForegroundID, FALSE); - return true; + int nForegroundID = GetWindowThreadProcessId(GetForegroundWindow(), NULL); + int nTargetID = GetWindowThreadProcessId(i_hwnd, NULL); + + //if (!AttachThreadInput(nTargetID, nForegroundID, TRUE)) + //return false; + AttachThreadInput(nTargetID, nForegroundID, TRUE); + + DWORD sp_time; + SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &sp_time, 0); + SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (void *)0, 0); + + SetForegroundWindow(i_hwnd); + + SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (void *)sp_time, 0); + + AttachThreadInput(nTargetID, nForegroundID, FALSE); + return true; } @@ -244,55 +240,53 @@ bool setForegroundWindow(HWND i_hwnd) // @return bytes of text size_t editGetTextBytes(HWND i_hwnd) { - return Edit_GetTextLength(i_hwnd); + return Edit_GetTextLength(i_hwnd); } // delete a line void editDeleteLine(HWND i_hwnd, size_t i_n) { - int len = Edit_LineLength(i_hwnd, i_n); - if (len < 0) - return; - len += 2; - int index = Edit_LineIndex(i_hwnd, i_n); - Edit_SetSel(i_hwnd, index, index + len); - Edit_ReplaceSel(i_hwnd, _T("")); + int len = Edit_LineLength(i_hwnd, i_n); + if (len < 0) + return; + len += 2; + int index = Edit_LineIndex(i_hwnd, i_n); + Edit_SetSel(i_hwnd, index, index + len); + Edit_ReplaceSel(i_hwnd, _T("")); } - + // insert text at last void editInsertTextAtLast(HWND i_hwnd, const tstring &i_text, - size_t i_threshold) + size_t i_threshold) { - if (i_text.empty()) - return; - - size_t len = editGetTextBytes(i_hwnd); - - if (i_threshold < len) - { - Edit_SetSel(i_hwnd, 0, len / 3 * 2); - Edit_ReplaceSel(i_hwnd, _T("")); - editDeleteLine(i_hwnd, 0); - len = editGetTextBytes(i_hwnd); - } - - Edit_SetSel(i_hwnd, len, len); - - // \n -> \r\n - Array<_TCHAR> buf(i_text.size() * 2 + 1); - _TCHAR *d = buf.get(); - const _TCHAR *str = i_text.c_str(); - for (const _TCHAR *s = str; s < str + i_text.size(); ++ s) - { - if (*s == _T('\n')) - *d++ = _T('\r'); - *d++ = *s; - } - *d = _T('\0'); - - Edit_ReplaceSel(i_hwnd, buf.get()); + if (i_text.empty()) + return; + + size_t len = editGetTextBytes(i_hwnd); + + if (i_threshold < len) { + Edit_SetSel(i_hwnd, 0, len / 3 * 2); + Edit_ReplaceSel(i_hwnd, _T("")); + editDeleteLine(i_hwnd, 0); + len = editGetTextBytes(i_hwnd); + } + + Edit_SetSel(i_hwnd, len, len); + + // \n -> \r\n + Array<_TCHAR> buf(i_text.size() * 2 + 1); + _TCHAR *d = buf.get(); + const _TCHAR *str = i_text.c_str(); + for (const _TCHAR *s = str; s < str + i_text.size(); ++ s) { + if (*s == _T('\n')) + *d++ = _T('\r'); + *d++ = *s; + } + *d = _T('\0'); + + Edit_ReplaceSel(i_hwnd, buf.get()); } @@ -302,128 +296,128 @@ void editInsertTextAtLast(HWND i_hwnd, const tstring &i_text, // initialize layerd window static BOOL WINAPI initalizeLayerdWindow( - HWND i_hwnd, COLORREF i_crKey, BYTE i_bAlpha, DWORD i_dwFlags) + HWND i_hwnd, COLORREF i_crKey, BYTE i_bAlpha, DWORD i_dwFlags) { - HMODULE hModule = GetModuleHandle(_T("user32.dll")); - if (!hModule) { - return FALSE; - } - SetLayeredWindowAttributes_t proc = - reinterpret_cast( - GetProcAddress(hModule, "SetLayeredWindowAttributes")); - if (setLayeredWindowAttributes) { - setLayeredWindowAttributes = proc; - return setLayeredWindowAttributes(i_hwnd, i_crKey, i_bAlpha, i_dwFlags); - } else { - return FALSE; - } + HMODULE hModule = GetModuleHandle(_T("user32.dll")); + if (!hModule) { + return FALSE; + } + SetLayeredWindowAttributes_t proc = + reinterpret_cast( + GetProcAddress(hModule, "SetLayeredWindowAttributes")); + if (setLayeredWindowAttributes) { + setLayeredWindowAttributes = proc; + return setLayeredWindowAttributes(i_hwnd, i_crKey, i_bAlpha, i_dwFlags); + } else { + return FALSE; + } } // SetLayeredWindowAttributes API SetLayeredWindowAttributes_t setLayeredWindowAttributes - = initalizeLayerdWindow; += initalizeLayerdWindow; // emulate MonitorFromWindow API static HMONITOR WINAPI emulateMonitorFromWindow(HWND hwnd, DWORD dwFlags) { - return reinterpret_cast(1); // dummy HMONITOR + return reinterpret_cast(1); // dummy HMONITOR } // initialize MonitorFromWindow API static HMONITOR WINAPI initializeMonitorFromWindow(HWND hwnd, DWORD dwFlags) { - HMODULE hModule = GetModuleHandle(_T("user32.dll")); - if (!hModule) - return FALSE; - - FARPROC proc = GetProcAddress(hModule, "MonitorFromWindow"); - if(proc) - monitorFromWindow = - reinterpret_cast(proc); - else - monitorFromWindow = emulateMonitorFromWindow; - - return monitorFromWindow(hwnd, dwFlags); + HMODULE hModule = GetModuleHandle(_T("user32.dll")); + if (!hModule) + return FALSE; + + FARPROC proc = GetProcAddress(hModule, "MonitorFromWindow"); + if (proc) + monitorFromWindow = + reinterpret_cast(proc); + else + monitorFromWindow = emulateMonitorFromWindow; + + return monitorFromWindow(hwnd, dwFlags); } // MonitorFromWindow API HMONITOR (WINAPI *monitorFromWindow)(HWND hwnd, DWORD dwFlags) - = initializeMonitorFromWindow; += initializeMonitorFromWindow; // emulate GetMonitorInfo API static BOOL WINAPI emulateGetMonitorInfo(HMONITOR hMonitor, LPMONITORINFO lpmi) { - if(lpmi->cbSize != sizeof(MONITORINFO)) - return FALSE; - - lpmi->rcMonitor.left = 0; - lpmi->rcMonitor.top = 0; - lpmi->rcMonitor.right = GetSystemMetrics(SM_CXFULLSCREEN); - lpmi->rcMonitor.bottom = GetSystemMetrics(SM_CYFULLSCREEN); - SystemParametersInfo(SPI_GETWORKAREA, 0, - reinterpret_cast(&lpmi->rcWork), FALSE); - lpmi->dwFlags = MONITORINFOF_PRIMARY; - - return TRUE; + if (lpmi->cbSize != sizeof(MONITORINFO)) + return FALSE; + + lpmi->rcMonitor.left = 0; + lpmi->rcMonitor.top = 0; + lpmi->rcMonitor.right = GetSystemMetrics(SM_CXFULLSCREEN); + lpmi->rcMonitor.bottom = GetSystemMetrics(SM_CYFULLSCREEN); + SystemParametersInfo(SPI_GETWORKAREA, 0, + reinterpret_cast(&lpmi->rcWork), FALSE); + lpmi->dwFlags = MONITORINFOF_PRIMARY; + + return TRUE; } // initialize GetMonitorInfo API static BOOL WINAPI initializeGetMonitorInfo(HMONITOR hMonitor, LPMONITORINFO lpmi) { - HMODULE hModule = GetModuleHandle(_T("user32.dll")); - if (!hModule) - return FALSE; - - FARPROC proc = GetProcAddress(hModule, "GetMonitorInfoA"); - if(proc) - getMonitorInfo = - reinterpret_cast(proc); - else - getMonitorInfo = emulateGetMonitorInfo; - - return getMonitorInfo(hMonitor, lpmi); + HMODULE hModule = GetModuleHandle(_T("user32.dll")); + if (!hModule) + return FALSE; + + FARPROC proc = GetProcAddress(hModule, "GetMonitorInfoA"); + if (proc) + getMonitorInfo = + reinterpret_cast(proc); + else + getMonitorInfo = emulateGetMonitorInfo; + + return getMonitorInfo(hMonitor, lpmi); } // GetMonitorInfo API BOOL (WINAPI *getMonitorInfo)(HMONITOR hMonitor, LPMONITORINFO lpmi) - = initializeGetMonitorInfo; += initializeGetMonitorInfo; // enumalte EnumDisplayMonitors API static BOOL WINAPI emulateEnumDisplayMonitors( - HDC hdc, LPRECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData) + HDC hdc, LPRECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData) { - lpfnEnum(reinterpret_cast(1), hdc, lprcClip, dwData); - return TRUE; + lpfnEnum(reinterpret_cast(1), hdc, lprcClip, dwData); + return TRUE; } // initialize EnumDisplayMonitors API static BOOL WINAPI initializeEnumDisplayMonitors( - HDC hdc, LPRECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData) + HDC hdc, LPRECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData) { - HMODULE hModule = GetModuleHandle(_T("user32.dll")); - if (!hModule) - return FALSE; - - FARPROC proc = GetProcAddress(hModule, "EnumDisplayMonitors"); - if(proc) - enumDisplayMonitors = - reinterpret_cast - (proc); - else - enumDisplayMonitors = emulateEnumDisplayMonitors; - - return enumDisplayMonitors(hdc, lprcClip, lpfnEnum, dwData); + HMODULE hModule = GetModuleHandle(_T("user32.dll")); + if (!hModule) + return FALSE; + + FARPROC proc = GetProcAddress(hModule, "EnumDisplayMonitors"); + if (proc) + enumDisplayMonitors = + reinterpret_cast + (proc); + else + enumDisplayMonitors = emulateEnumDisplayMonitors; + + return enumDisplayMonitors(hdc, lprcClip, lpfnEnum, dwData); } // EnumDisplayMonitors API BOOL (WINAPI *enumDisplayMonitors) - (HDC hdc, LPRECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData) - = initializeEnumDisplayMonitors; +(HDC hdc, LPRECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData) += initializeEnumDisplayMonitors; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -433,69 +427,69 @@ BOOL (WINAPI *enumDisplayMonitors) static BOOL WINAPI initializeWTSRegisterSessionNotification(HWND hWnd, DWORD dwFlags) { - LoadLibrary(_T("wtsapi32.dll")); - HMODULE hModule = GetModuleHandle(_T("wtsapi32.dll")); - if (!hModule) { - return FALSE; - } - WTSRegisterSessionNotification_t proc = - reinterpret_cast( - GetProcAddress(hModule, "WTSRegisterSessionNotification")); - if (proc) { - wtsRegisterSessionNotification = proc; - return wtsRegisterSessionNotification(hWnd, dwFlags); - } else { - return 0; - } + LoadLibrary(_T("wtsapi32.dll")); + HMODULE hModule = GetModuleHandle(_T("wtsapi32.dll")); + if (!hModule) { + return FALSE; + } + WTSRegisterSessionNotification_t proc = + reinterpret_cast( + GetProcAddress(hModule, "WTSRegisterSessionNotification")); + if (proc) { + wtsRegisterSessionNotification = proc; + return wtsRegisterSessionNotification(hWnd, dwFlags); + } else { + return 0; + } } // WTSRegisterSessionNotification API WTSRegisterSessionNotification_t wtsRegisterSessionNotification - = initializeWTSRegisterSessionNotification; += initializeWTSRegisterSessionNotification; static BOOL WINAPI initializeWTSUnRegisterSessionNotification(HWND hWnd) { - HMODULE hModule = GetModuleHandle(_T("wtsapi32.dll")); - if (!hModule) { - return FALSE; - } - WTSUnRegisterSessionNotification_t proc = - reinterpret_cast( - GetProcAddress(hModule, "WTSUnRegisterSessionNotification")); - if (proc) { - wtsUnRegisterSessionNotification = proc; - return wtsUnRegisterSessionNotification(hWnd); - } else { - return 0; - } + HMODULE hModule = GetModuleHandle(_T("wtsapi32.dll")); + if (!hModule) { + return FALSE; + } + WTSUnRegisterSessionNotification_t proc = + reinterpret_cast( + GetProcAddress(hModule, "WTSUnRegisterSessionNotification")); + if (proc) { + wtsUnRegisterSessionNotification = proc; + return wtsUnRegisterSessionNotification(hWnd); + } else { + return 0; + } } // WTSUnRegisterSessionNotification API WTSUnRegisterSessionNotification_t wtsUnRegisterSessionNotification - = initializeWTSUnRegisterSessionNotification; += initializeWTSUnRegisterSessionNotification; static DWORD WINAPI initializeWTSGetActiveConsoleSessionId(void) { - HMODULE hModule = GetModuleHandle(_T("kernel32.dll")); - if (!hModule) { - return FALSE; - } - WTSGetActiveConsoleSessionId_t proc = - reinterpret_cast( - GetProcAddress(hModule, "WTSGetActiveConsoleSessionId")); - if (proc) { - wtsGetActiveConsoleSessionId = proc; - return wtsGetActiveConsoleSessionId(); - } else { - return 0; - } + HMODULE hModule = GetModuleHandle(_T("kernel32.dll")); + if (!hModule) { + return FALSE; + } + WTSGetActiveConsoleSessionId_t proc = + reinterpret_cast( + GetProcAddress(hModule, "WTSGetActiveConsoleSessionId")); + if (proc) { + wtsGetActiveConsoleSessionId = proc; + return wtsGetActiveConsoleSessionId(); + } else { + return 0; + } } // WTSGetActiveConsoleSessionId API WTSGetActiveConsoleSessionId_t wtsGetActiveConsoleSessionId - = initializeWTSGetActiveConsoleSessionId; += initializeWTSGetActiveConsoleSessionId; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -504,16 +498,16 @@ WTSGetActiveConsoleSessionId_t wtsGetActiveConsoleSessionId // PathRemoveFileSpec() tstring pathRemoveFileSpec(const tstring &i_path) { - const _TCHAR *str = i_path.c_str(); - const _TCHAR *b = _tcsrchr(str, _T('\\')); - const _TCHAR *s = _tcsrchr(str, _T('/')); - if (b && s) - return tstring(str, MIN(b, s)); - if (b) - return tstring(str, b); - if (s) - return tstring(str, s); - if (const _TCHAR *c = _tcsrchr(str, _T(':'))) - return tstring(str, c + 1); - return i_path; + const _TCHAR *str = i_path.c_str(); + const _TCHAR *b = _tcsrchr(str, _T('\\')); + const _TCHAR *s = _tcsrchr(str, _T('/')); + if (b && s) + return tstring(str, MIN(b, s)); + if (b) + return tstring(str, b); + if (s) + return tstring(str, s); + if (const _TCHAR *c = _tcsrchr(str, _T(':'))) + return tstring(str, c + 1); + return i_path; } diff --git a/windowstool.h b/windowstool.h index c8c662b..71c4728 100644 --- a/windowstool.h +++ b/windowstool.h @@ -77,9 +77,9 @@ extern bool setForegroundWindow(HWND i_hwnd); template inline T getUserData(HWND i_hwnd, T *i_wc) { #ifdef MAYU64 - return (*i_wc = reinterpret_cast(GetWindowLongPtr(i_hwnd, GWLP_USERDATA))); + return (*i_wc = reinterpret_cast(GetWindowLongPtr(i_hwnd, GWLP_USERDATA))); #else - return (*i_wc = reinterpret_cast(GetWindowLong(i_hwnd, GWL_USERDATA))); + return (*i_wc = reinterpret_cast(GetWindowLong(i_hwnd, GWL_USERDATA))); #endif } @@ -87,11 +87,11 @@ template inline T getUserData(HWND i_hwnd, T *i_wc) template inline T setUserData(HWND i_hwnd, T i_wc) { #ifdef MAYU64 - SetWindowLongPtr(i_hwnd, GWLP_USERDATA, reinterpret_cast(i_wc)); + SetWindowLongPtr(i_hwnd, GWLP_USERDATA, reinterpret_cast(i_wc)); #else - SetWindowLong(i_hwnd, GWL_USERDATA, reinterpret_cast(i_wc)); + SetWindowLong(i_hwnd, GWL_USERDATA, reinterpret_cast(i_wc)); #endif - return i_wc; + return i_wc; } @@ -99,18 +99,24 @@ template inline T setUserData(HWND i_hwnd, T i_wc) // RECT /// -inline int rcWidth(const RECT *i_rc) { return i_rc->right - i_rc->left; } +inline int rcWidth(const RECT *i_rc) +{ + return i_rc->right - i_rc->left; +} /// -inline int rcHeight(const RECT *i_rc) { return i_rc->bottom - i_rc->top; } +inline int rcHeight(const RECT *i_rc) +{ + return i_rc->bottom - i_rc->top; +} /// inline bool isRectInRect(const RECT *i_rcin, const RECT *i_rcout) { - return (i_rcout->left <= i_rcin->left && - i_rcin->right <= i_rcout->right && - i_rcout->top <= i_rcin->top && - i_rcin->bottom <= i_rcout->bottom); + return (i_rcout->left <= i_rcin->left && + i_rcin->right <= i_rcout->right && + i_rcout->top <= i_rcin->top && + i_rcin->bottom <= i_rcout->bottom); } @@ -125,7 +131,7 @@ extern void editDeleteLine(HWND i_hwnd, size_t i_n); /// insert text at last extern void editInsertTextAtLast(HWND i_hwnd, const tstring &i_text, - size_t i_threshold); + size_t i_threshold); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -133,7 +139,7 @@ extern void editInsertTextAtLast(HWND i_hwnd, const tstring &i_text, /// SetLayeredWindowAttributes API typedef BOOL (WINAPI *SetLayeredWindowAttributes_t) - (HWND hwnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags); +(HWND hwnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags); extern SetLayeredWindowAttributes_t setLayeredWindowAttributes; /// MonitorFromWindow API @@ -144,7 +150,7 @@ extern BOOL (WINAPI *getMonitorInfo)(HMONITOR hMonitor, LPMONITORINFO lpmi); /// EnumDisplayMonitors API extern BOOL (WINAPI *enumDisplayMonitors) - (HDC hdc, LPRECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData); + (HDC hdc, LPRECT lprcClip, MONITORENUMPROC lpfnEnum, LPARAM dwData); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -152,7 +158,7 @@ extern BOOL (WINAPI *enumDisplayMonitors) /// WTSRegisterSessionNotification API typedef BOOL (WINAPI *WTSRegisterSessionNotification_t) - (HWND hWnd, DWORD dwFlags); +(HWND hWnd, DWORD dwFlags); extern WTSRegisterSessionNotification_t wtsRegisterSessionNotification; /// WTSUnRegisterSessionNotification API diff --git a/yamy.cpp b/yamy.cpp old mode 100755 new mode 100644 index be64fc9..b05d808 --- a/yamy.cpp +++ b/yamy.cpp @@ -7,54 +7,49 @@ /// main int WINAPI _tWinMain(HINSTANCE i_hInstance, HINSTANCE /* i_hPrevInstance */, - LPTSTR /* i_lpszCmdLine */, int /* i_nCmdShow */) + LPTSTR /* i_lpszCmdLine */, int /* i_nCmdShow */) { - typedef BOOL (WINAPI* ISWOW64PROCESS)(HANDLE hProcess, PBOOL Wow64Process); - BOOL isWow64; - ISWOW64PROCESS pIsWow64Process; - STARTUPINFO si; - PROCESS_INFORMATION pi; - BOOL result; - TCHAR *yamyPath = _T("yamy32"); - - pIsWow64Process = - (ISWOW64PROCESS)::GetProcAddress(::GetModuleHandle(_T("kernel32.dll")), - "IsWow64Process"); - ZeroMemory(&pi,sizeof(pi)); - ZeroMemory(&si,sizeof(si)); - si.cb=sizeof(si); - - if (pIsWow64Process) - { - result = pIsWow64Process(::GetCurrentProcess(), &isWow64); - if (result != FALSE && isWow64 == TRUE) - { - yamyPath = _T("yamy64"); - } - } - - result = CreateProcess(yamyPath, yamyPath, NULL, NULL, FALSE, - NORMAL_PRIORITY_CLASS, 0, NULL, &si, &pi); - - if (result == FALSE) - { - TCHAR buf[1024]; - TCHAR text[1024]; - TCHAR title[1024]; - - LoadString(i_hInstance, IDS_cannotInvoke, - text, sizeof(text)/sizeof(text[0])); - LoadString(i_hInstance, IDS_mayu, - title, sizeof(title)/sizeof(title[0])); - _stprintf_s(buf, sizeof(buf)/sizeof(buf[0]), - text, yamyPath, GetLastError()); - MessageBox((HWND)NULL, buf, title, MB_OK | MB_ICONSTOP); - } - else - { - CloseHandle(pi.hThread); - CloseHandle(pi.hProcess); - } - - return 0; + typedef BOOL (WINAPI* ISWOW64PROCESS)(HANDLE hProcess, PBOOL Wow64Process); + BOOL isWow64; + ISWOW64PROCESS pIsWow64Process; + STARTUPINFO si; + PROCESS_INFORMATION pi; + BOOL result; + TCHAR *yamyPath = _T("yamy32"); + + pIsWow64Process = + (ISWOW64PROCESS)::GetProcAddress(::GetModuleHandle(_T("kernel32.dll")), + "IsWow64Process"); + ZeroMemory(&pi,sizeof(pi)); + ZeroMemory(&si,sizeof(si)); + si.cb=sizeof(si); + + if (pIsWow64Process) { + result = pIsWow64Process(::GetCurrentProcess(), &isWow64); + if (result != FALSE && isWow64 == TRUE) { + yamyPath = _T("yamy64"); + } + } + + result = CreateProcess(yamyPath, yamyPath, NULL, NULL, FALSE, + NORMAL_PRIORITY_CLASS, 0, NULL, &si, &pi); + + if (result == FALSE) { + TCHAR buf[1024]; + TCHAR text[1024]; + TCHAR title[1024]; + + LoadString(i_hInstance, IDS_cannotInvoke, + text, sizeof(text)/sizeof(text[0])); + LoadString(i_hInstance, IDS_mayu, + title, sizeof(title)/sizeof(title[0])); + _stprintf_s(buf, sizeof(buf)/sizeof(buf[0]), + text, yamyPath, GetLastError()); + MessageBox((HWND)NULL, buf, title, MB_OK | MB_ICONSTOP); + } else { + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + } + + return 0; } diff --git a/yamyd.cpp b/yamyd.cpp index 001ea41..395d006 100644 --- a/yamyd.cpp +++ b/yamyd.cpp @@ -6,20 +6,19 @@ /// main int WINAPI _tWinMain(HINSTANCE /* i_hInstance */, HINSTANCE /* i_hPrevInstance */, - LPTSTR /* i_lpszCmdLine */, int /* i_nCmdShow */) + LPTSTR /* i_lpszCmdLine */, int /* i_nCmdShow */) { - HANDLE mutex = OpenMutex(SYNCHRONIZE, FALSE, MUTEX_MAYU_EXCLUSIVE_RUNNING); - if (mutex != NULL) - { - CHECK_FALSE( installHooks(NULL, NULL) ); + HANDLE mutex = OpenMutex(SYNCHRONIZE, FALSE, MUTEX_MAYU_EXCLUSIVE_RUNNING); + if (mutex != NULL) { + CHECK_FALSE( installHooks(NULL, NULL) ); - // wait for master process exit - WaitForSingleObject(mutex, INFINITE); - ReleaseMutex(mutex); + // wait for master process exit + WaitForSingleObject(mutex, INFINITE); + ReleaseMutex(mutex); - CHECK_FALSE( uninstallHooks() ); - SendMessage(HWND_BROADCAST, WM_NULL, 0, 0); - } + CHECK_FALSE( uninstallHooks() ); + SendMessage(HWND_BROADCAST, WM_NULL, 0, 0); + } - return 0; + return 0; } -- 2.11.0