id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,543,036
registeredimage.cpp
mullvad_win-split-tunnel/src/containers/registeredimage.cpp
#include <ntifs.h> #include "registeredimage.h" #include "../util.h" namespace registeredimage { struct CONTEXT { LIST_ENTRY ListEntry; ST_PAGEABLE Pageable; }; namespace { // // FindEntry() // // Use at PASSIVE only (APC is OK unless in paging file IO path). // Presumably because character tables are stored in pageable memory. // // Implements case-insensitive comparison. // REGISTERED_IMAGE_ENTRY* FindEntry ( CONTEXT *Context, UNICODE_STRING *ImageName ) { for (auto entry = Context->ListEntry.Flink; entry != &Context->ListEntry; entry = entry->Flink) { auto candidate = (REGISTERED_IMAGE_ENTRY*)entry; if (0 == RtlCompareUnicodeString((UNICODE_STRING*)&candidate->ImageName, ImageName, TRUE)) { return candidate; } } return NULL; } // // FindEntryExact() // // Use at DISPATCH. // Implements case-sensitive comparison. // REGISTERED_IMAGE_ENTRY* FindEntryExact ( CONTEXT *Context, LOWER_UNICODE_STRING *ImageName ) { for (auto entry = Context->ListEntry.Flink; entry != &Context->ListEntry; entry = entry->Flink) { auto candidate = (REGISTERED_IMAGE_ENTRY*)entry; if (util::Equal(ImageName, &candidate->ImageName)) { return candidate; } } return NULL; } NTSTATUS AddEntryInner ( CONTEXT *Context, LOWER_UNICODE_STRING *ImageName ) { // // Make a single allocation for the struct and string buffer. // auto offsetStringBuffer = util::RoundToMultiple(sizeof(REGISTERED_IMAGE_ENTRY), 8); auto allocationSize = offsetStringBuffer + ImageName->Length; const auto poolType = (Context->Pageable == ST_PAGEABLE::YES) ? PagedPool : NonPagedPool; auto record = (REGISTERED_IMAGE_ENTRY*) ExAllocatePoolUninitialized(poolType, allocationSize, ST_POOL_TAG); if (record == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } auto stringBuffer = (WCHAR*)(((CHAR*)record) + offsetStringBuffer); InitializeListHead(&record->ListEntry); record->ImageName.Length = ImageName->Length; record->ImageName.MaximumLength = ImageName->Length; record->ImageName.Buffer = stringBuffer; RtlCopyMemory(stringBuffer, ImageName->Buffer, ImageName->Length); InsertTailList(&Context->ListEntry, &record->ListEntry); return STATUS_SUCCESS; } bool RemoveEntryInner ( REGISTERED_IMAGE_ENTRY *Entry ) { if (Entry == NULL) { return false; } RemoveEntryList(&Entry->ListEntry); ExFreePoolWithTag(Entry, ST_POOL_TAG); return true; } } // anonymous namespace NTSTATUS Initialize ( CONTEXT **Context, ST_PAGEABLE Pageable ) { const auto poolType = (Pageable == ST_PAGEABLE::YES) ? PagedPool : NonPagedPool; *Context = (CONTEXT*)ExAllocatePoolUninitialized(poolType, sizeof(CONTEXT), ST_POOL_TAG); if (*Context == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } InitializeListHead(&(*Context)->ListEntry); (*Context)->Pageable = Pageable; return STATUS_SUCCESS; } _IRQL_requires_(PASSIVE_LEVEL) NTSTATUS AddEntry ( CONTEXT *Context, UNICODE_STRING *ImageName ) { NT_ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL); // // Avoid storing duplicates. // FindEntry doesn't care about character casing. // if (NULL != FindEntry(Context, ImageName)) { return STATUS_SUCCESS; } // // Make a lower case string copy. // UNICODE_STRING lowerImageName; auto status = RtlDowncaseUnicodeString(&lowerImageName, ImageName, TRUE); if (!NT_SUCCESS(status)) { return status; } status = AddEntryInner(Context, (LOWER_UNICODE_STRING*)&lowerImageName); RtlFreeUnicodeString(&lowerImageName); return status; } NTSTATUS AddEntryExact ( CONTEXT *Context, LOWER_UNICODE_STRING *ImageName ) { if (NULL != FindEntryExact(Context, ImageName)) { return STATUS_SUCCESS; } return AddEntryInner(Context, ImageName); } bool HasEntry ( CONTEXT *Context, UNICODE_STRING *ImageName ) { auto record = FindEntry(Context, ImageName); return record != NULL; } bool HasEntryExact ( CONTEXT *Context, LOWER_UNICODE_STRING *ImageName ) { auto record = FindEntryExact(Context, ImageName); return record != NULL; } bool RemoveEntry ( CONTEXT *Context, UNICODE_STRING *ImageName ) { return RemoveEntryInner(FindEntry(Context, ImageName)); } bool RemoveEntryExact ( CONTEXT *Context, LOWER_UNICODE_STRING *ImageName ) { return RemoveEntryInner(FindEntryExact(Context, ImageName)); } bool ForEach ( CONTEXT *Context, ST_RI_FOREACH Callback, void *ClientContext ) { for (auto entry = Context->ListEntry.Flink; entry != &Context->ListEntry; entry = entry->Flink) { auto typedEntry = (REGISTERED_IMAGE_ENTRY *)entry; if (!Callback(&typedEntry->ImageName, ClientContext)) { return false; } } return true; } void Reset ( CONTEXT *Context ) { while (FALSE == IsListEmpty(&Context->ListEntry)) { auto entry = RemoveHeadList(&Context->ListEntry); ExFreePoolWithTag(entry, ST_POOL_TAG); } } void TearDown ( CONTEXT **Context ) { Reset(*Context); ExFreePoolWithTag(*Context, ST_POOL_TAG); *Context = NULL; } bool IsEmpty ( CONTEXT *Context ) { return bool_cast(IsListEmpty(&Context->ListEntry)); } } // namespace registeredimage
5,080
C++
.cpp
256
17.859375
92
0.760965
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,037
logging.cpp
mullvad_win-split-tunnel/src/firewall/logging.cpp
#include "logging.h" #include "../util.h" #include "../trace.h" #include "logging.tmh" namespace firewall { void LogBindRedirect ( HANDLE ProcessId, const SOCKADDR_IN *Target, const IN_ADDR *Override ) { char targetString[32]; char overrideString[32]; RtlIpv4AddressToStringA(&Target->sin_addr, targetString); RtlIpv4AddressToStringA(Override, overrideString); const auto port = ntohs(Target->sin_port); DbgPrint ( "[BIND][%p] Rewriting Non-TCP bind request %s:%d into %s:%d\n", ProcessId, targetString, port, overrideString, port ); } void LogBindRedirect ( HANDLE ProcessId, const SOCKADDR_IN6 *Target, const IN6_ADDR *Override ) { char targetString[64]; char overrideString[64]; RtlIpv6AddressToStringA(&Target->sin6_addr, targetString); RtlIpv6AddressToStringA(Override, overrideString); const auto port = ntohs(Target->sin6_port); DbgPrint ( "[BIND][%p] Rewriting Non-TCP bind request [%s]:%d into [%s]:%d\n", ProcessId, targetString, port, overrideString, port ); } void LogConnectRedirectPass ( HANDLE ProcessId, const IN_ADDR *LocalAddress, USHORT LocalPort, const IN_ADDR *RemoteAddress, USHORT RemotePort ) { char localAddrString[32]; char remoteAddrString[32]; RtlIpv4AddressToStringA(LocalAddress, localAddrString); RtlIpv4AddressToStringA(RemoteAddress, remoteAddrString); DbgPrint ( "[CONN][%p] Passing on opportunity to redirect %s:%d -> %s:%d\n", ProcessId, localAddrString, LocalPort, remoteAddrString, RemotePort ); } void LogConnectRedirectPass ( HANDLE ProcessId, const IN6_ADDR *LocalAddress, USHORT LocalPort, const IN6_ADDR *RemoteAddress, USHORT RemotePort ) { char localAddrString[64]; char remoteAddrString[64]; RtlIpv6AddressToStringA(LocalAddress, localAddrString); RtlIpv6AddressToStringA(RemoteAddress, remoteAddrString); DbgPrint ( "[CONN][%p] Passing on opportunity to redirect [%s]:%d -> [%s]:%d\n", ProcessId, localAddrString, LocalPort, remoteAddrString, RemotePort ); } void LogConnectRedirect ( HANDLE ProcessId, const IN_ADDR *LocalAddress, USHORT LocalPort, const IN_ADDR *LocalAddressOverride, const IN_ADDR *RemoteAddress, USHORT RemotePort ) { char localAddrString[32]; char localAddrOverrideString[32]; char remoteAddrString[32]; RtlIpv4AddressToStringA(LocalAddress, localAddrString); RtlIpv4AddressToStringA(LocalAddressOverride, localAddrOverrideString); RtlIpv4AddressToStringA(RemoteAddress, remoteAddrString); DbgPrint ( "[CONN][%p] Rewriting connection on %s:%d as %s:%d -> %s:%d\n", ProcessId, localAddrString, LocalPort, localAddrOverrideString, LocalPort, remoteAddrString, RemotePort ); } void LogConnectRedirect ( HANDLE ProcessId, const IN6_ADDR *LocalAddress, USHORT LocalPort, const IN6_ADDR *LocalAddressOverride, const IN6_ADDR *RemoteAddress, USHORT RemotePort ) { char localAddrString[64]; char localAddrOverrideString[64]; char remoteAddrString[64]; RtlIpv6AddressToStringA(LocalAddress, localAddrString); RtlIpv6AddressToStringA(LocalAddressOverride, localAddrOverrideString); RtlIpv6AddressToStringA(RemoteAddress, remoteAddrString); DbgPrint ( "[CONN][%p] Rewriting connection on [%s]:%d as [%s]:%d -> [%s]:%d\n", ProcessId, localAddrString, LocalPort, localAddrOverrideString, LocalPort, remoteAddrString, RemotePort ); } void LogPermitConnection ( HANDLE ProcessId, const IN_ADDR *LocalAddress, USHORT LocalPort, const IN_ADDR *RemoteAddress, USHORT RemotePort, bool outgoing ) { char localAddrString[32]; char remoteAddrString[32]; RtlIpv4AddressToStringA(LocalAddress, localAddrString); RtlIpv4AddressToStringA(RemoteAddress, remoteAddrString); const auto direction = outgoing ? "->" : "<-"; DbgPrint ( "[PRMT][%p] %s:%d %s %s:%d\n", ProcessId, localAddrString, LocalPort, direction, remoteAddrString, RemotePort ); } void LogPermitConnection ( HANDLE ProcessId, const IN6_ADDR *LocalAddress, USHORT LocalPort, const IN6_ADDR *RemoteAddress, USHORT RemotePort, bool outgoing ) { char localAddrString[64]; char remoteAddrString[64]; RtlIpv6AddressToStringA(LocalAddress, localAddrString); RtlIpv6AddressToStringA(RemoteAddress, remoteAddrString); const auto direction = outgoing ? "->" : "<-"; DbgPrint ( "[PRMT][%p] [%s]:%d %s [%s]:%d\n", ProcessId, localAddrString, LocalPort, direction, remoteAddrString, RemotePort ); } void LogBlockConnection ( HANDLE ProcessId, const IN_ADDR *LocalAddress, USHORT LocalPort, const IN_ADDR *RemoteAddress, USHORT RemotePort, bool outgoing ) { char localAddrString[32]; char remoteAddrString[32]; RtlIpv4AddressToStringA(LocalAddress, localAddrString); RtlIpv4AddressToStringA(RemoteAddress, remoteAddrString); const auto direction = outgoing ? "->" : "<-"; DbgPrint ( "[BLCK][%p] %s:%d %s %s:%d\n", ProcessId, localAddrString, LocalPort, direction, remoteAddrString, RemotePort ); } void LogBlockConnection ( HANDLE ProcessId, const IN6_ADDR *LocalAddress, USHORT LocalPort, const IN6_ADDR *RemoteAddress, USHORT RemotePort, bool outgoing ) { char localAddrString[64]; char remoteAddrString[64]; RtlIpv6AddressToStringA(LocalAddress, localAddrString); RtlIpv6AddressToStringA(RemoteAddress, remoteAddrString); const auto direction = outgoing ? "->" : "<-"; DbgPrint ( "[BLCK][%p] [%s]:%d %s [%s]:%d\n", ProcessId, localAddrString, LocalPort, direction, remoteAddrString, RemotePort ); } void LogActivatedSplittingMode ( SPLITTING_MODE Mode ) { // // This only works because SPLITTING_MODE::MODE_1 is defined as 1, etc. // NT_ASSERT ( static_cast<size_t>(SPLITTING_MODE::MODE_1) == 1 && static_cast<size_t>(SPLITTING_MODE::MODE_9) == 9 ); DbgPrint("Activated splitting mode: %u\n", static_cast<size_t>(Mode)); } }; // namespace firewall
5,882
C++
.cpp
291
18.051546
72
0.776356
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,038
filters.cpp
mullvad_win-split-tunnel/src/firewall/filters.cpp
#include "../util.h" #include "identifiers.h" #include "constants.h" #include "filters.h" #define SUCCEED_OR_RETURN(status) if(!NT_SUCCESS(status)){ return status; } namespace firewall { NTSTATUS RegisterFilterBindRedirectIpv4Tx ( HANDLE WfpSession ) { // // Create filter that references callout. // // Use `protocol != TCP` as the sole condition. // This is because TCP traffic is better dealt with in connect-redirect. // FWPM_FILTER0 filter = { 0 }; const auto filterName = L"Mullvad Split Tunnel Bind Redirect Filter (IPv4)"; const auto filterDescription = L"Redirects certain binds away from tunnel interface"; filter.filterKey = ST_FW_FILTER_CLASSIFY_BIND_IPV4_KEY; filter.displayData.name = const_cast<wchar_t*>(filterName); filter.displayData.description = const_cast<wchar_t*>(filterDescription); filter.flags = FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT | FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT; filter.providerKey = const_cast<GUID*>(&ST_FW_PROVIDER_KEY); filter.layerKey = FWPM_LAYER_ALE_BIND_REDIRECT_V4; filter.subLayerKey = ST_FW_WINFW_BASELINE_SUBLAYER_KEY; filter.weight.type = FWP_UINT64; filter.weight.uint64 = const_cast<UINT64*>(&ST_MAX_FILTER_WEIGHT); filter.action.type = FWP_ACTION_CALLOUT_UNKNOWN; filter.action.calloutKey = ST_FW_CALLOUT_CLASSIFY_BIND_IPV4_KEY; filter.providerContextKey = ST_FW_PROVIDER_CONTEXT_KEY; FWPM_FILTER_CONDITION0 cond; cond.fieldKey = FWPM_CONDITION_IP_PROTOCOL; cond.matchType = FWP_MATCH_NOT_EQUAL; cond.conditionValue.type = FWP_UINT8; cond.conditionValue.uint8 = IPPROTO_TCP; filter.filterCondition = &cond; filter.numFilterConditions = 1; return FwpmFilterAdd0(WfpSession, &filter, NULL, NULL); } NTSTATUS RemoveFilterBindRedirectIpv4Tx ( HANDLE WfpSession ) { return FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_CLASSIFY_BIND_IPV4_KEY); } NTSTATUS RegisterFilterBindRedirectIpv6Tx ( HANDLE WfpSession ) { // // Create filter that references callout. // // Use `protocol != TCP` as the sole condition. // This is because TCP traffic is better dealt with in connect-redirect. // FWPM_FILTER0 filter = { 0 }; const auto filterName = L"Mullvad Split Tunnel Bind Redirect Filter (IPv6)"; const auto filterDescription = L"Redirects certain binds away from tunnel interface"; filter.filterKey = ST_FW_FILTER_CLASSIFY_BIND_IPV6_KEY; filter.displayData.name = const_cast<wchar_t*>(filterName); filter.displayData.description = const_cast<wchar_t*>(filterDescription); filter.flags = FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT | FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT; filter.providerKey = const_cast<GUID*>(&ST_FW_PROVIDER_KEY); filter.layerKey = FWPM_LAYER_ALE_BIND_REDIRECT_V6; filter.subLayerKey = ST_FW_WINFW_BASELINE_SUBLAYER_KEY; filter.weight.type = FWP_UINT64; filter.weight.uint64 = const_cast<UINT64*>(&ST_MAX_FILTER_WEIGHT); filter.action.type = FWP_ACTION_CALLOUT_UNKNOWN; filter.action.calloutKey = ST_FW_CALLOUT_CLASSIFY_BIND_IPV6_KEY; filter.providerContextKey = ST_FW_PROVIDER_CONTEXT_KEY; FWPM_FILTER_CONDITION0 cond; cond.fieldKey = FWPM_CONDITION_IP_PROTOCOL; cond.matchType = FWP_MATCH_NOT_EQUAL; cond.conditionValue.type = FWP_UINT8; cond.conditionValue.uint8 = IPPROTO_TCP; filter.filterCondition = &cond; filter.numFilterConditions = 1; return FwpmFilterAdd0(WfpSession, &filter, NULL, NULL); } NTSTATUS RemoveFilterBindRedirectIpv6Tx ( HANDLE WfpSession ) { return FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_CLASSIFY_BIND_IPV6_KEY); } NTSTATUS RegisterFilterConnectRedirectIpv4Tx ( HANDLE WfpSession ) { // // Create filter that references callout. // // Use `protocol == TCP` as the sole condition. // // This is because the source address for non-TCP traffic can't be updated in connect-redirect. // So that traffic is instead dealt with in bind-redirect. // FWPM_FILTER0 filter = { 0 }; const auto filterName = L"Mullvad Split Tunnel Connect Redirect Filter (IPv4)"; const auto filterDescription = L"Adjusts properties on new network connections"; filter.filterKey = ST_FW_FILTER_CLASSIFY_CONNECT_IPV4_KEY; filter.displayData.name = const_cast<wchar_t*>(filterName); filter.displayData.description = const_cast<wchar_t*>(filterDescription); filter.flags = FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT | FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT; filter.providerKey = const_cast<GUID*>(&ST_FW_PROVIDER_KEY); filter.layerKey = FWPM_LAYER_ALE_CONNECT_REDIRECT_V4; filter.subLayerKey = ST_FW_WINFW_BASELINE_SUBLAYER_KEY; filter.weight.type = FWP_UINT64; filter.weight.uint64 = const_cast<UINT64*>(&ST_MAX_FILTER_WEIGHT); filter.action.type = FWP_ACTION_CALLOUT_UNKNOWN; filter.action.calloutKey = ST_FW_CALLOUT_CLASSIFY_CONNECT_IPV4_KEY; filter.providerContextKey = ST_FW_PROVIDER_CONTEXT_KEY; FWPM_FILTER_CONDITION0 cond; cond.fieldKey = FWPM_CONDITION_IP_PROTOCOL; cond.matchType = FWP_MATCH_EQUAL; cond.conditionValue.type = FWP_UINT8; cond.conditionValue.uint8 = IPPROTO_TCP; filter.filterCondition = &cond; filter.numFilterConditions = 1; return FwpmFilterAdd0(WfpSession, &filter, NULL, NULL); } NTSTATUS RemoveFilterConnectRedirectIpv4Tx ( HANDLE WfpSession ) { return FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_CLASSIFY_CONNECT_IPV4_KEY); } NTSTATUS RegisterFilterConnectRedirectIpv6Tx ( HANDLE WfpSession ) { // // Create filter that references callout. // // Use `protocol == TCP` as the sole condition. // // This is because the source address for non-TCP traffic can't be updated in connect-redirect. // So that traffic is instead dealt with in bind-redirect. // FWPM_FILTER0 filter = { 0 }; const auto filterName = L"Mullvad Split Tunnel Connect Redirect Filter (IPv6)"; const auto filterDescription = L"Adjusts properties on new network connections"; filter.filterKey = ST_FW_FILTER_CLASSIFY_CONNECT_IPV6_KEY; filter.displayData.name = const_cast<wchar_t*>(filterName); filter.displayData.description = const_cast<wchar_t*>(filterDescription); filter.flags = FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT | FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT; filter.providerKey = const_cast<GUID*>(&ST_FW_PROVIDER_KEY); filter.layerKey = FWPM_LAYER_ALE_CONNECT_REDIRECT_V6; filter.subLayerKey = ST_FW_WINFW_BASELINE_SUBLAYER_KEY; filter.weight.type = FWP_UINT64; filter.weight.uint64 = const_cast<UINT64*>(&ST_MAX_FILTER_WEIGHT); filter.action.type = FWP_ACTION_CALLOUT_UNKNOWN; filter.action.calloutKey = ST_FW_CALLOUT_CLASSIFY_CONNECT_IPV6_KEY; filter.providerContextKey = ST_FW_PROVIDER_CONTEXT_KEY; FWPM_FILTER_CONDITION0 cond; cond.fieldKey = FWPM_CONDITION_IP_PROTOCOL; cond.matchType = FWP_MATCH_EQUAL; cond.conditionValue.type = FWP_UINT8; cond.conditionValue.uint8 = IPPROTO_TCP; filter.filterCondition = &cond; filter.numFilterConditions = 1; return FwpmFilterAdd0(WfpSession, &filter, NULL, NULL); } NTSTATUS RemoveFilterConnectRedirectIpv6Tx ( HANDLE WfpSession ) { return FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_CLASSIFY_CONNECT_IPV6_KEY); } NTSTATUS RegisterFilterPermitNonTunnelIpv4Tx ( HANDLE WfpSession, const IN_ADDR *TunnelIpv4 ) { // // Create filter that references callout. // // The single condition is IP_LOCAL_ADDRESS != Tunnel. // // This ensures the callout is presented only with connections that are // attempted outside the tunnel. // // Ipv4 outbound. // FWPM_FILTER0 filter = { 0 }; const auto filterName = L"Mullvad Split Tunnel Permissive Filter (IPv4)"; const auto filterDescription = L"Approves selected connections outside the tunnel"; filter.filterKey = ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV4_CONN_KEY; filter.displayData.name = const_cast<wchar_t*>(filterName); filter.displayData.description = const_cast<wchar_t*>(filterDescription); filter.flags = FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT; filter.providerKey = const_cast<GUID*>(&ST_FW_PROVIDER_KEY); filter.layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V4; filter.subLayerKey = ST_FW_WINFW_BASELINE_SUBLAYER_KEY; filter.weight.type = FWP_UINT64; filter.weight.uint64 = const_cast<UINT64*>(&ST_HIGH_FILTER_WEIGHT); filter.action.type = FWP_ACTION_CALLOUT_UNKNOWN; filter.action.calloutKey = ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV4_CONN_KEY; filter.providerContextKey = ST_FW_PROVIDER_CONTEXT_KEY; FWPM_FILTER_CONDITION0 cond = { 0 }; // // If there's no tunnel IPv4 interface then traffic on all interfaces // qualifies as non-tunnel traffic. // if (TunnelIpv4 != NULL) { cond.fieldKey = FWPM_CONDITION_IP_LOCAL_ADDRESS; cond.matchType = FWP_MATCH_NOT_EQUAL; cond.conditionValue.type = FWP_UINT32; cond.conditionValue.uint32 = RtlUlongByteSwap(TunnelIpv4->s_addr); filter.filterCondition = &cond; filter.numFilterConditions = 1; } SUCCEED_OR_RETURN ( FwpmFilterAdd0(WfpSession, &filter, NULL, NULL) ); // // Ipv4 inbound. // filter.filterKey = ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV4_RECV_KEY; filter.layerKey = FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4; filter.action.calloutKey = ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV4_RECV_KEY; SUCCEED_OR_RETURN ( FwpmFilterAdd0(WfpSession, &filter, NULL, NULL) ); // // Create corresponding filters in the DNS sublayer. // By convention, these filters should include a condition on the destination port. // // I.e. we'll be using 1 or 2 conditions. // FWPM_FILTER_CONDITION0 dnscond[2] = { 0, 0 }; dnscond[0].fieldKey = FWPM_CONDITION_IP_REMOTE_PORT; dnscond[0].matchType = FWP_MATCH_EQUAL; dnscond[0].conditionValue.type = FWP_UINT16; dnscond[0].conditionValue.uint16 = DNS_SERVER_PORT; filter.filterCondition = dnscond; if (TunnelIpv4 != NULL) { dnscond[1] = cond; filter.numFilterConditions = 2; } else { filter.numFilterConditions = 1; } // // Ipv4 outbound DNS. // filter.filterKey = ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV4_DNS_CONN_KEY; filter.layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V4; filter.subLayerKey = ST_FW_WINFW_DNS_SUBLAYER_KEY; filter.action.calloutKey = ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV4_CONN_KEY; SUCCEED_OR_RETURN ( FwpmFilterAdd0(WfpSession, &filter, NULL, NULL) ); // // Ipv4 inbound DNS. // filter.filterKey = ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV4_DNS_RECV_KEY; filter.layerKey = FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4; filter.action.calloutKey = ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV4_RECV_KEY; return FwpmFilterAdd0(WfpSession, &filter, NULL, NULL); } NTSTATUS RemoveFilterPermitNonTunnelIpv4Tx ( HANDLE WfpSession ) { SUCCEED_OR_RETURN ( FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV4_CONN_KEY) ); SUCCEED_OR_RETURN ( FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV4_RECV_KEY) ); SUCCEED_OR_RETURN ( FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV4_DNS_CONN_KEY) ); return FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV4_DNS_RECV_KEY); } NTSTATUS RegisterFilterPermitNonTunnelIpv6Tx ( HANDLE WfpSession, const IN6_ADDR *TunnelIpv6 ) { // // IPv6 outbound. // FWPM_FILTER0 filter = { 0 }; const auto filterName = L"Mullvad Split Tunnel Permissive Filter (IPv6)"; const auto filterDescription = L"Approves selected connections outside the tunnel"; filter.filterKey = ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV6_CONN_KEY; filter.displayData.name = const_cast<wchar_t*>(filterName); filter.displayData.description = const_cast<wchar_t*>(filterDescription); filter.flags = FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT; filter.providerKey = const_cast<GUID*>(&ST_FW_PROVIDER_KEY); filter.layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V6; filter.subLayerKey = ST_FW_WINFW_BASELINE_SUBLAYER_KEY; filter.weight.type = FWP_UINT64; filter.weight.uint64 = const_cast<UINT64*>(&ST_HIGH_FILTER_WEIGHT); filter.action.type = FWP_ACTION_CALLOUT_UNKNOWN; filter.action.calloutKey = ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV6_CONN_KEY; filter.providerContextKey = ST_FW_PROVIDER_CONTEXT_KEY; FWPM_FILTER_CONDITION0 cond = { 0 }; // // If there's no tunnel IPv6 interface then traffic on all interfaces // qualifies as non-tunnel traffic. // if (TunnelIpv6 != NULL) { cond.fieldKey = FWPM_CONDITION_IP_LOCAL_ADDRESS; cond.matchType = FWP_MATCH_NOT_EQUAL; cond.conditionValue.type = FWP_BYTE_ARRAY16_TYPE; cond.conditionValue.byteArray16 = (FWP_BYTE_ARRAY16*)TunnelIpv6->u.Byte; filter.filterCondition = &cond; filter.numFilterConditions = 1; } SUCCEED_OR_RETURN ( FwpmFilterAdd0(WfpSession, &filter, NULL, NULL) ); // // IPv6 inbound. // filter.filterKey = ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV6_RECV_KEY; filter.layerKey = FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6; filter.action.calloutKey = ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV6_RECV_KEY; SUCCEED_OR_RETURN ( FwpmFilterAdd0(WfpSession, &filter, NULL, NULL) ); // // Create corresponding filters in the DNS sublayer. // FWPM_FILTER_CONDITION0 dnscond[2] = { 0, 0 }; dnscond[0].fieldKey = FWPM_CONDITION_IP_REMOTE_PORT; dnscond[0].matchType = FWP_MATCH_EQUAL; dnscond[0].conditionValue.type = FWP_UINT16; dnscond[0].conditionValue.uint16 = DNS_SERVER_PORT; filter.filterCondition = dnscond; if (TunnelIpv6 != NULL) { dnscond[1] = cond; filter.numFilterConditions = 2; } else { filter.numFilterConditions = 1; } // // Ipv6 outbound DNS. // filter.filterKey = ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV6_DNS_CONN_KEY; filter.layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V6; filter.subLayerKey = ST_FW_WINFW_DNS_SUBLAYER_KEY; filter.action.calloutKey = ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV6_CONN_KEY; SUCCEED_OR_RETURN ( FwpmFilterAdd0(WfpSession, &filter, NULL, NULL) ); // // Ipv6 inbound DNS. // filter.filterKey = ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV6_DNS_RECV_KEY; filter.layerKey = FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6; filter.action.calloutKey = ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV6_RECV_KEY; return FwpmFilterAdd0(WfpSession, &filter, NULL, NULL); } NTSTATUS RemoveFilterPermitNonTunnelIpv6Tx ( HANDLE WfpSession ) { SUCCEED_OR_RETURN ( FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV6_CONN_KEY) ); SUCCEED_OR_RETURN ( FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV6_RECV_KEY) ); SUCCEED_OR_RETURN ( FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV6_DNS_CONN_KEY) ); return FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV6_DNS_RECV_KEY); } NTSTATUS RegisterFilterBlockTunnelIpv4Tx ( HANDLE WfpSession, const IN_ADDR *TunnelIp ) { // // Create filters that match all tunnel IPv4 traffic. // // The linked callout will then block all existing and attempted connections // that can be associated with apps that are being split. // FWPM_FILTER0 filter = { 0 }; const auto filterNameOutbound = L"Mullvad Split Tunnel IPv4 Blocking Filter (Outbound)"; const auto filterDescription = L"Blocks tunnel IPv4 traffic for apps being split"; filter.filterKey = ST_FW_FILTER_BLOCK_ALL_SPLIT_APPS_TUNNEL_IPV4_CONN_KEY; filter.displayData.name = const_cast<wchar_t*>(filterNameOutbound); filter.displayData.description = const_cast<wchar_t*>(filterDescription); filter.flags = FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT | FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT; filter.providerKey = const_cast<GUID*>(&ST_FW_PROVIDER_KEY); filter.layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V4; filter.subLayerKey = ST_FW_WINFW_BASELINE_SUBLAYER_KEY; filter.weight.type = FWP_UINT64; filter.weight.uint64 = const_cast<UINT64*>(&ST_MAX_FILTER_WEIGHT); filter.action.type = FWP_ACTION_CALLOUT_UNKNOWN; filter.action.calloutKey = ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV4_CONN_KEY; filter.providerContextKey = ST_FW_PROVIDER_CONTEXT_KEY; FWPM_FILTER_CONDITION0 cond; cond.fieldKey = FWPM_CONDITION_IP_LOCAL_ADDRESS; cond.matchType = FWP_MATCH_EQUAL; cond.conditionValue.type = FWP_UINT32; cond.conditionValue.uint32 = RtlUlongByteSwap(TunnelIp->s_addr); filter.filterCondition = &cond; filter.numFilterConditions = 1; auto status = FwpmFilterAdd0(WfpSession, &filter, NULL, NULL); if (!NT_SUCCESS(status)) { return status; } const auto filterNameInbound = L"Mullvad Split Tunnel IPv4 Blocking Filter (Inbound)"; filter.filterKey = ST_FW_FILTER_BLOCK_ALL_SPLIT_APPS_TUNNEL_IPV4_RECV_KEY; filter.displayData.name = const_cast<wchar_t*>(filterNameInbound); filter.layerKey = FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4; filter.action.calloutKey = ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV4_RECV_KEY; return FwpmFilterAdd0(WfpSession, &filter, NULL, NULL); } NTSTATUS RemoveFilterBlockTunnelIpv4Tx ( HANDLE WfpSession ) { auto status = FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_BLOCK_ALL_SPLIT_APPS_TUNNEL_IPV4_CONN_KEY); if (!NT_SUCCESS(status)) { return status; } return FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_BLOCK_ALL_SPLIT_APPS_TUNNEL_IPV4_RECV_KEY); } NTSTATUS RegisterFilterBlockTunnelIpv6Tx ( HANDLE WfpSession, const IN6_ADDR *TunnelIp ) { // // Create filters that match all tunnel IPv6 traffic. // // The linked callout will then block all existing and attempted connections // that can be associated with apps that are being split. // FWPM_FILTER0 filter = { 0 }; const auto filterNameOutbound = L"Mullvad Split Tunnel IPv6 Blocking Filter (Outbound)"; const auto filterDescription = L"Blocks tunnel IPv6 traffic for apps being split"; filter.filterKey = ST_FW_FILTER_BLOCK_ALL_SPLIT_APPS_TUNNEL_IPV6_CONN_KEY; filter.displayData.name = const_cast<wchar_t*>(filterNameOutbound); filter.displayData.description = const_cast<wchar_t*>(filterDescription); filter.flags = FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT | FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT; filter.providerKey = const_cast<GUID*>(&ST_FW_PROVIDER_KEY); filter.layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V6; filter.subLayerKey = ST_FW_WINFW_BASELINE_SUBLAYER_KEY; filter.weight.type = FWP_UINT64; filter.weight.uint64 = const_cast<UINT64*>(&ST_MAX_FILTER_WEIGHT); filter.action.type = FWP_ACTION_CALLOUT_UNKNOWN; filter.action.calloutKey = ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV6_CONN_KEY; filter.providerContextKey = ST_FW_PROVIDER_CONTEXT_KEY; FWPM_FILTER_CONDITION0 cond; cond.fieldKey = FWPM_CONDITION_IP_LOCAL_ADDRESS; cond.matchType = FWP_MATCH_EQUAL; cond.conditionValue.type = FWP_BYTE_ARRAY16_TYPE; cond.conditionValue.byteArray16 = (FWP_BYTE_ARRAY16*)TunnelIp->u.Byte; filter.filterCondition = &cond; filter.numFilterConditions = 1; auto status = FwpmFilterAdd0(WfpSession, &filter, NULL, NULL); if (!NT_SUCCESS(status)) { return status; } const auto filterNameInbound = L"Mullvad Split Tunnel IPv6 Blocking Filter (Inbound)"; filter.filterKey = ST_FW_FILTER_BLOCK_ALL_SPLIT_APPS_TUNNEL_IPV6_RECV_KEY; filter.displayData.name = const_cast<wchar_t*>(filterNameInbound); filter.layerKey = FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6; filter.action.calloutKey = ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV6_RECV_KEY; return FwpmFilterAdd0(WfpSession, &filter, NULL, NULL); } NTSTATUS RemoveFilterBlockTunnelIpv6Tx ( HANDLE WfpSession ) { auto status = FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_BLOCK_ALL_SPLIT_APPS_TUNNEL_IPV6_CONN_KEY); if (!NT_SUCCESS(status)) { return status; } return FwpmFilterDeleteByKey0(WfpSession, &ST_FW_FILTER_BLOCK_ALL_SPLIT_APPS_TUNNEL_IPV6_RECV_KEY); } } // namespace firewall
19,238
C++
.cpp
538
33.659851
107
0.778759
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,039
callouts.cpp
mullvad_win-split-tunnel/src/firewall/callouts.cpp
#include "wfp.h" #include "firewall.h" #include "context.h" #include "identifiers.h" #include "pending.h" #include "callouts.h" #include "logging.h" #include "classify.h" #include "../util.h" #include "../trace.h" #include "callouts.tmh" #define RETURN_IF_UNSUCCESSFUL(status) \ if (!NT_SUCCESS(status)) \ { \ return status; \ } namespace firewall { namespace { // // NotifyFilterAttach() // // Receive notifications about filters attaching/detaching the callout. // NTSTATUS NotifyFilterAttach ( FWPS_CALLOUT_NOTIFY_TYPE notifyType, const GUID *filterKey, FWPS_FILTER1 *filter ) { UNREFERENCED_PARAMETER(notifyType); UNREFERENCED_PARAMETER(filterKey); UNREFERENCED_PARAMETER(filter); return STATUS_SUCCESS; } NTSTATUS RegisterCalloutTx ( PDEVICE_OBJECT DeviceObject, HANDLE WfpSession, FWPS_CALLOUT_CLASSIFY_FN1 Callout, const GUID *CalloutKey, const GUID *LayerKey, const wchar_t *CalloutName, const wchar_t* CalloutDescription ) { // // Logically, this is the wrong order, but it results in cleaner code. // You're encouraged to first register the callout and then add it. // // However, what's currently here is fully supported: // // `By default filters that reference callouts that have been added // but have not yet registered with the filter engine are treated as Block filters.` // FWPM_CALLOUT0 callout; RtlZeroMemory(&callout, sizeof(callout)); callout.calloutKey = *CalloutKey; callout.displayData.name = const_cast<wchar_t *>(CalloutName); callout.displayData.description = const_cast<wchar_t *>(CalloutDescription); callout.flags = FWPM_CALLOUT_FLAG_USES_PROVIDER_CONTEXT; callout.providerKey = const_cast<GUID *>(&ST_FW_PROVIDER_KEY); callout.applicableLayer = *LayerKey; auto status = FwpmCalloutAdd0(WfpSession, &callout, NULL, NULL); if (!NT_SUCCESS(status)) { return status; } FWPS_CALLOUT1 aCallout = { 0 }; aCallout.calloutKey = *CalloutKey; aCallout.classifyFn = Callout; aCallout.notifyFn = NotifyFilterAttach; aCallout.flowDeleteFn = NULL; return FwpsCalloutRegister1(DeviceObject, &aCallout, NULL); } // // UnregisterCallout() // // This is a thin wrapper around FwpsCalloutUnregisterByKey0(). // The reason is to clarify and simplify usage. // NTSTATUS UnregisterCallout ( const GUID *CalloutKey ) { const auto status = FwpsCalloutUnregisterByKey0(CalloutKey); if (NT_SUCCESS(status)) { return status; } if (status == STATUS_FWP_CALLOUT_NOT_FOUND) { return STATUS_SUCCESS; } // // The current implementation doesn't process flows or use flow contexts. // So this status code won't be returned. // NT_ASSERT(status != STATUS_DEVICE_BUSY); // // The current implementation manages registration and unregistration // on the primary thread. So this status code won't be returned. // NT_ASSERT(status != STATUS_FWP_IN_USE); return status; } // // RewriteBind() // // Implements redirection for non-TCP socket binds. // // If a bind is attempted (or implied) with target inaddr_any or the tunnel interface, // we rewrite the bind to move it to the internet interface. // // This has the unfortunate effect that client sockets which are not explicitly bound // to localhost are prevented from connecting to localhost. // void RewriteBind ( CONTEXT *Context, const FWPS_INCOMING_VALUES0 *FixedValues, const FWPS_INCOMING_METADATA_VALUES0 *MetaValues, UINT64 FilterId, const void *ClassifyContext, FWPS_CLASSIFY_OUT0 *ClassifyOut ) { UNREFERENCED_PARAMETER(MetaValues); UINT64 classifyHandle = 0; auto status = FwpsAcquireClassifyHandle0 ( const_cast<void*>(ClassifyContext), 0, &classifyHandle ); if (!NT_SUCCESS(status)) { DbgPrint("FwpsAcquireClassifyHandle0() failed 0x%X\n", status); return; } FWPS_BIND_REQUEST0 *bindRequest = NULL; status = FwpsAcquireWritableLayerDataPointer0 ( classifyHandle, FilterId, 0, (PVOID*)&bindRequest, ClassifyOut ); if (!NT_SUCCESS(status)) { DbgPrint("FwpsAcquireWritableLayerDataPointer0() failed 0x%X\n", status); goto Cleanup_handle; } ClassificationReset(ClassifyOut); // // There's a list with redirection history. // // This only ever comes into play if several callouts are fighting to redirect the bind. // // To prevent recursion, we need to check if we're on the list, and abort if so. // for (auto history = bindRequest->previousVersion; history != NULL; history = history->previousVersion) { if (history->modifierFilterId == FilterId) { DbgPrint("Aborting bind processing because already redirected by us\n"); goto Cleanup_data; } } // // Rewrite bind as applicable. // const bool ipv4 = FixedValues->layerId == FWPS_LAYER_ALE_BIND_REDIRECT_V4; WdfSpinLockAcquire(Context->IpAddresses.Lock); if (ipv4) { auto bindTarget = (SOCKADDR_IN*)&(bindRequest->localAddressAndPort); if (IN4_IS_ADDR_UNSPECIFIED(&(bindTarget->sin_addr)) || IN4_ADDR_EQUAL(&(bindTarget->sin_addr), &(Context->IpAddresses.Addresses.TunnelIpv4))) { const auto newTarget = &Context->IpAddresses.Addresses.InternetIpv4; LogBindRedirect(HANDLE(MetaValues->processId), bindTarget, newTarget); bindTarget->sin_addr = *newTarget; ClassificationApplySoftPermit(ClassifyOut); } } else { auto bindTarget = (SOCKADDR_IN6*)&(bindRequest->localAddressAndPort); static const IN6_ADDR IN6_ADDR_ANY = { 0 }; if (IN6_ADDR_EQUAL(&(bindTarget->sin6_addr), &IN6_ADDR_ANY) || IN6_ADDR_EQUAL(&(bindTarget->sin6_addr), &(Context->IpAddresses.Addresses.TunnelIpv6))) { const auto newTarget = &Context->IpAddresses.Addresses.InternetIpv6; LogBindRedirect(HANDLE(MetaValues->processId), bindTarget, newTarget); bindTarget->sin6_addr = *newTarget; ClassificationApplySoftPermit(ClassifyOut); } } WdfSpinLockRelease(Context->IpAddresses.Lock); Cleanup_data: // // Call the "apply" function even in instances where we've made no changes // to the data, because it was deemed not necessary, or aborting for some other reason. // // This is the correct logic according to documentation. // FwpsApplyModifiedLayerData0(classifyHandle, bindRequest, 0); Cleanup_handle: FwpsReleaseClassifyHandle0(classifyHandle); } // // PendClassification() // // This function is used when, for an incoming request, we don't know what the correct action is. // I.e. when the process making the request hasn't been categorized yet. // void PendClassification ( pending::CONTEXT *Context, HANDLE ProcessId, UINT64 FilterId, UINT16 LayerId, const void *ClassifyContext, FWPS_CLASSIFY_OUT0 *ClassifyOut ) { auto status = pending::PendRequest ( Context, ProcessId, const_cast<void*>(ClassifyContext), FilterId, LayerId, ClassifyOut ); if (NT_SUCCESS(status)) { return; } pending::FailRequest ( ProcessId, const_cast<void*>(ClassifyContext), FilterId, LayerId, ClassifyOut ); } // // CalloutClassifyBind() // // === // // NOTE: This function is always called at PASSIVE_LEVEL. // // Callouts are generally activated at <= DISPATCH_LEVEL, but the bind redirect // layers are special-cased and guarantee PASSIVE_LEVEL. // // https://community.osr.com/discussion/292855/irql-for-wfp-callouts-at-fwpm-layer-ale-bind-redirect-vxxx // // === // // Entry point for splitting non-TCP socket binds. // // FWPS_LAYER_ALE_BIND_REDIRECT_V4 // FWPS_LAYER_ALE_BIND_REDIRECT_V6 // void CalloutClassifyBind ( const FWPS_INCOMING_VALUES0 *FixedValues, const FWPS_INCOMING_METADATA_VALUES0 *MetaValues, void *LayerData, const void *ClassifyContext, const FWPS_FILTER1 *Filter, UINT64 FlowContext, FWPS_CLASSIFY_OUT0 *ClassifyOut ) { UNREFERENCED_PARAMETER(LayerData); UNREFERENCED_PARAMETER(FlowContext); NT_ASSERT ( ( FixedValues->layerId == FWPS_LAYER_ALE_BIND_REDIRECT_V4 && FixedValues->incomingValue[FWPS_FIELD_ALE_BIND_REDIRECT_V4_IP_PROTOCOL] \ .value.uint8 != IPPROTO_TCP ) || ( FixedValues->layerId == FWPS_LAYER_ALE_BIND_REDIRECT_V6 && FixedValues->incomingValue[FWPS_FIELD_ALE_BIND_REDIRECT_V6_IP_PROTOCOL] \ .value.uint8 != IPPROTO_TCP ) ); NT_ASSERT ( Filter->providerContext != NULL && Filter->providerContext->type == FWPM_GENERAL_CONTEXT && Filter->providerContext->dataBuffer->size == sizeof(CONTEXT*) ); auto context = *(CONTEXT**)Filter->providerContext->dataBuffer->data; if (0 == (ClassifyOut->rights & FWPS_RIGHT_ACTION_WRITE)) { DbgPrint("Aborting bind processing because hard permit/block already applied\n"); return; } ClassificationReset(ClassifyOut); if (!FWPS_IS_METADATA_FIELD_PRESENT(MetaValues, FWPS_METADATA_FIELD_PROCESS_ID)) { DbgPrint("Failed to classify bind because PID was not provided\n"); return; } const CALLBACKS &callbacks = context->Callbacks; const auto verdict = callbacks.QueryProcess(HANDLE(MetaValues->processId), callbacks.Context); switch (verdict) { case PROCESS_SPLIT_VERDICT::DO_SPLIT: { RewriteBind ( context, FixedValues, MetaValues, Filter->filterId, ClassifyContext, ClassifyOut ); break; } case PROCESS_SPLIT_VERDICT::UNKNOWN: { PendClassification ( context->PendedClassifications, HANDLE(MetaValues->processId), Filter->filterId, FixedValues->layerId, ClassifyContext, ClassifyOut ); break; } }; } bool LocalAddress(const IN_ADDR *addr) { return IN4_IS_ADDR_LOOPBACK(addr) // 127/8 || IN4_IS_ADDR_LINKLOCAL(addr) // 169.254/16 || IN4_IS_ADDR_RFC1918(addr) // 10/8, 172.16/12, 192.168/16 || IN4_IS_ADDR_MC_LINKLOCAL(addr) // 224.0.0/24 || IN4_IS_ADDR_MC_ADMINLOCAL(addr) // 239.255/16 || IN4_IS_ADDR_MC_SITELOCAL(addr) // 239/8 || IN4_IS_ADDR_BROADCAST(addr) // 255.255.255.255 ; } bool IN6_IS_ADDR_ULA(const IN6_ADDR *a) { return (a->s6_bytes[0] == 0xfd); } bool IN6_IS_ADDR_MC_NON_GLOBAL(const IN6_ADDR *a) { return IN6_IS_ADDR_MULTICAST(a) && !IN6_IS_ADDR_MC_GLOBAL(a); } bool LocalAddress(const IN6_ADDR *addr) { return IN6_IS_ADDR_LOOPBACK(addr) // ::1/128 || IN6_IS_ADDR_LINKLOCAL(addr) // fe80::/10 || IN6_IS_ADDR_SITELOCAL(addr) // fec0::/10 || IN6_IS_ADDR_ULA(addr) // fd00::/8 || IN6_IS_ADDR_MC_NON_GLOBAL(addr) // ff00::/8 && !(ffxe::/16) ; } // // RewriteConnection() // // See comment on CalloutClassifyConnect(). // void RewriteConnection ( CONTEXT *Context, const FWPS_INCOMING_VALUES0 *FixedValues, const FWPS_INCOMING_METADATA_VALUES0 *MetaValues, UINT64 FilterId, const void *ClassifyContext, FWPS_CLASSIFY_OUT0 *ClassifyOut ) { UNREFERENCED_PARAMETER(MetaValues); WdfSpinLockAcquire(Context->IpAddresses.Lock); const auto ipAddresses = Context->IpAddresses.Addresses; WdfSpinLockRelease(Context->IpAddresses.Lock); // // Identify the specific cases we're interested in or abort. // const bool ipv4 = FixedValues->layerId == FWPS_LAYER_ALE_CONNECT_REDIRECT_V4; if (ipv4) { const auto rawLocalAddress = RtlUlongByteSwap(FixedValues->incomingValue[ FWPS_FIELD_ALE_CONNECT_REDIRECT_V4_IP_LOCAL_ADDRESS].value.uint32); const auto rawRemoteAddress = RtlUlongByteSwap(FixedValues->incomingValue[ FWPS_FIELD_ALE_CONNECT_REDIRECT_V4_IP_REMOTE_ADDRESS].value.uint32); auto localAddress = reinterpret_cast<const IN_ADDR*>(&rawLocalAddress); auto remoteAddress = reinterpret_cast<const IN_ADDR*>(&rawRemoteAddress); const auto shouldRedirect = IN4_ADDR_EQUAL(localAddress, &ipAddresses.TunnelIpv4) || !LocalAddress(remoteAddress); const auto localPort = FixedValues->incomingValue[ FWPS_FIELD_ALE_CONNECT_REDIRECT_V4_IP_LOCAL_PORT].value.uint16; const auto remotePort = FixedValues->incomingValue[ FWPS_FIELD_ALE_CONNECT_REDIRECT_V4_IP_REMOTE_PORT].value.uint16; if (!shouldRedirect) { LogConnectRedirectPass ( HANDLE(MetaValues->processId), localAddress, localPort, remoteAddress, remotePort ); return; } LogConnectRedirect ( HANDLE(MetaValues->processId), localAddress, localPort, &ipAddresses.InternetIpv4, remoteAddress, remotePort ); } else { auto localAddress = reinterpret_cast<const IN6_ADDR*>(FixedValues->incomingValue[ FWPS_FIELD_ALE_CONNECT_REDIRECT_V6_IP_LOCAL_ADDRESS].value.byteArray16); auto remoteAddress = reinterpret_cast<const IN6_ADDR*>(FixedValues->incomingValue[ FWPS_FIELD_ALE_CONNECT_REDIRECT_V6_IP_REMOTE_ADDRESS].value.byteArray16); const auto shouldRedirect = IN6_ADDR_EQUAL(localAddress, &ipAddresses.TunnelIpv6) || !LocalAddress(remoteAddress); const auto localPort = FixedValues->incomingValue[ FWPS_FIELD_ALE_CONNECT_REDIRECT_V6_IP_LOCAL_PORT].value.uint16; const auto remotePort = FixedValues->incomingValue[ FWPS_FIELD_ALE_CONNECT_REDIRECT_V6_IP_REMOTE_PORT].value.uint16; if (!shouldRedirect) { LogConnectRedirectPass ( HANDLE(MetaValues->processId), localAddress, localPort, remoteAddress, remotePort ); return; } LogConnectRedirect ( HANDLE(MetaValues->processId), localAddress, localPort, &ipAddresses.InternetIpv6, remoteAddress, remotePort ); } // // Patch local address to force connection off of tunnel interface. // UINT64 classifyHandle = 0; auto status = FwpsAcquireClassifyHandle0 ( const_cast<void*>(ClassifyContext), 0, &classifyHandle ); if (!NT_SUCCESS(status)) { DbgPrint("FwpsAcquireClassifyHandle0() failed 0x%X\n", status); return; } FWPS_CONNECT_REQUEST0 *connectRequest = NULL; status = FwpsAcquireWritableLayerDataPointer0 ( classifyHandle, FilterId, 0, (PVOID*)&connectRequest, ClassifyOut ); if (!NT_SUCCESS(status)) { DbgPrint("FwpsAcquireWritableLayerDataPointer0() failed 0x%X\n", status); goto Cleanup_handle; } ClassificationReset(ClassifyOut); // // There's a list with redirection history. // // This only ever comes into play if several callouts are fighting to redirect the connection. // // To prevent recursion, we need to check if we're on the list, and abort if so. // for (auto history = connectRequest->previousVersion; history != NULL; history = history->previousVersion) { if (history->modifierFilterId == FilterId) { DbgPrint("Aborting connection processing because already redirected by us\n"); goto Cleanup_data; } } // // Rewrite connection. // if (ipv4) { auto localDetails = (SOCKADDR_IN*)&connectRequest->localAddressAndPort; localDetails->sin_addr = ipAddresses.InternetIpv4; } else { auto localDetails = (SOCKADDR_IN6*)&connectRequest->localAddressAndPort; localDetails->sin6_addr = ipAddresses.InternetIpv6; } ClassificationApplySoftPermit(ClassifyOut); Cleanup_data: FwpsApplyModifiedLayerData0(classifyHandle, connectRequest, 0); Cleanup_handle: FwpsReleaseClassifyHandle0(classifyHandle); } // // CalloutClassifyConnect() // // Adjust properties on new TCP connections. // // If an app is marked for splitting, and if a new connection is explicitly made on the // tunnel interface, or can be assumed to be routed through the tunnel interface, // then move the connection to the Internet connected interface (LAN interface usually). // // FWPS_LAYER_ALE_CONNECT_REDIRECT_V4 // FWPS_LAYER_ALE_CONNECT_REDIRECT_V6 // void CalloutClassifyConnect ( const FWPS_INCOMING_VALUES0 *FixedValues, const FWPS_INCOMING_METADATA_VALUES0 *MetaValues, void *LayerData, const void *ClassifyContext, const FWPS_FILTER1 *Filter, UINT64 FlowContext, FWPS_CLASSIFY_OUT0 *ClassifyOut ) { UNREFERENCED_PARAMETER(LayerData); UNREFERENCED_PARAMETER(FlowContext); NT_ASSERT ( ( FixedValues->layerId == FWPS_LAYER_ALE_CONNECT_REDIRECT_V4 && FixedValues->incomingValue[FWPS_FIELD_ALE_CONNECT_REDIRECT_V4_IP_PROTOCOL] \ .value.uint8 == IPPROTO_TCP ) || ( FixedValues->layerId == FWPS_LAYER_ALE_CONNECT_REDIRECT_V6 && FixedValues->incomingValue[FWPS_FIELD_ALE_CONNECT_REDIRECT_V6_IP_PROTOCOL] \ .value.uint8 == IPPROTO_TCP ) ); NT_ASSERT ( Filter->providerContext != NULL && Filter->providerContext->type == FWPM_GENERAL_CONTEXT && Filter->providerContext->dataBuffer->size == sizeof(CONTEXT*) ); auto context = *(CONTEXT**)Filter->providerContext->dataBuffer->data; if (0 == (ClassifyOut->rights & FWPS_RIGHT_ACTION_WRITE)) { DbgPrint("Aborting connect-redirect processing because hard permit/block already applied\n"); return; } ClassificationReset(ClassifyOut); if (!FWPS_IS_METADATA_FIELD_PRESENT(MetaValues, FWPS_METADATA_FIELD_PROCESS_ID)) { DbgPrint("Failed to classify connection because PID was not provided\n"); return; } const CALLBACKS &callbacks = context->Callbacks; const auto verdict = callbacks.QueryProcess(HANDLE(MetaValues->processId), callbacks.Context); switch (verdict) { case PROCESS_SPLIT_VERDICT::DO_SPLIT: { RewriteConnection ( context, FixedValues, MetaValues, Filter->filterId, ClassifyContext, ClassifyOut ); break; } case PROCESS_SPLIT_VERDICT::UNKNOWN: { PendClassification ( context->PendedClassifications, HANDLE(MetaValues->processId), Filter->filterId, FixedValues->layerId, ClassifyContext, ClassifyOut ); break; } }; } bool IsAleReauthorize ( const FWPS_INCOMING_VALUES *FixedValues ) { size_t index; switch (FixedValues->layerId) { case FWPS_LAYER_ALE_AUTH_CONNECT_V4: { index = FWPS_FIELD_ALE_AUTH_CONNECT_V4_FLAGS; break; } case FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V4: { index = FWPS_FIELD_ALE_AUTH_RECV_ACCEPT_V4_FLAGS; break; } case FWPS_LAYER_ALE_AUTH_CONNECT_V6: { index = FWPS_FIELD_ALE_AUTH_CONNECT_V6_FLAGS; break; } case FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V6: { index = FWPS_FIELD_ALE_AUTH_RECV_ACCEPT_V6_FLAGS; break; } default: { return false; } }; const auto flags = FixedValues->incomingValue[index].value.uint32; return ((flags & FWP_CONDITION_FLAG_IS_REAUTHORIZE) != 0); } struct AuthLayerValueIndices { SIZE_T LocalAddress; SIZE_T LocalPort; SIZE_T RemoteAddress; SIZE_T RemotePort; }; bool GetAuthLayerValueIndices ( UINT16 LayerId, AuthLayerValueIndices *Indices ) { switch (LayerId) { case FWPS_LAYER_ALE_AUTH_CONNECT_V4: { *Indices = { FWPS_FIELD_ALE_AUTH_CONNECT_V4_IP_LOCAL_ADDRESS, FWPS_FIELD_ALE_AUTH_CONNECT_V4_IP_LOCAL_PORT, FWPS_FIELD_ALE_AUTH_CONNECT_V4_IP_REMOTE_ADDRESS, FWPS_FIELD_ALE_AUTH_CONNECT_V4_IP_REMOTE_PORT }; return true; } case FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V4: { *Indices = { FWPS_FIELD_ALE_AUTH_RECV_ACCEPT_V4_IP_LOCAL_ADDRESS, FWPS_FIELD_ALE_AUTH_RECV_ACCEPT_V4_IP_LOCAL_PORT, FWPS_FIELD_ALE_AUTH_RECV_ACCEPT_V4_IP_REMOTE_ADDRESS, FWPS_FIELD_ALE_AUTH_RECV_ACCEPT_V4_IP_REMOTE_PORT }; return true; } case FWPS_LAYER_ALE_AUTH_CONNECT_V6: { *Indices = { FWPS_FIELD_ALE_AUTH_CONNECT_V6_IP_LOCAL_ADDRESS, FWPS_FIELD_ALE_AUTH_CONNECT_V6_IP_LOCAL_PORT, FWPS_FIELD_ALE_AUTH_CONNECT_V6_IP_REMOTE_ADDRESS, FWPS_FIELD_ALE_AUTH_CONNECT_V6_IP_REMOTE_PORT }; return true; } case FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V6: { *Indices = { FWPS_FIELD_ALE_AUTH_RECV_ACCEPT_V6_IP_LOCAL_ADDRESS, FWPS_FIELD_ALE_AUTH_RECV_ACCEPT_V6_IP_LOCAL_PORT, FWPS_FIELD_ALE_AUTH_RECV_ACCEPT_V6_IP_REMOTE_ADDRESS, FWPS_FIELD_ALE_AUTH_RECV_ACCEPT_V6_IP_REMOTE_PORT }; return true; } } return false; } // // CalloutPermitSplitApps() // // For processes being split, binds and connections will have already been aptly redirected. // So now it's only a matter of approving the connection. // // The reason we have to explicitly approve these connections is because otherwise // the default filters with lower weights would block all non-tunnel connections. // // FWPS_LAYER_ALE_AUTH_CONNECT_V4 // FWPS_LAYER_ALE_AUTH_CONNECT_V6 // FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V4 // FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V6 // void CalloutPermitSplitApps ( const FWPS_INCOMING_VALUES0 *FixedValues, const FWPS_INCOMING_METADATA_VALUES0 *MetaValues, void *LayerData, const void *ClassifyContext, const FWPS_FILTER1 *Filter, UINT64 FlowContext, FWPS_CLASSIFY_OUT0 *ClassifyOut ) { UNREFERENCED_PARAMETER(LayerData); UNREFERENCED_PARAMETER(ClassifyContext); UNREFERENCED_PARAMETER(FlowContext); NT_ASSERT ( FixedValues->layerId == FWPS_LAYER_ALE_AUTH_CONNECT_V4 || FixedValues->layerId == FWPS_LAYER_ALE_AUTH_CONNECT_V6 || FixedValues->layerId == FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V4 || FixedValues->layerId == FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V6 ); NT_ASSERT ( Filter->providerContext != NULL && Filter->providerContext->type == FWPM_GENERAL_CONTEXT && Filter->providerContext->dataBuffer->size == sizeof(CONTEXT*) ); auto context = *(CONTEXT**)Filter->providerContext->dataBuffer->data; if (0 == (ClassifyOut->rights & FWPS_RIGHT_ACTION_WRITE)) { DbgPrint("Aborting auth processing because hard permit/block already applied\n"); return; } ClassificationReset(ClassifyOut); if (!FWPS_IS_METADATA_FIELD_PRESENT(MetaValues, FWPS_METADATA_FIELD_PROCESS_ID)) { DbgPrint("Failed to complete auth processing because PID was not provided\n"); return; } const CALLBACKS &callbacks = context->Callbacks; const auto verdict = callbacks.QueryProcess(HANDLE(MetaValues->processId), callbacks.Context); // // If the process is not marked for splitting we should just abort // and not attempt to classify the connection. // if (verdict != PROCESS_SPLIT_VERDICT::DO_SPLIT) { return; } // // Include extensive logging. // AuthLayerValueIndices indices = {0}; const auto status = GetAuthLayerValueIndices(FixedValues->layerId, &indices); NT_ASSERT(status); if (!status) { return; } const auto localPort = FixedValues->incomingValue[indices.LocalPort].value.uint16; const auto remotePort = FixedValues->incomingValue[indices.RemotePort].value.uint16; const bool ipv4 = FixedValues->layerId == FWPS_LAYER_ALE_AUTH_CONNECT_V4 || FixedValues->layerId == FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V4; if (ipv4) { const auto rawLocalAddress = RtlUlongByteSwap(FixedValues->incomingValue[ indices.LocalAddress].value.uint32); const auto rawRemoteAddress = RtlUlongByteSwap(FixedValues->incomingValue[ indices.RemoteAddress].value.uint32); auto localAddress = reinterpret_cast<const IN_ADDR*>(&rawLocalAddress); auto remoteAddress = reinterpret_cast<const IN_ADDR*>(&rawRemoteAddress); LogPermitConnection ( HANDLE(MetaValues->processId), localAddress, localPort, remoteAddress, remotePort, (FixedValues->layerId == FWPS_LAYER_ALE_AUTH_CONNECT_V4) ); } else { auto localAddress = reinterpret_cast<const IN6_ADDR*>(FixedValues->incomingValue[ indices.LocalAddress].value.byteArray16); auto remoteAddress = reinterpret_cast<const IN6_ADDR*>(FixedValues->incomingValue[ indices.RemoteAddress].value.byteArray16); LogPermitConnection ( HANDLE(MetaValues->processId), localAddress, localPort, remoteAddress, remotePort, (FixedValues->layerId == FWPS_LAYER_ALE_AUTH_CONNECT_V6) ); } // // Apply classification. // ClassificationApplySoftPermit(ClassifyOut); } // // CalloutBlockSplitApps() // // For processes just now being split, it could be the case that they have existing // long-lived connections inside the tunnel. // // These connections need to be blocked to ensure the process exists on // only one side of the tunnel. // // Additionally, block any processes which have not been evaluated. // // This normally isn't required because earlier callouts re-auth until the process // is categorized, but it makes sense as a safety measure. // // FWPS_LAYER_ALE_AUTH_CONNECT_V4 // FWPS_LAYER_ALE_AUTH_CONNECT_V6 // FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V4 // FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V6 // void CalloutBlockSplitApps ( const FWPS_INCOMING_VALUES0 *FixedValues, const FWPS_INCOMING_METADATA_VALUES0 *MetaValues, void *LayerData, const void *ClassifyContext, const FWPS_FILTER1 *Filter, UINT64 FlowContext, FWPS_CLASSIFY_OUT0 *ClassifyOut ) { UNREFERENCED_PARAMETER(LayerData); UNREFERENCED_PARAMETER(ClassifyContext); UNREFERENCED_PARAMETER(FlowContext); NT_ASSERT ( FixedValues->layerId == FWPS_LAYER_ALE_AUTH_CONNECT_V4 || FixedValues->layerId == FWPS_LAYER_ALE_AUTH_CONNECT_V6 || FixedValues->layerId == FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V4 || FixedValues->layerId == FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V6 ); NT_ASSERT ( Filter->providerContext != NULL && Filter->providerContext->type == FWPM_GENERAL_CONTEXT && Filter->providerContext->dataBuffer->size == sizeof(CONTEXT*) ); auto context = *(CONTEXT**)Filter->providerContext->dataBuffer->data; if (0 == (ClassifyOut->rights & FWPS_RIGHT_ACTION_WRITE)) { DbgPrint("Aborting auth processing because hard permit/block already applied\n"); return; } ClassificationReset(ClassifyOut); if (!FWPS_IS_METADATA_FIELD_PRESENT(MetaValues, FWPS_METADATA_FIELD_PROCESS_ID)) { DbgPrint("Failed to complete auth processing because PID was not provided\n"); return; } const CALLBACKS &callbacks = context->Callbacks; const auto verdict = callbacks.QueryProcess(HANDLE(MetaValues->processId), callbacks.Context); // // Block any processes which have not yet been evaluated. // This is a safety measure to prevent race conditions. // const auto shouldBlock = (verdict == PROCESS_SPLIT_VERDICT::DO_SPLIT) || (verdict == PROCESS_SPLIT_VERDICT::UNKNOWN); if (!shouldBlock) { return; } // // Include extensive logging. // AuthLayerValueIndices indices = {0}; const auto status = GetAuthLayerValueIndices(FixedValues->layerId, &indices); NT_ASSERT(status); if (!status) { return; } const auto localPort = FixedValues->incomingValue[indices.LocalPort].value.uint16; const auto remotePort = FixedValues->incomingValue[indices.RemotePort].value.uint16; const bool ipv4 = FixedValues->layerId == FWPS_LAYER_ALE_AUTH_CONNECT_V4 || FixedValues->layerId == FWPS_LAYER_ALE_AUTH_RECV_ACCEPT_V4; if (ipv4) { const auto rawLocalAddress = RtlUlongByteSwap(FixedValues->incomingValue[ indices.LocalAddress].value.uint32); const auto rawRemoteAddress = RtlUlongByteSwap(FixedValues->incomingValue[ indices.RemoteAddress].value.uint32); auto localAddress = reinterpret_cast<const IN_ADDR*>(&rawLocalAddress); auto remoteAddress = reinterpret_cast<const IN_ADDR*>(&rawRemoteAddress); LogBlockConnection ( HANDLE(MetaValues->processId), localAddress, localPort, remoteAddress, remotePort, (FixedValues->layerId == FWPS_LAYER_ALE_AUTH_CONNECT_V4) ); } else { auto localAddress = reinterpret_cast<const IN6_ADDR*>(FixedValues->incomingValue[ indices.LocalAddress].value.byteArray16); auto remoteAddress = reinterpret_cast<const IN6_ADDR*>(FixedValues->incomingValue[ indices.RemoteAddress].value.byteArray16); LogBlockConnection ( HANDLE(MetaValues->processId), localAddress, localPort, remoteAddress, remotePort, (FixedValues->layerId == FWPS_LAYER_ALE_AUTH_CONNECT_V6) ); } // // Apply classification. // ClassificationApplyHardBlock(ClassifyOut); } } // anonymous namespace // // RegisterCalloutClassifyBindTx() // // Register callout with WFP. In all applicable layers. // // "Tx" (in transaction) suffix means there is no clean-up in failure paths. // NTSTATUS RegisterCalloutClassifyBindTx ( PDEVICE_OBJECT DeviceObject, HANDLE WfpSession ) { auto status = RegisterCalloutTx ( DeviceObject, WfpSession, CalloutClassifyBind, &ST_FW_CALLOUT_CLASSIFY_BIND_IPV4_KEY, &FWPM_LAYER_ALE_BIND_REDIRECT_V4, L"Mullvad Split Tunnel Bind Redirect Callout (IPv4)", L"Redirects certain binds away from tunnel interface" ); if (!NT_SUCCESS(status)) { return status; } status = RegisterCalloutTx ( DeviceObject, WfpSession, CalloutClassifyBind, &ST_FW_CALLOUT_CLASSIFY_BIND_IPV6_KEY, &FWPM_LAYER_ALE_BIND_REDIRECT_V6, L"Mullvad Split Tunnel Bind Redirect Callout (IPv6)", L"Redirects certain binds away from tunnel interface" ); if (!NT_SUCCESS(status)) { UnregisterCalloutClassifyBind(); } return status; } NTSTATUS UnregisterCalloutClassifyBind ( ) { auto s1 = UnregisterCallout(&ST_FW_CALLOUT_CLASSIFY_BIND_IPV4_KEY); auto s2 = UnregisterCallout(&ST_FW_CALLOUT_CLASSIFY_BIND_IPV6_KEY); RETURN_IF_UNSUCCESSFUL(s1); RETURN_IF_UNSUCCESSFUL(s2); return STATUS_SUCCESS; } // // RegisterCalloutClassifyConnectTx() // // Register callout with WFP. In all applicable layers. // // "Tx" (in transaction) suffix means there is no clean-up in failure paths. // NTSTATUS RegisterCalloutClassifyConnectTx ( PDEVICE_OBJECT DeviceObject, HANDLE WfpSession ) { auto status = RegisterCalloutTx ( DeviceObject, WfpSession, CalloutClassifyConnect, &ST_FW_CALLOUT_CLASSIFY_CONNECT_IPV4_KEY, &FWPM_LAYER_ALE_CONNECT_REDIRECT_V4, L"Mullvad Split Tunnel Connect Redirect Callout (IPv4)", L"Adjusts properties on new network connections" ); if (!NT_SUCCESS(status)) { return status; } status = RegisterCalloutTx ( DeviceObject, WfpSession, CalloutClassifyConnect, &ST_FW_CALLOUT_CLASSIFY_CONNECT_IPV6_KEY, &FWPM_LAYER_ALE_CONNECT_REDIRECT_V6, L"Mullvad Split Tunnel Connect Redirect Callout (IPv6)", L"Adjusts properties on new network connections" ); if (!NT_SUCCESS(status)) { UnregisterCalloutClassifyConnect(); } return status; } NTSTATUS UnregisterCalloutClassifyConnect ( ) { auto s1 = UnregisterCallout(&ST_FW_CALLOUT_CLASSIFY_CONNECT_IPV4_KEY); auto s2 = UnregisterCallout(&ST_FW_CALLOUT_CLASSIFY_CONNECT_IPV6_KEY); RETURN_IF_UNSUCCESSFUL(s1); RETURN_IF_UNSUCCESSFUL(s2); return STATUS_SUCCESS; } // // RegisterCalloutPermitSplitAppsTx() // // Register callout with WFP. In all applicable layers. // // "Tx" (in transaction) suffix means there is no clean-up in failure paths. // NTSTATUS RegisterCalloutPermitSplitAppsTx ( PDEVICE_OBJECT DeviceObject, HANDLE WfpSession ) { auto status = RegisterCalloutTx ( DeviceObject, WfpSession, CalloutPermitSplitApps, &ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV4_CONN_KEY, &FWPM_LAYER_ALE_AUTH_CONNECT_V4, L"Mullvad Split Tunnel Permitting Callout (IPv4)", L"Permits selected connections outside the tunnel" ); if (!NT_SUCCESS(status)) { return status; } status = RegisterCalloutTx ( DeviceObject, WfpSession, CalloutPermitSplitApps, &ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV4_RECV_KEY, &FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4, L"Mullvad Split Tunnel Permitting Callout (IPv4)", L"Permits selected connections outside the tunnel" ); if (!NT_SUCCESS(status)) { UnregisterCalloutPermitSplitApps(); return status; } status = RegisterCalloutTx ( DeviceObject, WfpSession, CalloutPermitSplitApps, &ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV6_CONN_KEY, &FWPM_LAYER_ALE_AUTH_CONNECT_V6, L"Mullvad Split Tunnel Permitting Callout (IPv6)", L"Permits selected connections outside the tunnel" ); if (!NT_SUCCESS(status)) { UnregisterCalloutPermitSplitApps(); return status; } status = RegisterCalloutTx ( DeviceObject, WfpSession, CalloutPermitSplitApps, &ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV6_RECV_KEY, &FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6, L"Mullvad Split Tunnel Permitting Callout (IPv6)", L"Permits selected connections outside the tunnel" ); if (!NT_SUCCESS(status)) { UnregisterCalloutPermitSplitApps(); return status; } return STATUS_SUCCESS; } NTSTATUS UnregisterCalloutPermitSplitApps ( ) { auto s1 = UnregisterCallout(&ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV4_CONN_KEY); auto s2 = UnregisterCallout(&ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV4_RECV_KEY); auto s3 = UnregisterCallout(&ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV6_CONN_KEY); auto s4 = UnregisterCallout(&ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV6_RECV_KEY); RETURN_IF_UNSUCCESSFUL(s1); RETURN_IF_UNSUCCESSFUL(s2); RETURN_IF_UNSUCCESSFUL(s3); RETURN_IF_UNSUCCESSFUL(s4); return STATUS_SUCCESS; } // // RegisterCalloutBlockSplitAppsTx() // // Register callout with WFP. In all applicable layers. // // "Tx" (in transaction) suffix means there is no clean-up in failure paths. // NTSTATUS RegisterCalloutBlockSplitAppsTx ( PDEVICE_OBJECT DeviceObject, HANDLE WfpSession ) { auto status = RegisterCalloutTx ( DeviceObject, WfpSession, CalloutBlockSplitApps, &ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV4_CONN_KEY, &FWPM_LAYER_ALE_AUTH_CONNECT_V4, L"Mullvad Split Tunnel Blocking Callout (IPv4)", L"Blocks unwanted connections in relation to splitting" ); if (!NT_SUCCESS(status)) { return status; } status = RegisterCalloutTx ( DeviceObject, WfpSession, CalloutBlockSplitApps, &ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV4_RECV_KEY, &FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4, L"Mullvad Split Tunnel Blocking Callout (IPv4)", L"Blocks unwanted connections in relation to splitting" ); if (!NT_SUCCESS(status)) { UnregisterCalloutBlockSplitApps(); return status; } status = RegisterCalloutTx ( DeviceObject, WfpSession, CalloutBlockSplitApps, &ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV6_CONN_KEY, &FWPM_LAYER_ALE_AUTH_CONNECT_V6, L"Mullvad Split Tunnel Blocking Callout (IPv6)", L"Blocks unwanted connections in relation to splitting" ); if (!NT_SUCCESS(status)) { UnregisterCalloutBlockSplitApps(); return status; } status = RegisterCalloutTx ( DeviceObject, WfpSession, CalloutBlockSplitApps, &ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV6_RECV_KEY, &FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6, L"Mullvad Split Tunnel Blocking Callout (IPv6)", L"Blocks unwanted connections in relation to splitting" ); if (!NT_SUCCESS(status)) { UnregisterCalloutBlockSplitApps(); return status; } return STATUS_SUCCESS; } NTSTATUS UnregisterCalloutBlockSplitApps ( ) { auto s1 = UnregisterCallout(&ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV4_CONN_KEY); auto s2 = UnregisterCallout(&ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV4_RECV_KEY); auto s3 = UnregisterCallout(&ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV6_CONN_KEY); auto s4 = UnregisterCallout(&ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV6_RECV_KEY); RETURN_IF_UNSUCCESSFUL(s1); RETURN_IF_UNSUCCESSFUL(s2); RETURN_IF_UNSUCCESSFUL(s3); RETURN_IF_UNSUCCESSFUL(s4); return STATUS_SUCCESS; } } // namespace firewall
34,417
C++
.cpp
1,272
24.370283
105
0.756232
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,040
appfilters.cpp
mullvad_win-split-tunnel/src/firewall/appfilters.cpp
#include "wfp.h" #include "identifiers.h" #include "constants.h" #include "../defs/types.h" #include "../util.h" #include "appfilters.h" #include "../trace.h" #include "appfilters.tmh" namespace firewall::appfilters { namespace { struct BLOCK_CONNECTIONS_ENTRY { LIST_ENTRY ListEntry; // // Device path using all lower-case characters. // LOWER_UNICODE_STRING ImageName; // // Number of process instances that use this entry. // SIZE_T RefCount; // // WFP filter IDs. // UINT64 OutboundFilterIdV4; UINT64 InboundFilterIdV4; UINT64 OutboundFilterIdV6; UINT64 InboundFilterIdV6; }; struct APP_FILTERS_CONTEXT { HANDLE WfpSession; LIST_ENTRY BlockedTunnelConnections; LIST_ENTRY TransactionEvents; }; // // Transaction events represent logically atomic operations on the list of // block-connection entries. // // The most recent event is represented by the transaction event record at the head of // the transaction record list. // // An individual event record states what action needs to be taken // to undo a change to the block-connection list. // enum class TRANSACTION_EVENT_TYPE { INCREMENT_REF_COUNT, DECREMENT_REF_COUNT, ADD_ENTRY, REMOVE_ENTRY, SWAP_LISTS }; struct TRANSACTION_EVENT { LIST_ENTRY ListEntry; TRANSACTION_EVENT_TYPE EventType; BLOCK_CONNECTIONS_ENTRY *Target; }; struct TRANSACTION_EVENT_ADD_ENTRY { LIST_ENTRY ListEntry; TRANSACTION_EVENT_TYPE EventType; BLOCK_CONNECTIONS_ENTRY *Target; // // This may or may not be the real list head. // We insert to the right of it. // LIST_ENTRY *MockHead; }; struct TRANSACTION_EVENT_SWAP_LISTS { LIST_ENTRY ListEntry; TRANSACTION_EVENT_TYPE EventType; // // This is the list head of the previous list. // LIST_ENTRY BlockedTunnelConnections; }; NTSTATUS PushTransactionEvent ( LIST_ENTRY *TransactionEvents, TRANSACTION_EVENT_TYPE EventType, BLOCK_CONNECTIONS_ENTRY *Target ) { auto evt = (TRANSACTION_EVENT*)ExAllocatePoolUninitialized(NonPagedPool, sizeof(TRANSACTION_EVENT), ST_POOL_TAG); if (evt == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } InitializeListHead(&evt->ListEntry); evt->EventType = EventType; evt->Target = Target; InsertHeadList(TransactionEvents, &evt->ListEntry); return STATUS_SUCCESS; } NTSTATUS TransactionIncrementedRefCount ( LIST_ENTRY *TransactionEvents, BLOCK_CONNECTIONS_ENTRY *Target ) { return PushTransactionEvent ( TransactionEvents, TRANSACTION_EVENT_TYPE::DECREMENT_REF_COUNT, Target ); } NTSTATUS TransactionDecrementedRefCount ( LIST_ENTRY *TransactionEvents, BLOCK_CONNECTIONS_ENTRY *Target ) { return PushTransactionEvent ( TransactionEvents, TRANSACTION_EVENT_TYPE::INCREMENT_REF_COUNT, Target ); } NTSTATUS TransactionAddedEntry ( LIST_ENTRY *TransactionEvents, BLOCK_CONNECTIONS_ENTRY *Target ) { return PushTransactionEvent ( TransactionEvents, TRANSACTION_EVENT_TYPE::REMOVE_ENTRY, Target ); } NTSTATUS TransactionRemovedEntry ( LIST_ENTRY *TransactionEvents, BLOCK_CONNECTIONS_ENTRY *Target, LIST_ENTRY *MockHead ) { auto evt = (TRANSACTION_EVENT_ADD_ENTRY*) ExAllocatePoolUninitialized(NonPagedPool, sizeof(TRANSACTION_EVENT_ADD_ENTRY), ST_POOL_TAG); if (evt == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } InitializeListHead(&evt->ListEntry); evt->EventType = TRANSACTION_EVENT_TYPE::ADD_ENTRY; evt->Target = Target; evt->MockHead = MockHead; InsertHeadList(TransactionEvents, &evt->ListEntry); return STATUS_SUCCESS; } NTSTATUS TransactionSwappedLists ( LIST_ENTRY *TransactionEvents, LIST_ENTRY *BlockedTunnelConnections ) { auto evt = (TRANSACTION_EVENT_SWAP_LISTS*) ExAllocatePoolUninitialized(NonPagedPool, sizeof(TRANSACTION_EVENT_SWAP_LISTS), ST_POOL_TAG); if (evt == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } InitializeListHead(&evt->ListEntry); evt->EventType = TRANSACTION_EVENT_TYPE::SWAP_LISTS; // // Ownership of list is moved to transaction entry. // util::ReparentList(&evt->BlockedTunnelConnections, BlockedTunnelConnections); InsertHeadList(TransactionEvents, &evt->ListEntry); return STATUS_SUCCESS; } // // CustomGetAppIdFromFileName() // // The API FwpmGetAppIdFromFileName() is not exposed in kernel mode, but we // don't need it. All it does is look up the device path which we already have. // // However, for some reason the string also has to be null-terminated. // NTSTATUS CustomGetAppIdFromFileName ( const LOWER_UNICODE_STRING *ImageName, FWP_BYTE_BLOB **AppId ) { auto offsetStringBuffer = util::RoundToMultiple(sizeof(FWP_BYTE_BLOB), TYPE_ALIGNMENT(WCHAR)); UINT32 copiedStringLength = ImageName->Length + sizeof(WCHAR); auto allocationSize = offsetStringBuffer + copiedStringLength; auto blob = (FWP_BYTE_BLOB*) ExAllocatePoolUninitialized(PagedPool, allocationSize, ST_POOL_TAG); if (blob == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } auto stringBuffer = ((UINT8*)blob) + offsetStringBuffer; RtlCopyMemory(stringBuffer, ImageName->Buffer, ImageName->Length); stringBuffer[copiedStringLength - 2] = 0; stringBuffer[copiedStringLength - 1] = 0; blob->size = copiedStringLength; blob->data = stringBuffer; *AppId = blob; return STATUS_SUCCESS; } // // FindBlockConnectionsEntry() // // Returns pointer to matching entry or NULL. // BLOCK_CONNECTIONS_ENTRY* FindBlockConnectionsEntry ( LIST_ENTRY *List, const LOWER_UNICODE_STRING *ImageName ) { for (auto entry = List->Flink; entry != List; entry = entry->Flink) { auto candidate = (BLOCK_CONNECTIONS_ENTRY*)entry; if (util::Equal(ImageName, &candidate->ImageName)) { return candidate; } } return NULL; } NTSTATUS AddTunnelBlockFiltersTx ( HANDLE WfpSession, const LOWER_UNICODE_STRING *ImageName, const IN_ADDR *TunnelIpv4, const IN6_ADDR *TunnelIpv6, UINT64 *OutboundFilterIdV4, UINT64 *InboundFilterIdV4, UINT64 *OutboundFilterIdV6, UINT64 *InboundFilterIdV6 ) { NT_ASSERT ( OutboundFilterIdV4 != NULL && InboundFilterIdV4 != NULL && OutboundFilterIdV6 != NULL && InboundFilterIdV6 != NULL ); // // Format APP_ID payload that will be used with all filters. // FWP_BYTE_BLOB *appIdPayload; auto status = CustomGetAppIdFromFileName(ImageName, &appIdPayload); if (!NT_SUCCESS(status)) { return status; } if (TunnelIpv4 == NULL) { *OutboundFilterIdV4 = 0; *InboundFilterIdV4 = 0; } else { // // Register outbound IPv4 filter. // FWPM_FILTER0 filter = { 0 }; const auto FilterNameOutboundIpv4 = L"Mullvad Split Tunnel In-Tunnel Blocking Filter (Outbound IPv4)"; const auto FilterDescription = L"Blocks existing connections in the tunnel"; filter.displayData.name = const_cast<wchar_t*>(FilterNameOutboundIpv4); filter.displayData.description = const_cast<wchar_t*>(FilterDescription); filter.flags = FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT | FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT; filter.providerKey = const_cast<GUID*>(&ST_FW_PROVIDER_KEY); filter.layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V4; filter.subLayerKey = ST_FW_WINFW_BASELINE_SUBLAYER_KEY; filter.weight.type = FWP_UINT64; filter.weight.uint64 = const_cast<UINT64*>(&ST_MAX_FILTER_WEIGHT); filter.action.type = FWP_ACTION_CALLOUT_UNKNOWN; filter.action.calloutKey = ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV4_CONN_KEY; filter.providerContextKey = ST_FW_PROVIDER_CONTEXT_KEY; // // Conditions are: // // APP_ID == ImageName // LOCAL_ADDRESS == TunnelIp // FWPM_FILTER_CONDITION0 cond[2]; cond[0].fieldKey = FWPM_CONDITION_ALE_APP_ID; cond[0].matchType = FWP_MATCH_EQUAL; cond[0].conditionValue.type = FWP_BYTE_BLOB_TYPE; cond[0].conditionValue.byteBlob = appIdPayload; cond[1].fieldKey = FWPM_CONDITION_IP_LOCAL_ADDRESS; cond[1].matchType = FWP_MATCH_EQUAL; cond[1].conditionValue.type = FWP_UINT32; cond[1].conditionValue.uint32 = RtlUlongByteSwap(TunnelIpv4->s_addr); filter.filterCondition = cond; filter.numFilterConditions = ARRAYSIZE(cond); status = FwpmFilterAdd0(WfpSession, &filter, NULL, OutboundFilterIdV4); if (!NT_SUCCESS(status)) { goto Cleanup; } // // Register inbound IPv4 filter. // const auto FilterNameInboundIpv4 = L"Mullvad Split Tunnel In-Tunnel Blocking Filter (Inbound IPv4)"; RtlZeroMemory(&filter.filterKey, sizeof(filter.filterKey)); filter.displayData.name = const_cast<wchar_t*>(FilterNameInboundIpv4); filter.layerKey = FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4; filter.action.calloutKey = ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV4_RECV_KEY; status = FwpmFilterAdd0(WfpSession, &filter, NULL, InboundFilterIdV4); if (!NT_SUCCESS(status)) { goto Cleanup; } } if (TunnelIpv6 == NULL) { *OutboundFilterIdV6 = 0; *InboundFilterIdV6 = 0; } else { // // Register outbound IPv6 filter. // FWPM_FILTER0 filter = { 0 }; const auto FilterNameOutboundIpv6 = L"Mullvad Split Tunnel In-Tunnel Blocking Filter (Outbound IPv6)"; const auto FilterDescription = L"Blocks existing connections in the tunnel"; filter.displayData.name = const_cast<wchar_t*>(FilterNameOutboundIpv6); filter.displayData.description = const_cast<wchar_t*>(FilterDescription); filter.flags = FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT | FWPM_FILTER_FLAG_HAS_PROVIDER_CONTEXT; filter.providerKey = const_cast<GUID*>(&ST_FW_PROVIDER_KEY); filter.layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V6; filter.subLayerKey = ST_FW_WINFW_BASELINE_SUBLAYER_KEY; filter.weight.type = FWP_UINT64; filter.weight.uint64 = const_cast<UINT64*>(&ST_MAX_FILTER_WEIGHT); filter.action.type = FWP_ACTION_CALLOUT_UNKNOWN; filter.action.calloutKey = ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV6_CONN_KEY; filter.providerContextKey = ST_FW_PROVIDER_CONTEXT_KEY; // // Conditions are: // // APP_ID == ImageName // LOCAL_ADDRESS == TunnelIp // FWPM_FILTER_CONDITION0 cond[2]; cond[0].fieldKey = FWPM_CONDITION_ALE_APP_ID; cond[0].matchType = FWP_MATCH_EQUAL; cond[0].conditionValue.type = FWP_BYTE_BLOB_TYPE; cond[0].conditionValue.byteBlob = appIdPayload; cond[1].fieldKey = FWPM_CONDITION_IP_LOCAL_ADDRESS; cond[1].matchType = FWP_MATCH_EQUAL; cond[1].conditionValue.type = FWP_BYTE_ARRAY16_TYPE; cond[1].conditionValue.byteArray16 = (FWP_BYTE_ARRAY16*)TunnelIpv6->u.Byte; filter.filterCondition = cond; filter.numFilterConditions = ARRAYSIZE(cond); status = FwpmFilterAdd0(WfpSession, &filter, NULL, OutboundFilterIdV6); if (!NT_SUCCESS(status)) { goto Cleanup; } // // Register inbound IPv6 filter. // const auto FilterNameInboundIpv6 = L"Mullvad Split Tunnel In-Tunnel Blocking Filter (Inbound IPv6)"; RtlZeroMemory(&filter.filterKey, sizeof(filter.filterKey)); filter.displayData.name = const_cast<wchar_t*>(FilterNameInboundIpv6); filter.layerKey = FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6; filter.action.calloutKey = ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV6_RECV_KEY; status = FwpmFilterAdd0(WfpSession, &filter, NULL, InboundFilterIdV6); if (!NT_SUCCESS(status)) { goto Cleanup; } } status = STATUS_SUCCESS; Cleanup: ExFreePoolWithTag(appIdPayload, ST_POOL_TAG); return status; } typedef NTSTATUS (*AddBlockFiltersFunc) ( HANDLE WfpSession, const LOWER_UNICODE_STRING *ImageName, const IN_ADDR *TunnelIpv4, const IN6_ADDR *TunnelIpv6, UINT64 *OutboundFilterIdV4, UINT64 *InboundFilterIdV4, UINT64 *OutboundFilterIdV6, UINT64 *InboundFilterIdV6 ); NTSTATUS AddBlockFiltersCreateEntryTx ( HANDLE WfpSession, const LOWER_UNICODE_STRING *ImageName, const IN_ADDR *TunnelIpv4, const IN6_ADDR *TunnelIpv6, AddBlockFiltersFunc Blocker, BLOCK_CONNECTIONS_ENTRY **Entry ) { auto offsetStringBuffer = util::RoundToMultiple(sizeof(BLOCK_CONNECTIONS_ENTRY), TYPE_ALIGNMENT(WCHAR)); auto allocationSize = offsetStringBuffer + ImageName->Length; auto entry = (BLOCK_CONNECTIONS_ENTRY*) ExAllocatePoolUninitialized(PagedPool, allocationSize, ST_POOL_TAG); if (entry == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } RtlZeroMemory(entry, allocationSize); auto status = Blocker ( WfpSession, ImageName, TunnelIpv4, TunnelIpv6, &entry->OutboundFilterIdV4, &entry->InboundFilterIdV4, &entry->OutboundFilterIdV6, &entry->InboundFilterIdV6 ); if (!NT_SUCCESS(status)) { DbgPrint("Failed to add block filters: 0x%X\n", status); goto Cleanup; } auto stringBuffer = (WCHAR*)(((UINT8*)entry) + offsetStringBuffer); InitializeListHead(&entry->ListEntry); entry->RefCount = 1; entry->ImageName.Length = ImageName->Length; entry->ImageName.MaximumLength = ImageName->Length; entry->ImageName.Buffer = stringBuffer; RtlCopyMemory(stringBuffer, ImageName->Buffer, ImageName->Length); *Entry = entry; return STATUS_SUCCESS; Cleanup: ExFreePoolWithTag(entry, ST_POOL_TAG); return status; } NTSTATUS RemoveBlockFiltersTx ( HANDLE WfpSession, UINT64 OutboundFilterIdV4, UINT64 InboundFilterIdV4, UINT64 OutboundFilterIdV6, UINT64 InboundFilterIdV6 ) { // // Filters were installed in pairs. // NT_ASSERT(OutboundFilterIdV4 != 0 || OutboundFilterIdV6 != 0); auto status = STATUS_SUCCESS; if (OutboundFilterIdV4 != 0) { status = FwpmFilterDeleteById0(WfpSession, OutboundFilterIdV4); if (!NT_SUCCESS(status)) { return status; } NT_ASSERT(InboundFilterIdV4 != 0); status = FwpmFilterDeleteById0(WfpSession, InboundFilterIdV4); if (!NT_SUCCESS(status)) { return status; } } if (OutboundFilterIdV6 != 0) { status = FwpmFilterDeleteById0(WfpSession, OutboundFilterIdV6); if (!NT_SUCCESS(status)) { return status; } NT_ASSERT(InboundFilterIdV6 != 0); status = FwpmFilterDeleteById0(WfpSession, InboundFilterIdV6); if (!NT_SUCCESS(status)) { return status; } } return STATUS_SUCCESS; } NTSTATUS RemoveBlockFiltersAndEntryTx ( HANDLE WfpSession, LIST_ENTRY *TransactionEvents, BLOCK_CONNECTIONS_ENTRY *Entry ) { auto status = RemoveBlockFiltersTx ( WfpSession, Entry->OutboundFilterIdV4, Entry->InboundFilterIdV4, Entry->OutboundFilterIdV6, Entry->InboundFilterIdV6 ); if (!NT_SUCCESS(status)) { DbgPrint("Could not remove block filters: 0x%X\n", status); return status; } // // Record in transaction history before unlinking, because the former is a fallible operation. // status = TransactionRemovedEntry(TransactionEvents, Entry, Entry->ListEntry.Blink); if (!NT_SUCCESS(status)) { DbgPrint("Could not update local transaction: 0x%X\n", status); return status; } RemoveEntryList(&Entry->ListEntry); return STATUS_SUCCESS; } void FreeList ( LIST_ENTRY *List ) { LIST_ENTRY *entry; while ((entry = RemoveHeadList(List)) != List) { ExFreePoolWithTag(entry, ST_POOL_TAG); } } } // anonymous namespace NTSTATUS Initialize ( HANDLE WfpSession, void **Context ) { auto context = (APP_FILTERS_CONTEXT*) ExAllocatePoolUninitialized(PagedPool, sizeof(APP_FILTERS_CONTEXT), ST_POOL_TAG); if (context == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } context->WfpSession = WfpSession; InitializeListHead(&context->BlockedTunnelConnections); InitializeListHead(&context->TransactionEvents); *Context = context; return STATUS_SUCCESS; } void TearDown ( void **Context ) { auto context = (APP_FILTERS_CONTEXT*)*Context; // // This is a best effort venture so just keep going. // // Remove all app specific filters. // for (auto rawEntry = context->BlockedTunnelConnections.Flink; rawEntry != &context->BlockedTunnelConnections; /* no post-condition */) { auto entry = (BLOCK_CONNECTIONS_ENTRY*)rawEntry; RemoveBlockFiltersTx ( context->WfpSession, entry->OutboundFilterIdV4, entry->InboundFilterIdV4, entry->OutboundFilterIdV6, entry->InboundFilterIdV6 ); auto next = rawEntry->Flink; ExFreePoolWithTag(rawEntry, ST_POOL_TAG); rawEntry = next; } InitializeListHead(&context->BlockedTunnelConnections); // // This works because a commit discards all transaction events. // (Also, there shouldn't be any events at this time.) // if (!IsListEmpty(&context->TransactionEvents)) { DbgPrint("ERROR: Active transaction while tearing down appfilters module\n"); } TransactionCommit(*Context); // // Release context. // ExFreePoolWithTag(context, ST_POOL_TAG); *Context = NULL; } NTSTATUS TransactionBegin ( void *Context ) { auto context = (APP_FILTERS_CONTEXT*)Context; if (IsListEmpty(&context->TransactionEvents)) { return STATUS_SUCCESS; } return STATUS_TRANSACTION_REQUEST_NOT_VALID; } void TransactionCommit ( void *Context ) { // // All changes are already applied, discard transaction events. // // Each event has to be released, and some of them point to // a target entry which must also be released. // auto context = (APP_FILTERS_CONTEXT*)Context; auto list = &context->TransactionEvents; LIST_ENTRY *rawEvent; while ((rawEvent = RemoveHeadList(list)) != list) { switch (((TRANSACTION_EVENT*)rawEvent)->EventType) { case TRANSACTION_EVENT_TYPE::ADD_ENTRY: { auto addEvent = (TRANSACTION_EVENT_ADD_ENTRY*)rawEvent; ExFreePoolWithTag(addEvent->Target, ST_POOL_TAG); break; } case TRANSACTION_EVENT_TYPE::SWAP_LISTS: { auto swapEvent = (TRANSACTION_EVENT_SWAP_LISTS*)rawEvent; FreeList(&swapEvent->BlockedTunnelConnections); break; } } ExFreePoolWithTag(rawEvent, ST_POOL_TAG); } } void TransactionAbort ( void *Context ) { // // Step back through event records and undo all changes. // auto context = (APP_FILTERS_CONTEXT*)Context; auto list = &context->TransactionEvents; LIST_ENTRY *rawEvent; while ((rawEvent = RemoveHeadList(list)) != list) { auto evt = (TRANSACTION_EVENT*)rawEvent; switch (evt->EventType) { case TRANSACTION_EVENT_TYPE::INCREMENT_REF_COUNT: { ++evt->Target->RefCount; break; } case TRANSACTION_EVENT_TYPE::DECREMENT_REF_COUNT: { --evt->Target->RefCount; break; } case TRANSACTION_EVENT_TYPE::ADD_ENTRY: { auto addEvent = (TRANSACTION_EVENT_ADD_ENTRY*)rawEvent; InsertHeadList(addEvent->MockHead, &addEvent->Target->ListEntry); break; } case TRANSACTION_EVENT_TYPE::REMOVE_ENTRY: { RemoveEntryList(&evt->Target->ListEntry); ExFreePoolWithTag(evt->Target, ST_POOL_TAG); break; } case TRANSACTION_EVENT_TYPE::SWAP_LISTS: { auto liveList = &context->BlockedTunnelConnections; FreeList(liveList); auto swapEvent = (TRANSACTION_EVENT_SWAP_LISTS*)rawEvent; util::ReparentList(liveList, &swapEvent->BlockedTunnelConnections); break; } }; ExFreePoolWithTag(rawEvent, ST_POOL_TAG); } } // // RegisterFilterBlockAppTunnelTrafficTx2() // // Register filters that block tunnel traffic for a specific app. // // This is primarily done to ensure an application's existing connections are // blocked when the app starts being split. // // When filters are added, a re-auth occurs, and matching existing connections // are presented to the linked callout, to approve or block. // NTSTATUS RegisterFilterBlockAppTunnelTrafficTx2 ( void *Context, const LOWER_UNICODE_STRING *ImageName, const IN_ADDR *TunnelIpv4, const IN6_ADDR *TunnelIpv6 ) { if (TunnelIpv4 == NULL && TunnelIpv6 == NULL) { return STATUS_INVALID_PARAMETER; } auto context = (APP_FILTERS_CONTEXT*)Context; auto existingEntry = FindBlockConnectionsEntry(&context->BlockedTunnelConnections, ImageName); if (existingEntry != NULL) { auto status = TransactionIncrementedRefCount(&context->TransactionEvents, existingEntry); if (!NT_SUCCESS(status)) { DbgPrint("Could not update local transaction: 0x%X\n", status); return status; } ++existingEntry->RefCount; return STATUS_SUCCESS; } BLOCK_CONNECTIONS_ENTRY *entry; auto status = AddBlockFiltersCreateEntryTx ( context->WfpSession, ImageName, TunnelIpv4, TunnelIpv6, AddTunnelBlockFiltersTx, &entry ); if (!NT_SUCCESS(status)) { return status; } status = TransactionAddedEntry(&context->TransactionEvents, entry); if (!NT_SUCCESS(status)) { DbgPrint("Could not update local transaction: 0x%X\n", status); ExFreePoolWithTag(entry, ST_POOL_TAG); return status; } InsertTailList(&context->BlockedTunnelConnections, &entry->ListEntry); DbgPrint("Added tunnel block filters for %wZ\n", (const UNICODE_STRING*)ImageName); return STATUS_SUCCESS; } NTSTATUS RemoveFilterBlockAppTunnelTrafficTx2 ( void *Context, const LOWER_UNICODE_STRING *ImageName ) { auto context = (APP_FILTERS_CONTEXT*)Context; auto entry = FindBlockConnectionsEntry(&context->BlockedTunnelConnections, ImageName); if (entry == NULL) { return STATUS_INVALID_PARAMETER; } if (entry->RefCount > 1) { auto status = TransactionDecrementedRefCount(&context->TransactionEvents, entry); if (!NT_SUCCESS(status)) { DbgPrint("Could not update local transaction: 0x%X\n", status); return status; } --entry->RefCount; // // TODO: Indicate to layer above that it might want to force an ALE reauthorization in WFP. // // https://docs.microsoft.com/en-us/windows/win32/fwp/ale-re-authorization // // Forcing a reauthorization is only necessary in very specific cases. Usually the transaction // will include the addition/removal of at least one filter, and this triggers a reauthorization. // // Also, the issue only comes into play if a process stops being split but keeps running. // // Rationale: // // There could be existing connections which have been blocked for some duration of time // and now need to be reauthorized in WFP so they are no longer blocked. // // Similarly, there could be non-tunnel connections that were previously approved // and should now be reauthorized so they can be blocked. // return STATUS_SUCCESS; } auto status = RemoveBlockFiltersAndEntryTx ( context->WfpSession, &context->TransactionEvents, entry ); if (NT_SUCCESS(status)) { DbgPrint("Removed tunnel block filters for %wZ\n", (const UNICODE_STRING*)ImageName); } return status; } NTSTATUS ResetTx2 ( void *Context ) { auto context = (APP_FILTERS_CONTEXT*)Context; if (IsListEmpty(&context->BlockedTunnelConnections)) { return STATUS_SUCCESS; } for (auto rawEntry = context->BlockedTunnelConnections.Flink; rawEntry != &context->BlockedTunnelConnections; rawEntry = rawEntry->Flink) { auto entry = (BLOCK_CONNECTIONS_ENTRY*)rawEntry; auto status = RemoveBlockFiltersTx ( context->WfpSession, entry->OutboundFilterIdV4, entry->InboundFilterIdV4, entry->OutboundFilterIdV6, entry->InboundFilterIdV6 ); if (!NT_SUCCESS(status)) { return status; } } // // Create transaction event and pass ownership of list to it. // auto status = TransactionSwappedLists(&context->TransactionEvents, &context->BlockedTunnelConnections); if (!NT_SUCCESS(status)) { return STATUS_INSUFFICIENT_RESOURCES; } // // Clear list to reflect new state. // InitializeListHead(&context->BlockedTunnelConnections); return STATUS_SUCCESS; } NTSTATUS UpdateFiltersTx2 ( void *Context, const IN_ADDR *TunnelIpv4, const IN6_ADDR *TunnelIpv6 ) { auto context = (APP_FILTERS_CONTEXT*)Context; if (IsListEmpty(&context->BlockedTunnelConnections)) { return STATUS_SUCCESS; } LIST_ENTRY newList; InitializeListHead(&newList); for (auto rawEntry = context->BlockedTunnelConnections.Flink; rawEntry != &context->BlockedTunnelConnections; rawEntry = rawEntry->Flink) { auto entry = (BLOCK_CONNECTIONS_ENTRY*)rawEntry; auto status = RemoveBlockFiltersTx ( context->WfpSession, entry->OutboundFilterIdV4, entry->InboundFilterIdV4, entry->OutboundFilterIdV6, entry->InboundFilterIdV6 ); if (!NT_SUCCESS(status)) { FreeList(&newList); return status; } BLOCK_CONNECTIONS_ENTRY *newEntry; status = AddBlockFiltersCreateEntryTx ( context->WfpSession, &entry->ImageName, TunnelIpv4, TunnelIpv6, AddTunnelBlockFiltersTx, &newEntry ); if (!NT_SUCCESS(status)) { FreeList(&newList); return status; } newEntry->RefCount = entry->RefCount; InsertTailList(&newList, &newEntry->ListEntry); } // // context->BlockedTunnelConnections is now completely obsolete. // newList has all the updated entries. // auto status = TransactionSwappedLists(&context->TransactionEvents, &context->BlockedTunnelConnections); if (!NT_SUCCESS(status)) { FreeList(&newList); return status; } // // Ownership of the list formerly rooted at context->BlockedTunnelConnections // has been moved to the recently queued transaction event. // // Perform actual state update. // util::ReparentList(&context->BlockedTunnelConnections, &newList); return STATUS_SUCCESS; } } // namespace firewall::appfilters
24,759
C++
.cpp
942
23.739915
114
0.763271
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,041
mode.cpp
mullvad_win-split-tunnel/src/firewall/mode.cpp
#include "mode.h" namespace firewall { NTSTATUS DetermineSplittingMode ( const ST_IP_ADDRESSES *IpAddresses, SPLITTING_MODE *Mode ) { const auto internetV4 = ip::ValidInternetIpv4Address(IpAddresses); const auto internetV6 = ip::ValidInternetIpv6Address(IpAddresses); const auto tunnelV4 = ip::ValidTunnelIpv4Address(IpAddresses); const auto tunnelV6 = ip::ValidTunnelIpv6Address(IpAddresses); if (internetV4 && tunnelV4 && internetV6 && tunnelV6) { *Mode = SPLITTING_MODE::MODE_1; return STATUS_SUCCESS; } if (internetV4 && tunnelV4 && !internetV6 && !tunnelV6) { *Mode = SPLITTING_MODE::MODE_2; return STATUS_SUCCESS; } if (internetV4 && tunnelV4 && internetV6 && !tunnelV6) { *Mode = SPLITTING_MODE::MODE_3; return STATUS_SUCCESS; } if (internetV4 && tunnelV4 && !internetV6 && tunnelV6) { *Mode = SPLITTING_MODE::MODE_4; return STATUS_SUCCESS; } if (!internetV4 && !tunnelV4 && internetV6 && tunnelV6) { *Mode = SPLITTING_MODE::MODE_5; return STATUS_SUCCESS; } if (internetV4 && !tunnelV4 && internetV6 && tunnelV6) { *Mode = SPLITTING_MODE::MODE_6; return STATUS_SUCCESS; } if (!internetV4 && tunnelV4 && internetV6 && tunnelV6) { *Mode = SPLITTING_MODE::MODE_7; return STATUS_SUCCESS; } if (!internetV4 && tunnelV4 && internetV6 && !tunnelV6) { *Mode = SPLITTING_MODE::MODE_8; return STATUS_SUCCESS; } if (internetV4 && !tunnelV4 && !internetV6 && tunnelV6) { *Mode = SPLITTING_MODE::MODE_9; return STATUS_SUCCESS; } return STATUS_INVALID_DISPOSITION; } } // namespace firewall
1,567
C++
.cpp
62
22.935484
67
0.72319
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,042
pending.cpp
mullvad_win-split-tunnel/src/firewall/pending.cpp
#include "pending.h" #include "classify.h" #include "../util.h" #include "../trace.h" #include "pending.tmh" namespace firewall::pending { struct PENDED_CLASSIFICATION { LIST_ENTRY ListEntry; // Process that's making the request. HANDLE ProcessId; // Timestamp when record was created. ULONGLONG Timestamp; // Handle used to trigger re-auth or resume processing. UINT64 ClassifyHandle; // Result of classification is recorded here. FWPS_CLASSIFY_OUT0 ClassifyOut; // Filter that triggered the classification. UINT64 FilterId; // Layer in which classification is occurring. UINT16 LayerId; }; struct CONTEXT { procbroker::CONTEXT *ProcessEventBroker; WDFSPINLOCK Lock; // PENDED_CLASSIFICATION LIST_ENTRY Classifications; }; namespace { const ULONGLONG RECORD_MAX_LIFETIME_MS = 10000; bool AssertCompatibleLayer ( UINT16 LayerId ) { NT_ASSERT ( LayerId == FWPS_LAYER_ALE_BIND_REDIRECT_V4 || LayerId == FWPS_LAYER_ALE_BIND_REDIRECT_V6 || LayerId == FWPS_LAYER_ALE_CONNECT_REDIRECT_V4 || LayerId == FWPS_LAYER_ALE_CONNECT_REDIRECT_V6 ); if (LayerId == FWPS_LAYER_ALE_BIND_REDIRECT_V4 || LayerId == FWPS_LAYER_ALE_BIND_REDIRECT_V6 || LayerId == FWPS_LAYER_ALE_CONNECT_REDIRECT_V4 || LayerId == FWPS_LAYER_ALE_CONNECT_REDIRECT_V6) { return true; } DbgPrint("Invalid layer id %d specified in call to 'pending' module\n", LayerId); return false; } const char* LayerToString ( UINT16 LayerId ) { char *string = "undefined"; switch (LayerId) { case FWPS_LAYER_ALE_BIND_REDIRECT_V4: { string = "FWPS_LAYER_ALE_BIND_REDIRECT_V4"; break; } case FWPS_LAYER_ALE_BIND_REDIRECT_V6: { string = "FWPS_LAYER_ALE_BIND_REDIRECT_V6"; break; } case FWPS_LAYER_ALE_CONNECT_REDIRECT_V4: { string = "FWPS_LAYER_ALE_CONNECT_REDIRECT_V4"; break; } case FWPS_LAYER_ALE_CONNECT_REDIRECT_V6: { string = "FWPS_LAYER_ALE_CONNECT_REDIRECT_V6"; break; } } return string; } NTSTATUS FailRequest ( UINT64 FilterId, UINT16 LayerId, FWPS_CLASSIFY_OUT0 *ClassifyOut, UINT64 ClassifyHandle ) { // // There doesn't seem to be any support in WFP for blocking requests in the redirect layers. // Specifying `FWP_ACTION_BLOCK` will just resume request processing. // So the best we can do is rewrite the request to do as little harm as possible. // PVOID requestData = NULL; auto status = FwpsAcquireWritableLayerDataPointer0 ( ClassifyHandle, FilterId, 0, &requestData, ClassifyOut ); if (!NT_SUCCESS(status)) { DbgPrint("FwpsAcquireWritableLayerDataPointer0() failed\n"); return status; } switch (LayerId) { case FWPS_LAYER_ALE_BIND_REDIRECT_V4: case FWPS_LAYER_ALE_BIND_REDIRECT_V6: { auto bindRequest = reinterpret_cast<FWPS_BIND_REQUEST0*>(requestData); // // This sets the port to 0, as well. // INETADDR_SETLOOPBACK((PSOCKADDR)&(bindRequest->localAddressAndPort)); break; } case FWPS_LAYER_ALE_CONNECT_REDIRECT_V4: case FWPS_LAYER_ALE_CONNECT_REDIRECT_V6: { auto connectRequest = reinterpret_cast<FWPS_CONNECT_REQUEST0*>(requestData); INETADDR_SETLOOPBACK((PSOCKADDR)&(connectRequest->localAddressAndPort)); break; } }; ClassificationApplyHardPermit(ClassifyOut); FwpsApplyModifiedLayerData0(ClassifyHandle, requestData, 0); return STATUS_SUCCESS; } void ReauthPendedRequest ( PENDED_CLASSIFICATION *Record ) { DbgPrint ( "Requesting re-auth for pended request in layer %s for process %p\n", LayerToString(Record->LayerId), Record->ProcessId ); FwpsCompleteClassify0(Record->ClassifyHandle, 0, NULL); FwpsReleaseClassifyHandle0(Record->ClassifyHandle); ExFreePoolWithTag(Record, ST_POOL_TAG); } void FailPendedRequest ( PENDED_CLASSIFICATION *Record, bool ReauthOnFailure = true ) { DbgPrint ( "Failing pended request in layer %s for process %p\n", LayerToString(Record->LayerId), Record->ProcessId ); const auto status = FailRequest ( Record->FilterId, Record->LayerId, &Record->ClassifyOut, Record->ClassifyHandle ); if (NT_SUCCESS(status)) { FwpsCompleteClassify0(Record->ClassifyHandle, 0, &Record->ClassifyOut); FwpsReleaseClassifyHandle0(Record->ClassifyHandle); } else { DbgPrint("FailRequest() failed 0x%X\n", status); if (ReauthOnFailure) { ReauthPendedRequest(Record); return; } } ExFreePoolWithTag(Record, ST_POOL_TAG); } // // FailAllPendedRequests() // // This function is used during tear down. // So we don't have the luxury of re-authing requests that can't be failed. // void FailAllPendedRequests ( CONTEXT *Context ) { for (auto rawRecord = Context->Classifications.Flink; rawRecord != &Context->Classifications; /* no post-condition */) { auto record = (PENDED_CLASSIFICATION*)rawRecord; rawRecord = rawRecord->Flink; RemoveEntryList(&record->ListEntry); FailPendedRequest(record, false); } } void HandleProcessEvent ( HANDLE ProcessId, bool Arriving, void *Context ) { auto context = (CONTEXT*)Context; auto timeNow = KeQueryInterruptTime(); static const ULONGLONG MS_TO_100NS_FACTOR = 10000; auto maxAge = RECORD_MAX_LIFETIME_MS * MS_TO_100NS_FACTOR; // // Iterate over all pended bind requests. // // Fail all requests that are too old. // Re-auth all requests that belong to the arriving process. // WdfSpinLockAcquire(context->Lock); for (auto rawRecord = context->Classifications.Flink; rawRecord != &context->Classifications; /* no post-condition */) { auto record = (PENDED_CLASSIFICATION*)rawRecord; rawRecord = rawRecord->Flink; auto timeDelta = timeNow - record->Timestamp; if (timeDelta > maxAge) { RemoveEntryList(&record->ListEntry); FailPendedRequest(record); continue; } if (record->ProcessId != ProcessId) { continue; } RemoveEntryList(&record->ListEntry); if (Arriving) { ReauthPendedRequest(record); } else { FailPendedRequest(record, false); } } WdfSpinLockRelease(context->Lock); } } // anonymous namespace NTSTATUS Initialize ( CONTEXT **Context, procbroker::CONTEXT *ProcessEventBroker ) { auto context = (CONTEXT*)ExAllocatePoolUninitialized(NonPagedPool, sizeof(CONTEXT), ST_POOL_TAG); if (context == NULL) { DbgPrint("ExAllocatePoolUninitialized() failed\n"); return STATUS_INSUFFICIENT_RESOURCES; } RtlZeroMemory(context, sizeof(*context)); context->ProcessEventBroker = ProcessEventBroker; auto status = WdfSpinLockCreate(WDF_NO_OBJECT_ATTRIBUTES, &context->Lock); if (!NT_SUCCESS(status)) { DbgPrint("WdfSpinLockCreate() failed\n"); goto Abort; } InitializeListHead(&context->Classifications); // // Everything is initialized. // Register with process event broker. // status = procbroker::Subscribe(ProcessEventBroker, HandleProcessEvent, context); if (!NT_SUCCESS(status)) { DbgPrint("Could not register with process event broker\n"); goto Abort_delete_lock; } *Context = context; return STATUS_SUCCESS; Abort_delete_lock: WdfObjectDelete(context->Lock); Abort: ExFreePoolWithTag(context, ST_POOL_TAG); return status; } void TearDown ( CONTEXT **Context ) { auto context = *Context; *Context = NULL; procbroker::CancelSubscription(context->ProcessEventBroker, HandleProcessEvent); FailAllPendedRequests(context); WdfObjectDelete(context->Lock); ExFreePoolWithTag(context, ST_POOL_TAG); } NTSTATUS PendRequest ( CONTEXT *Context, HANDLE ProcessId, void *ClassifyContext, UINT64 FilterId, UINT16 LayerId, FWPS_CLASSIFY_OUT0 *ClassifyOut ) { if (!AssertCompatibleLayer(LayerId)) { return STATUS_UNSUCCESSFUL; } DbgPrint ( "Pending request in layer %s for process %p\n", LayerToString(LayerId), ProcessId ); auto record = (PENDED_CLASSIFICATION*) ExAllocatePoolUninitialized(NonPagedPool, sizeof(PENDED_CLASSIFICATION), ST_POOL_TAG); if (record == NULL) { DbgPrint("ExAllocatePoolUninitialized() failed\n"); return STATUS_INSUFFICIENT_RESOURCES; } UINT64 classifyHandle; auto status = FwpsAcquireClassifyHandle0(ClassifyContext, 0, &classifyHandle); if (!NT_SUCCESS(status)) { DbgPrint("FwpsAcquireClassifyHandle0() failed\n"); goto Abort; } status = FwpsPendClassify0(classifyHandle, FilterId, 0, ClassifyOut); if (!NT_SUCCESS(status)) { DbgPrint("FwpsPendClassify0() failed\n"); FwpsReleaseClassifyHandle0(classifyHandle); goto Abort; } record->ProcessId = ProcessId; record->Timestamp = KeQueryInterruptTime(); record->ClassifyHandle = classifyHandle; record->ClassifyOut = *ClassifyOut; record->LayerId = LayerId; record->FilterId = FilterId; WdfSpinLockAcquire(Context->Lock); InsertTailList(&Context->Classifications, &record->ListEntry); WdfSpinLockRelease(Context->Lock); return STATUS_SUCCESS; Abort: ExFreePoolWithTag(record, ST_POOL_TAG); return status; } NTSTATUS FailRequest ( HANDLE ProcessId, void *ClassifyContext, UINT64 FilterId, UINT16 LayerId, FWPS_CLASSIFY_OUT0 *ClassifyOut ) { if (!AssertCompatibleLayer(LayerId)) { return STATUS_UNSUCCESSFUL; } DbgPrint ( "Failing request in layer %s for process %p\n", LayerToString(LayerId), ProcessId ); UINT64 classifyHandle = 0; auto status = FwpsAcquireClassifyHandle0 ( ClassifyContext, 0, &classifyHandle ); if (!NT_SUCCESS(status)) { DbgPrint("FwpsAcquireClassifyHandle0() failed\n"); return status; } status = FailRequest(FilterId, LayerId, ClassifyOut, classifyHandle); if (!NT_SUCCESS(status)) { return status; } FwpsReleaseClassifyHandle0(classifyHandle); return STATUS_SUCCESS; } } // namespace firewall::pending
10,816
C++
.cpp
413
20.77724
98
0.674593
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,043
firewall.cpp
mullvad_win-split-tunnel/src/firewall/firewall.cpp
#include "wfp.h" #include "context.h" #include "identifiers.h" #include "appfilters.h" #include "filters.h" #include "callouts.h" #include "constants.h" #include "pending.h" #include "logging.h" #include "../util.h" #include "../eventing/builder.h" #include "firewall.h" #include "../trace.h" #include "firewall.tmh" namespace firewall { namespace { // // CreateWfpSession() // // Create dynamic WFP session that will be used for all filters etc. // NTSTATUS CreateWfpSession ( HANDLE *WfpSession ) { FWPM_SESSION0 sessionInfo = { 0 }; sessionInfo.flags = FWPM_SESSION_FLAG_DYNAMIC; const auto status = FwpmEngineOpen0(NULL, RPC_C_AUTHN_DEFAULT, NULL, &sessionInfo, WfpSession); if (!NT_SUCCESS(status)) { *WfpSession = 0; } return status; } NTSTATUS DestroyWfpSession ( HANDLE WfpSession ) { return FwpmEngineClose0(WfpSession); } // // ConfigureWfp() // // Register structural objects with WFP. // Essentially making everything ready for installing callouts and filters. // // "Tx" (in transaction) suffix means there is no clean-up in failure paths. // NTSTATUS ConfigureWfpTx ( HANDLE WfpSession, CONTEXT *Context ) { FWPM_PROVIDER0 provider = { 0 }; const auto ProviderName = L"Mullvad Split Tunnel"; const auto ProviderDescription = L"Manages filters and callouts that aid in implementing split tunneling"; provider.providerKey = ST_FW_PROVIDER_KEY; provider.displayData.name = const_cast<wchar_t*>(ProviderName); provider.displayData.description = const_cast<wchar_t*>(ProviderDescription); auto status = FwpmProviderAdd0(WfpSession, &provider, NULL); if (!NT_SUCCESS(status)) { return status; } FWPM_PROVIDER_CONTEXT1 pc = { 0 }; const auto ProviderContextName = L"Mullvad Split Tunnel Provider Context"; const auto ProviderContextDescription = L"Exposes context data to callouts"; FWP_BYTE_BLOB blob = { .size = sizeof(CONTEXT*), .data = (UINT8*)&Context }; pc.providerContextKey = ST_FW_PROVIDER_CONTEXT_KEY; pc.displayData.name = const_cast<wchar_t*>(ProviderContextName); pc.displayData.description = const_cast<wchar_t*>(ProviderContextDescription); pc.providerKey = const_cast<GUID*>(&ST_FW_PROVIDER_KEY); pc.type = FWPM_GENERAL_CONTEXT; pc.dataBuffer = &blob; status = FwpmProviderContextAdd1(WfpSession, &pc, NULL, NULL); if (!NT_SUCCESS(status)) { return status; } // // Adding a specific sublayer for split tunneling is futile unless a hard permit // applied by the connect callout overrides filters registered by winfw // - which it won't. // // A hard permit applied by a callout doesn't seem to be respected at all. // // Using a plain filter with no callout, it's possible to sometimes make // a hard permit override a lower-weighted block, but it's not entirely consistent. // // And even then, it's not applicable to what we're doing since the logic // applied here cannot be expressed using a plain filter. // return STATUS_SUCCESS; } NTSTATUS UnregisterCallouts ( ) { auto s1 = UnregisterCalloutBlockSplitApps(); auto s2 = UnregisterCalloutPermitSplitApps(); auto s3 = UnregisterCalloutClassifyConnect(); auto s4 = UnregisterCalloutClassifyBind(); if (!NT_SUCCESS(s1)) { DbgPrint("Could not unregister block-split-apps callout\n"); return s1; } if (!NT_SUCCESS(s2)) { DbgPrint("Could not unregister permit-split-apps callout\n"); return s2; } if (!NT_SUCCESS(s3)) { DbgPrint("Could not unregister connect-redirect callout\n"); return s3; } if (!NT_SUCCESS(s4)) { DbgPrint("Could not unregister bind-redirect callout\n"); return s4; } return STATUS_SUCCESS; } // // RegisterCallouts() // // The reason we need this function is because the called functions are individually // safe if called inside a transaction. // // But a successful call is not undone by destroying the transaction. // NTSTATUS RegisterCallouts ( PDEVICE_OBJECT DeviceObject, HANDLE WfpSession ) { auto status = RegisterCalloutClassifyBindTx(DeviceObject, WfpSession); if (!NT_SUCCESS(status)) { DbgPrint("Could not register bind-redirect callout\n"); return status; } status = RegisterCalloutClassifyConnectTx(DeviceObject, WfpSession); if (!NT_SUCCESS(status)) { DbgPrint("Could not register connect-redirect callout\n"); goto Unregister_callouts; } status = RegisterCalloutPermitSplitAppsTx(DeviceObject, WfpSession); if (!NT_SUCCESS(status)) { DbgPrint("Could not register permit-split-apps callout\n"); goto Unregister_callouts; } status = RegisterCalloutBlockSplitAppsTx(DeviceObject, WfpSession); if (!NT_SUCCESS(status)) { DbgPrint("Could not register block-split-apps callout\n"); goto Unregister_callouts; } return STATUS_SUCCESS; Unregister_callouts: const auto s2 = UnregisterCallouts(); if (!NT_SUCCESS(s2)) { DbgPrint("One or more callouts could not be unregistered: 0x%X\n", s2); } return status; } PROCESS_SPLIT_VERDICT NTAPI DummyQueryProcessFunc ( HANDLE ProcessId, void *Context ) { UNREFERENCED_PARAMETER(ProcessId); UNREFERENCED_PARAMETER(Context); return PROCESS_SPLIT_VERDICT::DONT_SPLIT; } // // ResetClientCallbacks() // // This function is used if callouts/filters can't be unregistered. // // It's assumed that the driver was tearing down all subsystems in preparation // for unloading. // // Other parts of the driver may no longer be available so we have to prevent // callouts from accessing these parts through previously registered callbacks. // void ResetClientCallbacks ( CONTEXT *Context ) { Context->Callbacks.QueryProcess = DummyQueryProcessFunc; Context->Callbacks.Context = NULL; } NTSTATUS WfpTransactionBegin ( CONTEXT *Context ) { auto status = FwpmTransactionBegin0(Context->WfpSession, 0); if (!NT_SUCCESS(status)) { DbgPrint("Could not create WFP transaction: 0x%X\n", status); DECLARE_CONST_UNICODE_STRING(errorMessage, L"Could not create WFP transaction"); auto evt = eventing::BuildErrorMessageEvent(status, &errorMessage); eventing::Emit(Context->Eventing, &evt); } return status; } NTSTATUS WfpTransactionCommit ( CONTEXT *Context ) { auto status = FwpmTransactionCommit0(Context->WfpSession); if (!NT_SUCCESS(status)) { DbgPrint("Could not commit WFP transaction: 0x%X\n", status); DECLARE_CONST_UNICODE_STRING(errorMessage, L"Could not commit WFP transaction"); auto evt = eventing::BuildErrorMessageEvent(status, &errorMessage); eventing::Emit(Context->Eventing, &evt); } return status; } NTSTATUS WfpTransactionAbort ( CONTEXT *Context ) { auto status = FwpmTransactionAbort0(Context->WfpSession); if (!NT_SUCCESS(status)) { DbgPrint("Could not abort WFP transaction: 0x%X\n", status); DECLARE_CONST_UNICODE_STRING(errorMessage, L"Could not abort WFP transaction"); auto evt = eventing::BuildErrorMessageEvent(status, &errorMessage); eventing::Emit(Context->Eventing, &evt); } return status; } void ResetStructure ( ACTIVE_FILTERS *ActiveFilters ) { ActiveFilters->BindRedirectIpv4 = false; ActiveFilters->BindRedirectIpv6 = false; ActiveFilters->ConnectRedirectIpv4 = false; ActiveFilters->ConnectRedirectIpv6 = false; ActiveFilters->BlockTunnelIpv4 = false; ActiveFilters->BlockTunnelIpv6 = false; ActiveFilters->PermitNonTunnelIpv4 = false; ActiveFilters->PermitNonTunnelIpv6 = false; } // // RegisterFiltersForModeTx() // // Register filters according to mode. // Assumes no filters are installed to begin with. // // Will update ActiveFilters. // NTSTATUS RegisterFiltersForModeTx ( HANDLE WfpSession, SPLITTING_MODE Mode, const ST_IP_ADDRESSES *IpAddresses, ACTIVE_FILTERS *ActiveFilters ) { #define RFFM_SUCCEED_OR_RETURN(status, record) if(NT_SUCCESS(status)){ *record = true; } else { return status; } ResetStructure(ActiveFilters); switch (Mode) { case SPLITTING_MODE::MODE_1: { RFFM_SUCCEED_OR_RETURN ( RegisterFilterBindRedirectIpv4Tx(WfpSession), &ActiveFilters->BindRedirectIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterConnectRedirectIpv4Tx(WfpSession), &ActiveFilters->ConnectRedirectIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterPermitNonTunnelIpv4Tx(WfpSession, &IpAddresses->TunnelIpv4), &ActiveFilters->PermitNonTunnelIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterBlockTunnelIpv4Tx(WfpSession, &IpAddresses->TunnelIpv4), &ActiveFilters->BlockTunnelIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterBindRedirectIpv6Tx(WfpSession), &ActiveFilters->BindRedirectIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterConnectRedirectIpv6Tx(WfpSession), &ActiveFilters->ConnectRedirectIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterPermitNonTunnelIpv6Tx(WfpSession, &IpAddresses->TunnelIpv6), &ActiveFilters->PermitNonTunnelIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterBlockTunnelIpv6Tx(WfpSession, &IpAddresses->TunnelIpv6), &ActiveFilters->BlockTunnelIpv6 ); return STATUS_SUCCESS; } case SPLITTING_MODE::MODE_2: { RFFM_SUCCEED_OR_RETURN ( RegisterFilterBindRedirectIpv4Tx(WfpSession), &ActiveFilters->BindRedirectIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterConnectRedirectIpv4Tx(WfpSession), &ActiveFilters->ConnectRedirectIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterPermitNonTunnelIpv4Tx(WfpSession, &IpAddresses->TunnelIpv4), &ActiveFilters->PermitNonTunnelIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterBlockTunnelIpv4Tx(WfpSession, &IpAddresses->TunnelIpv4), &ActiveFilters->BlockTunnelIpv4 ); return STATUS_SUCCESS; } case SPLITTING_MODE::MODE_3: { RFFM_SUCCEED_OR_RETURN ( RegisterFilterBindRedirectIpv4Tx(WfpSession), &ActiveFilters->BindRedirectIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterConnectRedirectIpv4Tx(WfpSession), &ActiveFilters->ConnectRedirectIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterPermitNonTunnelIpv4Tx(WfpSession, &IpAddresses->TunnelIpv4), &ActiveFilters->PermitNonTunnelIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterBlockTunnelIpv4Tx(WfpSession, &IpAddresses->TunnelIpv4), &ActiveFilters->BlockTunnelIpv4 ); // // Pass NULL for tunnel IP since Mode-3 doesn't have a tunnel IPv6 interface. // RFFM_SUCCEED_OR_RETURN ( RegisterFilterPermitNonTunnelIpv6Tx(WfpSession, NULL), &ActiveFilters->PermitNonTunnelIpv6 ); return STATUS_SUCCESS; } case SPLITTING_MODE::MODE_4: { RFFM_SUCCEED_OR_RETURN ( RegisterFilterBindRedirectIpv4Tx(WfpSession), &ActiveFilters->BindRedirectIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterConnectRedirectIpv4Tx(WfpSession), &ActiveFilters->ConnectRedirectIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterPermitNonTunnelIpv4Tx(WfpSession, &IpAddresses->TunnelIpv4), &ActiveFilters->PermitNonTunnelIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterBlockTunnelIpv4Tx(WfpSession, &IpAddresses->TunnelIpv4), &ActiveFilters->BlockTunnelIpv4 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterBlockTunnelIpv6Tx(WfpSession, &IpAddresses->TunnelIpv6), &ActiveFilters->BlockTunnelIpv6 ); return STATUS_SUCCESS; } case SPLITTING_MODE::MODE_5: { RFFM_SUCCEED_OR_RETURN ( RegisterFilterBindRedirectIpv6Tx(WfpSession), &ActiveFilters->BindRedirectIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterConnectRedirectIpv6Tx(WfpSession), &ActiveFilters->ConnectRedirectIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterPermitNonTunnelIpv6Tx(WfpSession, &IpAddresses->TunnelIpv6), &ActiveFilters->PermitNonTunnelIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterBlockTunnelIpv6Tx(WfpSession, &IpAddresses->TunnelIpv6), &ActiveFilters->BlockTunnelIpv6 ); return STATUS_SUCCESS; } case SPLITTING_MODE::MODE_6: { RFFM_SUCCEED_OR_RETURN ( RegisterFilterBindRedirectIpv6Tx(WfpSession), &ActiveFilters->BindRedirectIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterConnectRedirectIpv6Tx(WfpSession), &ActiveFilters->ConnectRedirectIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterPermitNonTunnelIpv6Tx(WfpSession, &IpAddresses->TunnelIpv6), &ActiveFilters->PermitNonTunnelIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterBlockTunnelIpv6Tx(WfpSession, &IpAddresses->TunnelIpv6), &ActiveFilters->BlockTunnelIpv6 ); // // Pass NULL for tunnel IP since Mode-6 doesn't have a tunnel IPv4 interface. // RFFM_SUCCEED_OR_RETURN ( RegisterFilterPermitNonTunnelIpv4Tx(WfpSession, NULL), &ActiveFilters->PermitNonTunnelIpv4 ); return STATUS_SUCCESS; } case SPLITTING_MODE::MODE_7: { RFFM_SUCCEED_OR_RETURN ( RegisterFilterBindRedirectIpv6Tx(WfpSession), &ActiveFilters->BindRedirectIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterConnectRedirectIpv6Tx(WfpSession), &ActiveFilters->ConnectRedirectIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterPermitNonTunnelIpv6Tx(WfpSession, &IpAddresses->TunnelIpv6), &ActiveFilters->PermitNonTunnelIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterBlockTunnelIpv6Tx(WfpSession, &IpAddresses->TunnelIpv6), &ActiveFilters->BlockTunnelIpv6 ); RFFM_SUCCEED_OR_RETURN ( RegisterFilterBlockTunnelIpv4Tx(WfpSession, &IpAddresses->TunnelIpv4), &ActiveFilters->BlockTunnelIpv4 ); return STATUS_SUCCESS; } case SPLITTING_MODE::MODE_8: { RFFM_SUCCEED_OR_RETURN ( RegisterFilterBlockTunnelIpv4Tx(WfpSession, &IpAddresses->TunnelIpv4), &ActiveFilters->BlockTunnelIpv4 ); // // Pass NULL for tunnel IP since Mode-8 doesn't have a tunnel IPv6 interface. // RFFM_SUCCEED_OR_RETURN ( RegisterFilterPermitNonTunnelIpv6Tx(WfpSession, NULL), &ActiveFilters->PermitNonTunnelIpv6 ); return STATUS_SUCCESS; } case SPLITTING_MODE::MODE_9: { RFFM_SUCCEED_OR_RETURN ( RegisterFilterBlockTunnelIpv6Tx(WfpSession, &IpAddresses->TunnelIpv6), &ActiveFilters->BlockTunnelIpv6 ); // // Pass NULL for tunnel IP since Mode-9 doesn't have a tunnel IPv4 interface. // RFFM_SUCCEED_OR_RETURN ( RegisterFilterPermitNonTunnelIpv4Tx(WfpSession, NULL), &ActiveFilters->PermitNonTunnelIpv4 ); return STATUS_SUCCESS; } }; DbgPrint("Non-actionable SPLITTING_MODE argument\n"); return STATUS_UNSUCCESSFUL; } NTSTATUS RemoveActiveFiltersTx ( HANDLE WfpSession, const ACTIVE_FILTERS *ActiveFilters ) { #define RAF_SUCCEED_OR_RETURN(status) if(!NT_SUCCESS(status)){ return status; } if (ActiveFilters->BindRedirectIpv4) { RAF_SUCCEED_OR_RETURN ( RemoveFilterBindRedirectIpv4Tx(WfpSession) ); } if (ActiveFilters->BindRedirectIpv6) { RAF_SUCCEED_OR_RETURN ( RemoveFilterBindRedirectIpv6Tx(WfpSession) ); } if (ActiveFilters->ConnectRedirectIpv4) { RAF_SUCCEED_OR_RETURN ( RemoveFilterConnectRedirectIpv4Tx(WfpSession) ); } if (ActiveFilters->ConnectRedirectIpv6) { RAF_SUCCEED_OR_RETURN ( RemoveFilterConnectRedirectIpv6Tx(WfpSession) ); } if (ActiveFilters->BlockTunnelIpv4) { RAF_SUCCEED_OR_RETURN ( RemoveFilterBlockTunnelIpv4Tx(WfpSession) ); } if (ActiveFilters->BlockTunnelIpv6) { RAF_SUCCEED_OR_RETURN ( RemoveFilterBlockTunnelIpv6Tx(WfpSession) ); } if (ActiveFilters->PermitNonTunnelIpv4) { RAF_SUCCEED_OR_RETURN ( RemoveFilterPermitNonTunnelIpv4Tx(WfpSession) ); } if (ActiveFilters->PermitNonTunnelIpv6) { RAF_SUCCEED_OR_RETURN ( RemoveFilterPermitNonTunnelIpv6Tx(WfpSession) ); } return STATUS_SUCCESS; } struct TUNNEL_ADDRESS_POINTERS { const IN_ADDR *TunnelIpv4; const IN6_ADDR *TunnelIpv6; }; // // SelectTunnelAddresses() // // Select addresses based on mode. Both addresses are not valid in all modes. // NTSTATUS SelectTunnelAddresses ( const ST_IP_ADDRESSES *IpAddresses, SPLITTING_MODE SplittingMode, TUNNEL_ADDRESS_POINTERS *AddressPointers ) { AddressPointers->TunnelIpv4 = NULL; AddressPointers->TunnelIpv6 = NULL; switch (SplittingMode) { case SPLITTING_MODE::MODE_1: case SPLITTING_MODE::MODE_4: case SPLITTING_MODE::MODE_7: { AddressPointers->TunnelIpv4 = &IpAddresses->TunnelIpv4; AddressPointers->TunnelIpv6 = &IpAddresses->TunnelIpv6; return STATUS_SUCCESS; } case SPLITTING_MODE::MODE_2: case SPLITTING_MODE::MODE_3: case SPLITTING_MODE::MODE_8: { AddressPointers->TunnelIpv4 = &IpAddresses->TunnelIpv4; return STATUS_SUCCESS; } case SPLITTING_MODE::MODE_5: case SPLITTING_MODE::MODE_6: case SPLITTING_MODE::MODE_9: { AddressPointers->TunnelIpv6 = &IpAddresses->TunnelIpv6; return STATUS_SUCCESS; } }; DbgPrint("Non-actionable SPLITTING_MODE argument\n"); return STATUS_UNSUCCESSFUL; } struct ALE_REAUTHORIZATION_FILTER_IDS { UINT64 OutboundFilterIdV4; UINT64 InboundFilterIdV4; UINT64 OutboundFilterIdV6; UINT64 InboundFilterIdV6; }; // // AddAleReauthorizationFiltersTx() // // Add dummy filters to trigger an ALE reauthorization in the following layers: // // FWPM_LAYER_ALE_AUTH_CONNECT_V4 // FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4 // FWPM_LAYER_ALE_AUTH_CONNECT_V6 // FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6 // NTSTATUS AddAleReauthorizationFiltersTx ( HANDLE WfpSession, ALE_REAUTHORIZATION_FILTER_IDS *ReauthFilters ) { RtlZeroMemory(ReauthFilters, sizeof(*ReauthFilters)); // // Add IPv4 outbound filter. // // The single condition for IPv4 layers is: // // REMOTE_ADDRESS == 1.3.3.7 // FWPM_FILTER0 filter = { 0 }; const auto FilterName = L"Mullvad Split Tunnel ALE reauthorization filter"; const auto FilterDescription = L"Forces an ALE reauthorization to occur"; filter.displayData.name = const_cast<wchar_t*>(FilterName); filter.displayData.description = const_cast<wchar_t*>(FilterDescription); filter.providerKey = const_cast<GUID*>(&ST_FW_PROVIDER_KEY); filter.layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V4; filter.subLayerKey = ST_FW_WINFW_BASELINE_SUBLAYER_KEY; filter.weight.type = FWP_UINT64; filter.weight.uint64 = const_cast<UINT64*>(&ST_MAX_FILTER_WEIGHT); filter.action.type = FWP_ACTION_BLOCK; FWPM_FILTER_CONDITION0 cond; cond.fieldKey = FWPM_CONDITION_IP_REMOTE_ADDRESS; cond.matchType = FWP_MATCH_EQUAL; cond.conditionValue.type = FWP_UINT32; cond.conditionValue.uint32 = 0x01030307; filter.filterCondition = &cond; filter.numFilterConditions = 1; auto status = FwpmFilterAdd0(WfpSession, &filter, NULL, &ReauthFilters->OutboundFilterIdV4); if (!NT_SUCCESS(status)) { return status; } // // Add IPv4 inbound filter. // RtlZeroMemory(&filter.filterKey, sizeof(filter.filterKey)); filter.layerKey = FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4; status = FwpmFilterAdd0(WfpSession, &filter, NULL, &ReauthFilters->InboundFilterIdV4); if (!NT_SUCCESS(status)) { return status; } // // Add IPv6 outbound filter. // // The single condition for IPv6 layers is the same as for IPv4 layers, // but the address is encoded as an IPv6 address. // RtlZeroMemory(&filter.filterKey, sizeof(filter.filterKey)); filter.layerKey = FWPM_LAYER_ALE_AUTH_CONNECT_V6; const FWP_BYTE_ARRAY16 ipv6RemoteAddress = { .byteArray16 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 1, 3, 3, 7 } }; cond.conditionValue.type = FWP_BYTE_ARRAY16_TYPE; cond.conditionValue.byteArray16 = const_cast<FWP_BYTE_ARRAY16*>(&ipv6RemoteAddress); status = FwpmFilterAdd0(WfpSession, &filter, NULL, &ReauthFilters->OutboundFilterIdV6); if (!NT_SUCCESS(status)) { return status; } // // Add IPv6 inbound filter. // RtlZeroMemory(&filter.filterKey, sizeof(filter.filterKey)); filter.layerKey = FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6; return FwpmFilterAdd0(WfpSession, &filter, NULL, &ReauthFilters->InboundFilterIdV6); } NTSTATUS RemoveAleReauthorizationFilters ( CONTEXT *Context, ALE_REAUTHORIZATION_FILTER_IDS *ReauthFilters ) { auto status = WfpTransactionBegin(Context); if (!NT_SUCCESS(status)) { return status; } if (!NT_SUCCESS(status = FwpmFilterDeleteById0(Context->WfpSession, ReauthFilters->OutboundFilterIdV4)) || !NT_SUCCESS(status = FwpmFilterDeleteById0(Context->WfpSession, ReauthFilters->InboundFilterIdV4)) || !NT_SUCCESS(status = FwpmFilterDeleteById0(Context->WfpSession, ReauthFilters->OutboundFilterIdV6)) || !NT_SUCCESS(status = FwpmFilterDeleteById0(Context->WfpSession, ReauthFilters->InboundFilterIdV6))) { goto Abort; } status = WfpTransactionCommit(Context); if (!NT_SUCCESS(status)) { goto Abort; } return STATUS_SUCCESS; Abort: WfpTransactionAbort(Context); return status; } } // anonymous namespace // // Initialize() // // Initialize data structures and locks etc. // // Configure WFP. // // We don't actually need a transaction here, if there are any failures // we destroy the entire WFP session, which resets everything. // NTSTATUS Initialize ( CONTEXT **Context, PDEVICE_OBJECT DeviceObject, const CALLBACKS *Callbacks, procbroker::CONTEXT *ProcessEventBroker, eventing::CONTEXT *Eventing ) { auto context = (CONTEXT*)ExAllocatePoolUninitialized(NonPagedPool, sizeof(CONTEXT), ST_POOL_TAG); if (context == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } RtlZeroMemory(context, sizeof(*context)); context->Callbacks = *Callbacks; context->Eventing = Eventing; auto status = WdfSpinLockCreate(WDF_NO_OBJECT_ATTRIBUTES, &context->IpAddresses.Lock); if (!NT_SUCCESS(status)) { DbgPrint("WdfSpinLockCreate() failed 0x%X\n", status); context->IpAddresses.Lock = NULL; goto Abort; } status = WdfWaitLockCreate(WDF_NO_OBJECT_ATTRIBUTES, &context->Transaction.Lock); if (!NT_SUCCESS(status)) { DbgPrint("WdfWaitLockCreate() failed 0x%X\n", status); context->Transaction.Lock = NULL; goto Abort_delete_ip_lock; } status = pending::Initialize ( &context->PendedClassifications, ProcessEventBroker ); if (!NT_SUCCESS(status)) { DbgPrint("pending::Initialize failed 0x%X\n", status); context->PendedClassifications = NULL; goto Abort_delete_transaction_lock; } status = CreateWfpSession(&context->WfpSession); if (!NT_SUCCESS(status)) { context->WfpSession = NULL; goto Abort_teardown_pending; } status = ConfigureWfpTx(context->WfpSession, context); if (!NT_SUCCESS(status)) { goto Abort_destroy_session; } status = RegisterCallouts(DeviceObject, context->WfpSession); if (!NT_SUCCESS(status)) { goto Abort_destroy_session; } status = appfilters::Initialize(context->WfpSession, &context->AppFiltersContext); if (!NT_SUCCESS(status)) { goto Abort_unregister_callouts; } *Context = context; return STATUS_SUCCESS; Abort_unregister_callouts: { const auto s2 = UnregisterCallouts(); if (!NT_SUCCESS(s2)) { DbgPrint("One or more callouts could not be unregistered: 0x%X\n", s2); } } Abort_destroy_session: DestroyWfpSession(context->WfpSession); Abort_teardown_pending: pending::TearDown(&context->PendedClassifications); Abort_delete_transaction_lock: WdfObjectDelete(context->Transaction.Lock); Abort_delete_ip_lock: WdfObjectDelete(context->IpAddresses.Lock); Abort: ExFreePoolWithTag(context, ST_POOL_TAG); *Context = NULL; return status; } // // TearDown() // // Destroy WFP session along with all filters. // Release resources. // // If the return value is not successful, it means the following: // // The context used by callouts has been updated to make callouts return early, // thereby avoiding crashes. // // The callouts are still registered with the system so the driver cannot be unloaded. // NTSTATUS TearDown ( CONTEXT **Context ) { const bool preConditions = ( (Context != NULL) && (*Context != NULL) && ((*Context)->SplittingEnabled == false) ); NT_ASSERT(preConditions); if (!preConditions) { return STATUS_INVALID_DISPOSITION; } auto context = *Context; *Context = NULL; // // Clean up adjacent systems. // pending::TearDown(&context->PendedClassifications); appfilters::TearDown(&context->AppFiltersContext); // // Since we're using a dynamic session we don't actually // have to remove all WFP objects one by one. // // Everything will be cleaned up when the session is ended. // // (Except for callout registrations.) // auto status = DestroyWfpSession(context->WfpSession); if (!NT_SUCCESS(status)) { DbgPrint("WFP session could not be cleaned up: 0x%X\n", status); ResetClientCallbacks(context); // Leak context structure. return status; } status = UnregisterCallouts(); if (!NT_SUCCESS(status)) { DbgPrint("One or more callouts could not be unregistered: 0x%X\n", status); ResetClientCallbacks(context); // Leak context structure. return status; } WdfObjectDelete(context->IpAddresses.Lock); WdfObjectDelete(context->Transaction.Lock); ExFreePoolWithTag(context, ST_POOL_TAG); return STATUS_SUCCESS; } // // EnableSplitting() // // Register all filters required for splitting. // NTSTATUS EnableSplitting ( CONTEXT *Context, const ST_IP_ADDRESSES *IpAddresses ) { NT_ASSERT(!Context->SplittingEnabled); NT_ASSERT(!Context->Transaction.Active); if (Context->SplittingEnabled || Context->Transaction.Active) { return STATUS_UNSUCCESSFUL; } // // There are no readers at this time so we can update at leasure and without // taking the lock. // // IP addresses and mode should be updated before filters are committed. // Context->IpAddresses.Addresses = *IpAddresses; auto status = DetermineSplittingMode ( &Context->IpAddresses.Addresses, &Context->IpAddresses.SplittingMode ); if (!NT_SUCCESS(status)) { return status; } // // Update WFP inside a transaction. // status = WfpTransactionBegin(Context); if (!NT_SUCCESS(status)) { return status; } // // There are no filters installed at this time. // Just go ahead and install the required filters. // ACTIVE_FILTERS activeFilters; status = RegisterFiltersForModeTx ( Context->WfpSession, Context->IpAddresses.SplittingMode, &Context->IpAddresses.Addresses, &activeFilters ); if (!NT_SUCCESS(status)) { goto Abort; } // // Commit filters. // status = WfpTransactionCommit(Context); if (!NT_SUCCESS(status)) { goto Abort; } Context->SplittingEnabled = true; Context->ActiveFilters = activeFilters; LogActivatedSplittingMode(Context->IpAddresses.SplittingMode); return STATUS_SUCCESS; Abort: WfpTransactionAbort(Context); return status; } // // DisableSplitting() // // Remove all filters associated with splitting. // NTSTATUS DisableSplitting ( CONTEXT *Context ) { NT_ASSERT(Context->SplittingEnabled); if (!Context->SplittingEnabled) { return STATUS_UNSUCCESSFUL; } // // Use double transaction because resetting appfilters requires this. // auto status = TransactionBegin(Context); if (!NT_SUCCESS(status)) { return status; } status = RemoveActiveFiltersTx(Context->WfpSession, &Context->ActiveFilters); if (!NT_SUCCESS(status)) { goto Abort; } status = appfilters::ResetTx2(Context->AppFiltersContext); if (!NT_SUCCESS(status)) { goto Abort; } status = TransactionCommit(Context); if (!NT_SUCCESS(status)) { goto Abort; } Context->SplittingEnabled = false; ResetStructure(&Context->ActiveFilters); return STATUS_SUCCESS; Abort: TransactionAbort(Context); return status; } NTSTATUS RegisterUpdatedIpAddresses ( CONTEXT *Context, const ST_IP_ADDRESSES *IpAddresses ) { if (!Context->SplittingEnabled) { return STATUS_SUCCESS; } // // Determine which mode we're entering into. // SPLITTING_MODE newMode; auto status = DetermineSplittingMode(IpAddresses, &newMode); if (!NT_SUCCESS(status)) { return status; } // // Use a double transaction // // Remove all generic filters, and add back still relevant ones // status = TransactionBegin(Context); if (!NT_SUCCESS(status)) { return status; } status = RemoveActiveFiltersTx(Context->WfpSession, &Context->ActiveFilters); if (!NT_SUCCESS(status)) { goto Abort; } ACTIVE_FILTERS newActiveFilters; status = RegisterFiltersForModeTx ( Context->WfpSession, newMode, IpAddresses, &newActiveFilters ); if (!NT_SUCCESS(status)) { goto Abort; } // // Update any app-specific filters. // TUNNEL_ADDRESS_POINTERS addressPointers; status = SelectTunnelAddresses(IpAddresses, newMode, &addressPointers); if (!NT_SUCCESS(status)) { goto Abort; } status = appfilters::UpdateFiltersTx2 ( Context->AppFiltersContext, addressPointers.TunnelIpv4, addressPointers.TunnelIpv6 ); if (!NT_SUCCESS(status)) { goto Abort; } // // Finalize. // status = TransactionCommit(Context); if (!NT_SUCCESS(status)) { goto Abort; } auto intermediateNonPagedAddresses = *IpAddresses; WdfSpinLockAcquire(Context->IpAddresses.Lock); Context->IpAddresses.Addresses = intermediateNonPagedAddresses; Context->IpAddresses.SplittingMode = newMode; WdfSpinLockRelease(Context->IpAddresses.Lock); Context->ActiveFilters = newActiveFilters; LogActivatedSplittingMode(newMode); return STATUS_SUCCESS; Abort: TransactionAbort(Context); return status; } NTSTATUS TransactionBegin ( CONTEXT *Context ) { NT_ASSERT(Context->SplittingEnabled); if (!Context->SplittingEnabled) { return STATUS_UNSUCCESSFUL; } WdfWaitLockAcquire(Context->Transaction.Lock, NULL); auto status = WfpTransactionBegin(Context); if (!NT_SUCCESS(status)) { goto Abort; } status = appfilters::TransactionBegin(Context->AppFiltersContext); if (!NT_SUCCESS(status)) { DbgPrint("Could not create appfilters transaction: 0x%X\n", status); goto Abort_cancel_wfp; } Context->Transaction.OwnerId = PsGetCurrentThreadId(); Context->Transaction.Active = true; return STATUS_SUCCESS; Abort_cancel_wfp: WfpTransactionAbort(Context); Abort: WdfWaitLockRelease(Context->Transaction.Lock); return status; } NTSTATUS TransactionCommit ( CONTEXT *Context, bool ForceAleReauthorization ) { NT_ASSERT(Context->SplittingEnabled); NT_ASSERT(Context->Transaction.Active); if (!Context->SplittingEnabled || !Context->Transaction.Active) { DbgPrint(__FUNCTION__ " called outside transaction\n"); return STATUS_UNSUCCESSFUL; } if (Context->Transaction.OwnerId != PsGetCurrentThreadId()) { DbgPrint(__FUNCTION__ " called by other than transaction owner\n"); return STATUS_UNSUCCESSFUL; } ALE_REAUTHORIZATION_FILTER_IDS reauthFilters; if (ForceAleReauthorization) { auto status = AddAleReauthorizationFiltersTx(Context->WfpSession, &reauthFilters); if (!NT_SUCCESS(status)) { DbgPrint("Could not add ALE reauthorization filters\n"); return status; } } auto status = WfpTransactionCommit(Context); if (!NT_SUCCESS(status)) { return status; } appfilters::TransactionCommit(Context->AppFiltersContext); Context->Transaction.OwnerId = NULL; Context->Transaction.Active = false; if (ForceAleReauthorization) { status = RemoveAleReauthorizationFilters(Context, &reauthFilters); if (!NT_SUCCESS(status)) { // // This is bad to the extent that we were unable to remove filters which no longer // serve a purpose. // // However, the filters aren't using unique GUIDs as identifiers, and they're using // dummy conditions that won't match any traffic. // // So filters will merely be wasting a tiny amount of system resources. // DbgPrint("Could not remove ALE reauthorization filters: 0x%X\n", status); DECLARE_CONST_UNICODE_STRING(errorMessage, L"Could not remove ALE reauthorization filters"); auto evt = eventing::BuildErrorMessageEvent(status, &errorMessage); eventing::Emit(Context->Eventing, &evt); } } WdfWaitLockRelease(Context->Transaction.Lock); return STATUS_SUCCESS; } NTSTATUS TransactionAbort ( CONTEXT *Context ) { NT_ASSERT(Context->SplittingEnabled); NT_ASSERT(Context->Transaction.Active); if (!Context->SplittingEnabled || !Context->Transaction.Active) { DbgPrint(__FUNCTION__ " called outside transaction\n"); return STATUS_UNSUCCESSFUL; } if (Context->Transaction.OwnerId != PsGetCurrentThreadId()) { DbgPrint(__FUNCTION__ " called by other than transaction owner\n"); return STATUS_UNSUCCESSFUL; } auto status = WfpTransactionAbort(Context); if (!NT_SUCCESS(status)) { return status; } appfilters::TransactionAbort(Context->AppFiltersContext); Context->Transaction.OwnerId = NULL; Context->Transaction.Active = false; WdfWaitLockRelease(Context->Transaction.Lock); return STATUS_SUCCESS; } NTSTATUS RegisterAppBecomingSplitTx ( CONTEXT *Context, const LOWER_UNICODE_STRING *ImageName ) { NT_ASSERT(Context->SplittingEnabled); NT_ASSERT(Context->Transaction.Active); if (!Context->SplittingEnabled || !Context->Transaction.Active) { return STATUS_UNSUCCESSFUL; } if (Context->Transaction.OwnerId != PsGetCurrentThreadId()) { DbgPrint(__FUNCTION__ " called by other than transaction owner\n"); return STATUS_UNSUCCESSFUL; } // // We're in a transaction so IP addresses won't be updated on another thread. // TUNNEL_ADDRESS_POINTERS addressPointers; auto status = SelectTunnelAddresses ( &Context->IpAddresses.Addresses, Context->IpAddresses.SplittingMode, &addressPointers ); if (!NT_SUCCESS(status)) { return status; } return appfilters::RegisterFilterBlockAppTunnelTrafficTx2 ( Context->AppFiltersContext, ImageName, addressPointers.TunnelIpv4, addressPointers.TunnelIpv6 ); } NTSTATUS RegisterAppBecomingUnsplitTx ( CONTEXT *Context, const LOWER_UNICODE_STRING *ImageName ) { NT_ASSERT(Context->SplittingEnabled); NT_ASSERT(Context->Transaction.Active); if (!Context->SplittingEnabled || !Context->Transaction.Active) { return STATUS_UNSUCCESSFUL; } if (Context->Transaction.OwnerId != PsGetCurrentThreadId()) { DbgPrint(__FUNCTION__ " called by other than transaction owner\n"); return STATUS_UNSUCCESSFUL; } return appfilters::RemoveFilterBlockAppTunnelTrafficTx2(Context->AppFiltersContext, ImageName); } } // namespace firewall
34,154
C++
.cpp
1,332
22.953453
120
0.765424
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,044
classify.cpp
mullvad_win-split-tunnel/src/firewall/classify.cpp
#include "classify.h" namespace firewall { void ClassificationReset ( FWPS_CLASSIFY_OUT0 *ClassifyOut ) { // // According to documentation, FwpsAcquireWritableLayerDataPointer0() will update the // `actionType` and `rights` fields with poorly chosen values: // // ``` // classifyOut->actionType = FWP_ACTION_BLOCK // classifyOut->rights &= ~FWPS_RIGHT_ACTION_WRITE // ``` // // However, in practice it seems to not make any changes to those fields. // But if it did we'd want to ensure the fields have sane values. // ClassifyOut->actionType = FWP_ACTION_CONTINUE; ClassifyOut->rights |= FWPS_RIGHT_ACTION_WRITE; } void ClassificationApplyHardPermit ( FWPS_CLASSIFY_OUT0 *ClassifyOut ) { ClassifyOut->actionType = FWP_ACTION_PERMIT; ClassifyOut->rights &= ~FWPS_RIGHT_ACTION_WRITE; } void ClassificationApplySoftPermit ( FWPS_CLASSIFY_OUT0 *ClassifyOut ) { ClassifyOut->actionType = FWP_ACTION_PERMIT; ClassifyOut->rights |= FWPS_RIGHT_ACTION_WRITE; } void ClassificationApplyHardBlock ( FWPS_CLASSIFY_OUT0 *ClassifyOut ) { ClassifyOut->actionType = FWP_ACTION_BLOCK; ClassifyOut->rights &= ~FWPS_RIGHT_ACTION_WRITE; } } // namespace firewall
1,174
C++
.cpp
52
20.980769
86
0.778475
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,045
util.h
mullvad_win-split-tunnel/leaktest/util.h
#pragma once #include <vector> #include <string> #include <stdexcept> #include <filesystem> #include <optional> #include <ws2tcpip.h> #include <ws2ipdef.h> #include <windows.h> class ArgumentContext { public: ArgumentContext(const std::vector<std::wstring> &args) : m_args(args) , m_remaining(m_args.size()) { } size_t total() const { return m_args.size(); } void ensureExactArgumentCount(size_t count) const { if (m_args.size() != count) { throw std::runtime_error("Invalid number of arguments"); } } const std::wstring &next() { if (0 == m_remaining) { throw std::runtime_error("Argument missing"); } const auto &str = m_args.at(m_args.size() - m_remaining); --m_remaining; return str; } std::wstring nextOrDefault(const std::wstring &def) { if (0 == m_remaining) { return def; } const auto &str = m_args.at(m_args.size() - m_remaining); --m_remaining; return str; } void assertExhausted() { if (0 != m_remaining) { throw std::runtime_error("Unknown extra argument(s)"); } } private: const std::vector<std::wstring> &m_args; size_t m_remaining; }; void PromptActivateVpnSplitTunnel(); void PromptActivateVpn(); void PromptActivateSplitTunnel(); void PromptDisableSplitTunnel(); // // // ProcessBinaryCreateRandomCopy() // // Copy process binary to temporary directory, using random file name. // std::filesystem::path ProcessBinaryCreateRandomCopy(); HANDLE LaunchProcess ( const std::filesystem::path &path, const std::vector<std::wstring> &args, DWORD creationFlags = 0, std::optional<LPPROC_THREAD_ATTRIBUTE_LIST> attributes = std::nullopt ); // // LaunchUnrelatedProcess() // // Launch new process as child of `explorer.exe` // HANDLE LaunchUnrelatedProcess ( const std::filesystem::path &path, const std::vector<std::wstring> &args, DWORD creationFlags = 0 ); HANDLE Fork(const std::vector<std::wstring> &args); void PrintGreen(const std::wstring &str); void PrintRed(const std::wstring &str); // // GetAdapterAddresses() // // Determine IPv4 and/or IPv6 addresses for adapter. // void GetAdapterAddresses(const std::wstring &adapterName, IN_ADDR *ipv4, IN6_ADDR *ipv6); std::wstring IpToString(const IN_ADDR &ip); IN_ADDR ParseIpv4(const std::wstring &ip); bool operator==(const IN_ADDR &lhs, const IN_ADDR &rhs); bool ProtoArgumentTcp(const std::wstring &argValue);
2,386
C++
.h
104
20.875
89
0.734902
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,046
runtimesettings.h
mullvad_win-split-tunnel/leaktest/runtimesettings.h
#pragma once // Include this to get IN6_ADDR // There's some magical include order which is non-trivial to reproduce #include <libcommon/network/adapters.h> #include "settings.h" #include <string> #include <cstdint> #include <optional> #include <filesystem> class RuntimeSettings { RuntimeSettings(Settings settings); public: static std::filesystem::path GetSettingsFilePath(); static void OverrideSettingsFilePath(const std::filesystem::path &path); static RuntimeSettings &Instance(); IN_ADDR tunnelIp(); IN6_ADDR tunnelIp6(); IN_ADDR lanIp(); IN6_ADDR lanIp6(); // // TODO: Start making use of this in combination with the tcpbin info service. // IN_ADDR publicNonVpnIp(); IN_ADDR tcpbinServerIp(); uint16_t tcpbinEchoPort(); uint16_t tcpbinEchoPortUdp(); uint16_t tcpbinInfoPort(); private: Settings m_settings; std::optional<IN_ADDR> m_tunnelIp; std::optional<IN6_ADDR> m_tunnelIp6; std::optional<IN_ADDR> m_lanIp; std::optional<IN6_ADDR> m_lanIp6; std::optional<IN_ADDR> m_publicNonVpnIp; std::optional<IN_ADDR> m_tcpbinServerIp; std::optional<uint16_t> m_tcpbinEchoPort; std::optional<uint16_t> m_tcpbinEchoPortUdp; std::optional<uint16_t> m_tcpbinInfoPort; };
1,210
C++
.h
40
28.2
79
0.778163
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,047
settings.h
mullvad_win-split-tunnel/leaktest/settings.h
#pragma once #include <filesystem> #include <string> #include <libcommon/string.h> using common::string::KeyValuePairs; class Settings { public: Settings(KeyValuePairs values) : m_values(std::move(values)) { } static Settings FromFile(const std::filesystem::path &filename); const std::wstring &get(const std::wstring &key); private: KeyValuePairs m_values; };
377
C++
.h
17
20.235294
65
0.778409
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,048
sockutil.h
mullvad_win-split-tunnel/leaktest/sockutil.h
#pragma once #include <cstdint> #include <string> #include <vector> #include <chrono> #include <ws2tcpip.h> std::string FormatWsaError(int errorCode); SOCKET CreateBindSocket(const IN_ADDR &ip, uint16_t port = 0, bool tcp = true); SOCKET CreateBindSocket(const std::wstring &ip, uint16_t port = 0, bool tcp = true); SOCKET CreateSocket(bool tcp = true); void ShutdownSocket(SOCKET &s); void ConnectSocket(SOCKET s, const IN_ADDR &ip, uint16_t port); void ConnectSocket(SOCKET s, const std::wstring &ip, uint16_t port); std::vector<uint8_t> SendRecvSocket(SOCKET s, const std::vector<uint8_t> &sendBuffer); void SendRecvValidateEcho(SOCKET s, const std::vector<uint8_t> &sendBuffer); sockaddr_in QueryBind(SOCKET s); void ValidateBind(SOCKET s, const IN_ADDR &ip); void SetSocketRecvTimeout(SOCKET s, std::chrono::milliseconds timeout); SOCKET CreateBindOverlappedSocket(const IN_ADDR &ip, uint16_t port = 0, bool tcp = true); SOCKET CreateBindOverlappedSocket(const std::wstring &ip, uint16_t port = 0, bool tcp = true); struct WinsockOverlapped { // // Overlapped instance with valid event. // WSAOVERLAPPED overlapped; // // Actual data buffer. // std::vector<uint8_t> buffer; // // Buffer descriptor. // WSABUF winsockBuffer; // // Whether there is an active send or receive. // bool pendingOperation; }; WinsockOverlapped *AllocateWinsockOverlapped(); void DeleteWinsockOverlapped(WinsockOverlapped **ctx); void AssignOverlappedBuffer(WinsockOverlapped &ctx, std::vector<uint8_t> &&buffer); void SendOverlappedSocket(SOCKET s, WinsockOverlapped &ctx); void RecvOverlappedSocket(SOCKET s, WinsockOverlapped &ctx, size_t bytes = 0); bool PollOverlappedSend(SOCKET s, WinsockOverlapped &ctx); bool PollOverlappedRecv(SOCKET s, WinsockOverlapped &ctx);
1,795
C++
.h
46
37.108696
94
0.782356
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,049
st3.h
mullvad_win-split-tunnel/leaktest/split-tunnel/st3.h
#pragma once #include <vector> #include <string> bool TestCaseSt3(const std::vector<std::wstring> &arguments);
113
C++
.h
4
26.75
61
0.785047
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,050
st7.h
mullvad_win-split-tunnel/leaktest/split-tunnel/st7.h
#pragma once #include <vector> #include <string> bool TestCaseSt7(const std::vector<std::wstring> &arguments); bool TestCaseSt7Child(const std::vector<std::wstring> &arguments);
180
C++
.h
5
34.6
66
0.791908
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,051
st4.h
mullvad_win-split-tunnel/leaktest/split-tunnel/st4.h
#pragma once #include <vector> #include <string> bool TestCaseSt4(const std::vector<std::wstring> &arguments);
113
C++
.h
4
26.75
61
0.785047
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,052
st5.h
mullvad_win-split-tunnel/leaktest/split-tunnel/st5.h
#pragma once #include <vector> #include <string> bool TestCaseSt5(const std::vector<std::wstring> &arguments); bool TestCaseSt5Child(const std::vector<std::wstring> &arguments);
180
C++
.h
5
34.6
66
0.791908
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,053
st1.h
mullvad_win-split-tunnel/leaktest/split-tunnel/st1.h
#pragma once #include <vector> #include <string> bool TestCaseSt1(const std::vector<std::wstring> &arguments);
113
C++
.h
4
26.75
61
0.785047
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,054
st6.h
mullvad_win-split-tunnel/leaktest/split-tunnel/st6.h
#pragma once #include <vector> #include <string> bool TestCaseSt6(const std::vector<std::wstring> &arguments); bool TestCaseSt6Server(const std::vector<std::wstring> &arguments); bool TestCaseSt6Client(const std::vector<std::wstring> &arguments);
249
C++
.h
6
40.166667
67
0.79668
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,055
st2.h
mullvad_win-split-tunnel/leaktest/split-tunnel/st2.h
#pragma once #include <vector> #include <string> bool TestCaseSt2(const std::vector<std::wstring> &arguments);
113
C++
.h
4
26.75
61
0.785047
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,056
gen1.h
mullvad_win-split-tunnel/leaktest/general/gen1.h
#pragma once #include <vector> #include <string> bool TestCaseGen1(const std::vector<std::wstring> &arguments);
114
C++
.h
4
27
62
0.787037
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,057
public.h
mullvad_win-split-tunnel/src/public.h
#pragma once #include "win64guard.h" #include "ipaddr.h" #include "defs/state.h" #include "defs/ioctl.h" #include "defs/config.h" #include "defs/process.h" #include "defs/queryprocess.h" #include "defs/events.h"
213
C++
.h
9
22.555556
30
0.763547
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,058
version.h
mullvad_win-split-tunnel/src/version.h
#pragma once #define DRIVER_VERSION_MAJOR 1 #define DRIVER_VERSION_MINOR 2 #define DRIVER_VERSION_PATCH 4 #define DRIVER_VERSION_BUILD 0
138
C++
.h
5
26.4
30
0.833333
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,059
validation.h
mullvad_win-split-tunnel/src/validation.h
#pragma once #include <wdm.h> // // ValidateUserBufferConfiguration() // // Validates configuration data sent by user mode. // bool ValidateUserBufferConfiguration ( void *Buffer, size_t BufferLength ); // // ValidateUserBufferProcesses() // // Validates process data sent by user mode. // bool ValidateUserBufferProcesses ( void *Buffer, size_t BufferLength );
381
C++
.h
24
14.083333
50
0.771186
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,060
trace.h
mullvad_win-split-tunnel/src/trace.h
#pragma once // // Define GUID and tracing flags. // #define WPP_CONTROL_GUIDS \ WPP_DEFINE_CONTROL_GUID( \ StTraceGuid, (33E4119D,8A89,4FEC,A90C,C003310B17E9), \ WPP_DEFINE_BIT(TRACE_GENERAL) \ WPP_DEFINE_BIT(TRACE_DRIVER) \ WPP_DEFINE_BIT(TRACE_DEVICE) \ ) #define WPP_FLAG_LEVEL_LOGGER(flag, level) \ WPP_LEVEL_LOGGER(flag) #define WPP_FLAG_LEVEL_ENABLED(flag, level) \ (WPP_LEVEL_ENABLED(flag) && \ WPP_CONTROL(WPP_BIT_ ## flag).Level >= level) #define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) \ WPP_LEVEL_LOGGER(flags) #define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) \ (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_ ## flags).Level >= lvl) // // This comment block is scanned by the trace preprocessor to define the // TraceEvents function. // // This also overrides DbgPrint and sends messages to WPP // // begin_wpp config // FUNC TraceEvents(LEVEL, FLAGS, MSG, ...); // FUNC DbgPrint{LEVEL=TRACE_LEVEL_INFORMATION, FLAGS=TRACE_GENERAL}(MSG, ...); // end_wpp //
1,357
C++
.h
31
39.419355
79
0.520849
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,061
util.h
mullvad_win-split-tunnel/src/util.h
#pragma once #include <wdm.h> #include "defs/types.h" #define bswapw(s) (((s & 0xFF) << 8) | ((s >> 8) & 0xFF)) #define ntohs(s) bswapw(s) #define htons(s) bswapw(s) template<typename T> bool bool_cast(T t) { return t != 0; } namespace util { // // N.B. m has to be a power of two. // inline constexpr SIZE_T RoundToMultiple ( SIZE_T v, SIZE_T m ) { return ((v + m - 1) & ~(m - 1)); } void ReparentList ( LIST_ENTRY *Dest, LIST_ENTRY *Src ); // // GetDevicePathImageName() // // Returns the device path of the process binary. // I.e. the returned path begins with `\Device\HarddiskVolumeX\` // rather than a symbolic link of the form `\??\C:\`. // // A UNICODE_STRING structure and an associated filename buffer // is allocated and returned. // // TODO: The type PEPROCESS seems to require C-linkage on any function // that uses it as an argument. Fix, maybe. // extern "C" NTSTATUS GetDevicePathImageName ( PEPROCESS Process, UNICODE_STRING **ImageName ); bool ValidateBufferRange ( const void *Buffer, const void *BufferEnd, SIZE_T RangeOffset, SIZE_T RangeLength ); bool IsEmptyRange ( const void *Buffer, SIZE_T Length ); // // AllocateCopyDowncaseString() // // Make a lower case copy of the string. // `Dest->Buffer` is allocated and assigned. // NTSTATUS AllocateCopyDowncaseString ( LOWER_UNICODE_STRING *Dest, const UNICODE_STRING * const Src, ST_PAGEABLE Pageable ); void FreeStringBuffer ( UNICODE_STRING *String ); void FreeStringBuffer ( LOWER_UNICODE_STRING *String ); NTSTATUS DuplicateString ( UNICODE_STRING *Dest, const UNICODE_STRING *Src, ST_PAGEABLE Pageable ); NTSTATUS DuplicateString ( LOWER_UNICODE_STRING *Dest, const LOWER_UNICODE_STRING *Src, ST_PAGEABLE Pageable ); void StopIfDebugBuild ( ); bool SplittingEnabled ( ST_PROCESS_SPLIT_STATUS Status ); bool Equal ( const LOWER_UNICODE_STRING *lhs, const LOWER_UNICODE_STRING *rhs ); void Swap ( LOWER_UNICODE_STRING *lhs, LOWER_UNICODE_STRING *rhs ); } // namespace util
1,999
C++
.h
127
14.346457
70
0.759179
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,062
containers.h
mullvad_win-split-tunnel/src/containers.h
#pragma once #include <wdm.h> #include <wdf.h> #include "containers/procregistry.h" #include "containers/registeredimage.h" // // The single instance of this struct lives in the device context. // But it has to be defined here so it can be shared with other components // in the system that should not be concerned with the full context. // struct PROCESS_REGISTRY_MGMT { WDFSPINLOCK Lock; procregistry::CONTEXT *Instance; }; // // Same deal as above. // // This instance is replaced from time to time hence wrapping it makes // for a better interface when sharing it. // struct REGISTERED_IMAGE_MGMT { registeredimage::CONTEXT * volatile Instance; };
658
C++
.h
25
25.08
74
0.777778
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,063
ioctl.h
mullvad_win-split-tunnel/src/ioctl.h
#pragma once #include <ntddk.h> #include <wdf.h> #include "containers/registeredimage.h" namespace ioctl { // // Initialize() // // Initialize subsystems and device context. // NTSTATUS Initialize ( WDFDEVICE Device ); // // SetConfigurationPrepare() // // Parse client buffer into registeredimage instance. // // This should be called at PASSIVE, and the actual updating and // state transition may be performed at DISPATCH. // NTSTATUS SetConfigurationPrepare ( WDFREQUEST Request, registeredimage::CONTEXT **Imageset ); NTSTATUS SetConfiguration ( WDFDEVICE Device, registeredimage::CONTEXT *Imageset ); void GetConfigurationComplete ( WDFDEVICE Device, WDFREQUEST Request ); NTSTATUS ClearConfiguration ( WDFDEVICE Device ); NTSTATUS RegisterProcesses ( WDFDEVICE Device, WDFREQUEST Request ); NTSTATUS RegisterIpAddresses ( WDFDEVICE Device, WDFREQUEST Request ); void GetIpAddressesComplete ( WDFDEVICE Device, WDFREQUEST Request ); void GetStateComplete ( WDFDEVICE Device, WDFREQUEST Request ); void QueryProcessComplete ( WDFDEVICE Device, WDFREQUEST Request ); void ResetComplete ( WDFDEVICE Device, WDFREQUEST Request ); } // namespace ioctl
1,247
C++
.h
84
12.72619
64
0.791123
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,064
devicecontext.h
mullvad_win-split-tunnel/src/devicecontext.h
#pragma once #include <wdf.h> #include "ipaddr.h" #include "containers.h" #include "defs/state.h" #include "firewall/firewall.h" #include "procmgmt/procmgmt.h" #include "eventing/eventing.h" #include "procbroker/procbroker.h" struct DRIVER_STATE_MGMT { WDFWAITLOCK Lock; ST_DRIVER_STATE State; }; typedef struct tag_ST_DEVICE_CONTEXT { DRIVER_STATE_MGMT DriverState; // Parallel queue for processing IOCTLs which use inverted call. WDFQUEUE ParallelRequestQueue; // Serialized queue for processing of most IOCTLs. WDFQUEUE SerializedRequestQueue; ST_IP_ADDRESSES IpAddresses; PROCESS_REGISTRY_MGMT ProcessRegistry; // Protected by state lock. REGISTERED_IMAGE_MGMT RegisteredImage; firewall::CONTEXT *Firewall; procmgmt::CONTEXT *ProcessMgmt; eventing::CONTEXT *Eventing; procbroker::CONTEXT *ProcessEventBroker; } ST_DEVICE_CONTEXT; WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(ST_DEVICE_CONTEXT, DeviceGetSplitTunnelContext)
945
C++
.h
32
27.65625
82
0.817778
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,065
win64guard.h
mullvad_win-split-tunnel/src/win64guard.h
#pragma once #ifdef NTDDI_VERSION // kernel #ifndef _WIN64 #error Only 64-bit is supported #endif #else // user #ifdef _WIN64 #error Only 64-bit is supported #endif #endif
207
C++
.h
10
18
35
0.647959
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,066
ipaddr.h
mullvad_win-split-tunnel/src/ipaddr.h
#pragma once #include <inaddr.h> #include <in6addr.h> typedef struct tag_ST_IP_ADDRESSES { IN_ADDR TunnelIpv4; IN_ADDR InternetIpv4; IN6_ADDR TunnelIpv6; IN6_ADDR InternetIpv6; } ST_IP_ADDRESSES; namespace ip { bool ValidTunnelIpv4Address ( const ST_IP_ADDRESSES *IpAddresses ); bool ValidInternetIpv4Address ( const ST_IP_ADDRESSES *IpAddresses ); bool ValidTunnelIpv6Address ( const ST_IP_ADDRESSES *IpAddresses ); bool ValidInternetIpv6Address ( const ST_IP_ADDRESSES *IpAddresses ); } // namespace ip
522
C++
.h
34
13.852941
35
0.82881
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,067
procmon.h
mullvad_win-split-tunnel/src/procmon/procmon.h
#pragma once #include <wdm.h> namespace procmon { typedef struct tag_PROCESS_EVENT_DETAILS { HANDLE ParentProcessId; // Device path using mixed case characters. UNICODE_STRING ImageName; } PROCESS_EVENT_DETAILS; typedef struct tag_PROCESS_EVENT { LIST_ENTRY ListEntry; HANDLE ProcessId; // // `Details` will be present and valid for processes that are arriving. // If a process is departing, this field is set to NULL. // PROCESS_EVENT_DETAILS *Details; } PROCESS_EVENT; typedef void (NTAPI *PROCESS_EVENT_SINK)(const PROCESS_EVENT *Event, void *Context); struct CONTEXT; NTSTATUS Initialize ( CONTEXT **Context, PROCESS_EVENT_SINK ProcessEventSink, void *SinkContext ); void TearDown ( CONTEXT **Context ); void EnableDispatching ( CONTEXT *Context ); } // namespace procmon
807
C++
.h
42
17.47619
84
0.793883
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,068
context.h
mullvad_win-split-tunnel/src/procmon/context.h
#pragma once #include <wdm.h> #include <wdf.h> #include "procmon.h" namespace procmon { struct CONTEXT { // The thread that services queued process events. PETHREAD DispatchWorker; // Lock to coordinate work on the queue. WDFWAITLOCK QueueLock; // Queue of incoming process events. LIST_ENTRY EventQueue; // Event that signals worker should exit. KEVENT ExitWorker; // Event that signals a new process event has been queued. KEVENT WakeUpWorker; // // Initially events are not dispatched. // // This variable controls whether an event should only be queued or if the queue should be // signalled as well. // bool DispatchingEnabled; // // Client callback function that receives process events. // Single client only in this layer. // PROCESS_EVENT_SINK ProcessEventSink; // // Context to pass along when making the callback. // void *SinkContext; }; } // namespace procmon
910
C++
.h
36
23.25
91
0.767092
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,069
callbacks.h
mullvad_win-split-tunnel/src/procmgmt/callbacks.h
#pragma once #include <wdf.h> namespace procmgmt { typedef void (NTAPI *ACQUIRE_STATE_LOCK_FN)(void *context); typedef void (NTAPI *RELEASE_STATE_LOCK_FN)(void *context); typedef bool (NTAPI *ENGAGED_STATE_ACTIVE_FN)(void *context); } // namespace procmgmt
261
C++
.h
8
31.125
61
0.771084
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,070
context.h
mullvad_win-split-tunnel/src/procmgmt/context.h
#pragma once #include "../procmon/procmon.h" #include "../procbroker/procbroker.h" #include "../containers.h" #include "../eventing/eventing.h" #include "../firewall/firewall.h" #include "callbacks.h" namespace procmgmt { struct CONTEXT { procmon::CONTEXT *ProcessMonitor; procbroker::CONTEXT *ProcessEventBroker; PROCESS_REGISTRY_MGMT *ProcessRegistry; REGISTERED_IMAGE_MGMT *RegisteredImage; eventing::CONTEXT *Eventing; firewall::CONTEXT *Firewall; ACQUIRE_STATE_LOCK_FN AcquireStateLock; RELEASE_STATE_LOCK_FN ReleaseStateLock; ENGAGED_STATE_ACTIVE_FN EngagedStateActive; void *CallbackContext; }; } // namespace procmgmt
650
C++
.h
23
26.217391
44
0.798701
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,071
procmgmt.h
mullvad_win-split-tunnel/src/procmgmt/procmgmt.h
#pragma once #include <ntddk.h> #include <wdf.h> #include "../procbroker/procbroker.h" #include "../containers.h" #include "../eventing/eventing.h" #include "../firewall/firewall.h" #include "callbacks.h" namespace procmgmt { struct CONTEXT; NTSTATUS Initialize ( CONTEXT **Context, procbroker::CONTEXT *ProcessEventBroker, PROCESS_REGISTRY_MGMT *ProcessRegistry, REGISTERED_IMAGE_MGMT *RegisteredImage, eventing::CONTEXT *Eventing, firewall::CONTEXT *Firewall, ACQUIRE_STATE_LOCK_FN AcquireStateLock, RELEASE_STATE_LOCK_FN ReleaseStateLock, ENGAGED_STATE_ACTIVE_FN EngagedStateActive, void *CallbackContext ); void TearDown ( CONTEXT **Context ); // // Activate() // // Until after you call Activate(), all process events are queued. // Call Activate() after the process registry is populated. // void Activate ( CONTEXT *Context ); } // namespace procmgmt
880
C++
.h
42
19.428571
66
0.787004
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,072
builder.h
mullvad_win-split-tunnel/src/eventing/builder.h
#pragma once #include <wdm.h> #include "../defs/events.h" #include "../defs/types.h" #include "eventing.h" namespace eventing { RAW_EVENT* BuildStartSplittingEvent ( HANDLE ProcessId, ST_SPLITTING_STATUS_CHANGE_REASON Reason, LOWER_UNICODE_STRING *ImageName ); RAW_EVENT* BuildStopSplittingEvent ( HANDLE ProcessId, ST_SPLITTING_STATUS_CHANGE_REASON Reason, LOWER_UNICODE_STRING *ImageName ); RAW_EVENT* BuildStartSplittingErrorEvent ( HANDLE ProcessId, LOWER_UNICODE_STRING *ImageName ); RAW_EVENT* BuildStopSplittingErrorEvent ( HANDLE ProcessId, LOWER_UNICODE_STRING *ImageName ); RAW_EVENT* BuildErrorMessageEvent ( NTSTATUS Status, const UNICODE_STRING *ErrorMessage ); void ReleaseEvent ( RAW_EVENT **Event ); } // namespace eventing
762
C++
.h
45
15.444444
42
0.823446
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,073
eventing.h
mullvad_win-split-tunnel/src/eventing/eventing.h
#pragma once #include <wdm.h> #include <wdf.h> namespace eventing { struct CONTEXT; NTSTATUS Initialize ( CONTEXT **Context, WDFDEVICE Device ); void TearDown ( CONTEXT **Context ); struct RAW_EVENT { LIST_ENTRY ListEntry; size_t BufferSize; void *Buffer; }; // // Emit() // // Takes ownership of passed event. // // If possible, sends the event to user mode immediately. // Otherwise queues the event for later dispatching. // void Emit ( CONTEXT *Context, RAW_EVENT **Evt ); // // CollectOne() // // Collects a single event and completes the request. // Or pends the request if there are no queued events. // void CollectOne ( CONTEXT *Context, WDFREQUEST Request ); } // namespace eventing
714
C++
.h
50
12.86
57
0.761103
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,074
context.h
mullvad_win-split-tunnel/src/eventing/context.h
#pragma once #include <wdm.h> #include <wdf.h> namespace eventing { struct CONTEXT { // Pended IOCTL requests for inverted call. WDFQUEUE RequestQueue; WDFSPINLOCK EventQueueLock; LIST_ENTRY EventQueue; SIZE_T NumEvents; }; } // namespace eventing
260
C++
.h
14
16.714286
44
0.799163
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,075
context.h
mullvad_win-split-tunnel/src/procbroker/context.h
#pragma once #include <wdf.h> #include "procbroker.h" namespace procbroker { struct SUBSCRIPTION { LIST_ENTRY ListEntry; ST_PB_CALLBACK Callback; void *ClientContext; }; struct CONTEXT { WDFWAITLOCK SubscriptionsLock; LIST_ENTRY Subscriptions; }; } // namespace procbroker
283
C++
.h
17
15.058824
31
0.816092
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,076
procbroker.h
mullvad_win-split-tunnel/src/procbroker/procbroker.h
#pragma once #include <wdm.h> // // Process event broker. // // Distributes events in the system to notify subsystems when // processes arrive and depart. // // Introduced to break the dependency between "procmgmt" and "firewall". // namespace procbroker { struct CONTEXT; NTSTATUS Initialize ( CONTEXT **Context ); void TearDown ( CONTEXT **Context ); typedef void (NTAPI *ST_PB_CALLBACK)(HANDLE ProcessId, bool Arriving, void *Context); NTSTATUS Subscribe ( CONTEXT *Context, ST_PB_CALLBACK Callback, void *ClientContext ); void CancelSubscription ( CONTEXT *Context, ST_PB_CALLBACK Callback ); void Publish ( CONTEXT *Context, HANDLE ProcessId, bool Arriving ); } // namespace procbroker
712
C++
.h
45
14.355556
85
0.792683
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,077
procregistry.h
mullvad_win-split-tunnel/src/containers/procregistry.h
#pragma once #include <ntddk.h> #include "../defs/types.h" namespace procregistry { struct PROCESS_REGISTRY_ENTRY_SETTINGS { // Whether traffic should be split. ST_PROCESS_SPLIT_STATUS Split; // Whether the process is associated with any firewall filters. bool HasFirewallState; }; struct PROCESS_REGISTRY_ENTRY { HANDLE ParentProcessId; HANDLE ProcessId; PROCESS_REGISTRY_ENTRY_SETTINGS Settings; PROCESS_REGISTRY_ENTRY_SETTINGS TargetSettings; PROCESS_REGISTRY_ENTRY_SETTINGS PreviousSettings; // Device path using all lower-case characters. LOWER_UNICODE_STRING ImageName; // // This is management data initialized and updated // by the implementation. // // It would be inconvenient to store it anywhere else. // PROCESS_REGISTRY_ENTRY *ParentEntry; }; struct CONTEXT; NTSTATUS Initialize ( CONTEXT **Context, ST_PAGEABLE Pageable ); void TearDown ( CONTEXT **Context ); void Reset ( CONTEXT *Context ); // // InitializeEntry() // // IRQL <= APC. // // Initializes `Entry` with provided values and initializes a buffer of // the correct backing and format for `Entry->ImageName.Buffer`. // // The provided `Entry` argument is typically allocated on the stack. // NTSTATUS InitializeEntry ( CONTEXT *Context, HANDLE ParentProcessId, HANDLE ProcessId, ST_PROCESS_SPLIT_STATUS Split, UNICODE_STRING *ImageName, PROCESS_REGISTRY_ENTRY *Entry ); // // AddEntry() // // IRQL <= DISPATCH. // // On Success: // // The `Entry` argument will be copied and `Entry->ImageName.Buffer` // is taken ownership of. // // On failure: // // `Entry->ImageName.Buffer` is not taken ownership of. // NTSTATUS AddEntry ( CONTEXT *Context, PROCESS_REGISTRY_ENTRY *Entry ); // // ReleaseEntry() // // Memory backing the imagename string buffer is allocated by InitializeEntry(). // // Use this function to release an entry that could not be added, in order to // keep details abstracted. // void ReleaseEntry ( PROCESS_REGISTRY_ENTRY *Entry ); PROCESS_REGISTRY_ENTRY* FindEntry ( CONTEXT *Context, HANDLE ProcessId ); bool DeleteEntry ( CONTEXT *Context, PROCESS_REGISTRY_ENTRY *Entry ); bool DeleteEntryById ( CONTEXT *Context, HANDLE ProcessId ); typedef bool (NTAPI *ST_PR_FOREACH)(PROCESS_REGISTRY_ENTRY *Entry, void *Context); bool ForEach ( CONTEXT *Context, ST_PR_FOREACH Callback, void *ClientContext ); PROCESS_REGISTRY_ENTRY* GetParentEntry ( CONTEXT *Context, PROCESS_REGISTRY_ENTRY *Entry ); bool IsEmpty ( CONTEXT *Context ); } // namespace procregistry
2,514
C++
.h
137
16.854015
82
0.783163
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,078
registeredimage.h
mullvad_win-split-tunnel/src/containers/registeredimage.h
#pragma once #include <wdm.h> #include "../defs/types.h" namespace registeredimage { struct REGISTERED_IMAGE_ENTRY { LIST_ENTRY ListEntry; // Device path using all lower-case characters. LOWER_UNICODE_STRING ImageName; }; struct CONTEXT; NTSTATUS Initialize ( CONTEXT **Context, ST_PAGEABLE Pageable ); // // AddEntry() // // IRQL == PASSIVE_LEVEL // // Converts imagename to lower case before creating an entry. // _IRQL_requires_(PASSIVE_LEVEL) NTSTATUS AddEntry ( CONTEXT *Context, UNICODE_STRING *ImageName ); // // AddEntryExact() // // IRQL <= DISPATCH // // Creates a new entry with the `ImageName` argument exactly as passed. // NTSTATUS AddEntryExact ( CONTEXT *Context, LOWER_UNICODE_STRING *ImageName ); // // HasEntry() // // IRQL <= APC // // Compares existing entries against `ImageName` without regard to character casing. // bool HasEntry ( CONTEXT *Context, UNICODE_STRING *ImageName ); // // HasEntryExact() // // IRQL <= DISPATCH // // Compares existing entries against case-sensitive `ImageName` argument. // bool HasEntryExact ( CONTEXT *Context, LOWER_UNICODE_STRING *ImageName ); // // RemoveEntry() // // IRQL <= APC // // Searches for and removes entry matching `ImageName` without regard to character casing. // bool RemoveEntry ( CONTEXT *Context, UNICODE_STRING *ImageName ); // // RemoveEntryExact() // // IRQL <= DISPATCH // // Searches for and removes entry using case-sensitive matching of `ImageName`. // bool RemoveEntryExact ( CONTEXT *Context, LOWER_UNICODE_STRING *ImageName ); typedef bool (NTAPI *ST_RI_FOREACH)(const LOWER_UNICODE_STRING *ImageName, void *Context); bool ForEach ( CONTEXT *Context, ST_RI_FOREACH Callback, void *ClientContext ); void Reset ( CONTEXT *Context ); void TearDown ( CONTEXT **Context ); bool IsEmpty ( CONTEXT *Context ); } // namespace registeredimage
1,863
C++
.h
121
14.057851
90
0.766821
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,079
identifiers.h
mullvad_win-split-tunnel/src/firewall/identifiers.h
#pragma once #include <initguid.h> /////////////////////////////////////////////////////////////////////////////// // // Identifiers used with WFP. // /////////////////////////////////////////////////////////////////////////////// // {E2C114EE-F32A-4264-A6CB-3FA7996356D9} DEFINE_GUID(ST_FW_PROVIDER_KEY, 0xe2c114ee, 0xf32a, 0x4264, 0xa6, 0xcb, 0x3f, 0xa7, 0x99, 0x63, 0x56, 0xd9); // {76653805-1972-45D1-B47C-3140AEBABC49} DEFINE_GUID(ST_FW_CALLOUT_CLASSIFY_BIND_IPV4_KEY, 0x76653805, 0x1972, 0x45d1, 0xb4, 0x7c, 0x31, 0x40, 0xae, 0xba, 0xbc, 0x49); // {53FB3120-B6A4-462B-BFFC-6978AADA1DA2} DEFINE_GUID(ST_FW_CALLOUT_CLASSIFY_BIND_IPV6_KEY, 0x53fb3120, 0xb6a4, 0x462b, 0xbf, 0xfc, 0x69, 0x78, 0xaa, 0xda, 0x1d, 0xa2); // {A4E010B5-DC3F-474A-B7C2-2F3269945F41} DEFINE_GUID(ST_FW_CALLOUT_CLASSIFY_CONNECT_IPV4_KEY, 0xa4e010b5, 0xdc3f, 0x474a, 0xb7, 0xc2, 0x2f, 0x32, 0x69, 0x94, 0x5f, 0x41); // {6B634022-B3D3-4667-88BA-BF5028858F52} DEFINE_GUID(ST_FW_CALLOUT_CLASSIFY_CONNECT_IPV6_KEY, 0x6b634022, 0xb3d3, 0x4667, 0x88, 0xba, 0xbf, 0x50, 0x28, 0x85, 0x8f, 0x52); // {33F3EDCC-EB5E-41CF-9250-702C94A28E39} DEFINE_GUID(ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV4_CONN_KEY, 0x33f3edcc, 0xeb5e, 0x41cf, 0x92, 0x50, 0x70, 0x2c, 0x94, 0xa2, 0x8e, 0x39); // {A7A13809-0DE6-48AB-9BB8-20A8BCEC37AB} DEFINE_GUID(ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV4_RECV_KEY, 0xa7a13809, 0xde6, 0x48ab, 0x9b, 0xb8, 0x20, 0xa8, 0xbc, 0xec, 0x37, 0xab); // {7B7E0055-89F5-4760-8928-CCD57C8830AB} DEFINE_GUID(ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV6_CONN_KEY, 0x7b7e0055, 0x89f5, 0x4760, 0x89, 0x28, 0xcc, 0xd5, 0x7c, 0x88, 0x30, 0xab); // {B40B78EF-5642-40EF-AC4D-F9651261F9E7} DEFINE_GUID(ST_FW_CALLOUT_PERMIT_SPLIT_APPS_IPV6_RECV_KEY, 0xb40b78ef, 0x5642, 0x40ef, 0xac, 0x4d, 0xf9, 0x65, 0x12, 0x61, 0xf9, 0xe7); // {974AA588-397A-483E-AC29-88F4F4112AC2} DEFINE_GUID(ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV4_CONN_KEY, 0x974aa588, 0x397a, 0x483e, 0xac, 0x29, 0x88, 0xf4, 0xf4, 0x11, 0x2a, 0xc2); // {8E314FD7-BDD3-45A4-A712-46036B25B3E1} DEFINE_GUID(ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV4_RECV_KEY, 0x8e314fd7, 0xbdd3, 0x45a4, 0xa7, 0x12, 0x46, 0x3, 0x6b, 0x25, 0xb3, 0xe1); // {466B7800-5EF4-4772-AA79-E0A834328214} DEFINE_GUID(ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV6_CONN_KEY, 0x466b7800, 0x5ef4, 0x4772, 0xaa, 0x79, 0xe0, 0xa8, 0x34, 0x32, 0x82, 0x14); // {D25AFB1B-4645-43CB-B0BE-3794FE487BAC} DEFINE_GUID(ST_FW_CALLOUT_BLOCK_SPLIT_APPS_IPV6_RECV_KEY, 0xd25afb1b, 0x4645, 0x43cb, 0xb0, 0xbe, 0x37, 0x94, 0xfe, 0x48, 0x7b, 0xac); // {B47D14A7-AEED-48B9-AD4E-5529619F1337} DEFINE_GUID(ST_FW_FILTER_CLASSIFY_BIND_IPV4_KEY, 0xb47d14a7, 0xaeed, 0x48b9, 0xad, 0x4e, 0x55, 0x29, 0x61, 0x9f, 0x13, 0x37); // {2F607222-B2EB-443C-B6E0-641067375478} DEFINE_GUID(ST_FW_FILTER_CLASSIFY_BIND_IPV6_KEY, 0x2f607222, 0xb2eb, 0x443c, 0xb6, 0xe0, 0x64, 0x10, 0x67, 0x37, 0x54, 0x78); // {4207F127-CC80-477E-ADDF-26F76585E073} DEFINE_GUID(ST_FW_FILTER_CLASSIFY_CONNECT_IPV4_KEY, 0x4207f127, 0xcc80, 0x477e, 0xad, 0xdf, 0x26, 0xf7, 0x65, 0x85, 0xe0, 0x73); // {9A87F137-5112-4427-B315-4F87B3E84DCC} DEFINE_GUID(ST_FW_FILTER_CLASSIFY_CONNECT_IPV6_KEY, 0x9a87f137, 0x5112, 0x4427, 0xb3, 0x15, 0x4f, 0x87, 0xb3, 0xe8, 0x4d, 0xcc); // {66CED079-C270-4B4D-A45C-D11711C0D600} DEFINE_GUID(ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV4_CONN_KEY, 0x66ced079, 0xc270, 0x4b4d, 0xa4, 0x5c, 0xd1, 0x17, 0x11, 0xc0, 0xd6, 0x0); // {37972155-EBDB-49FC-9A37-3A0B3B0AA100} DEFINE_GUID(ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV4_RECV_KEY, 0x37972155, 0xebdb, 0x49fc, 0x9a, 0x37, 0x3a, 0xb, 0x3b, 0xa, 0xa1, 0x0); // {0AFA08E3-B010-4082-9E03-1CC4BE1C6CF8} DEFINE_GUID(ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV6_CONN_KEY, 0xafa08e3, 0xb010, 0x4082, 0x9e, 0x3, 0x1c, 0xc4, 0xbe, 0x1c, 0x6c, 0xf8); // {7835DFD7-24AE-44F4-8A8A-5E9C766AAE63} DEFINE_GUID(ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV6_RECV_KEY, 0x7835dfd7, 0x24ae, 0x44f4, 0x8a, 0x8a, 0x5e, 0x9c, 0x76, 0x6a, 0xae, 0x63); // {EDB743A8-1A77-4BA9-906B-C594A7DDB75B} DEFINE_GUID(ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV4_DNS_CONN_KEY, 0xedb743a8, 0x1a77, 0x4ba9, 0x90, 0x6b, 0xc5, 0x94, 0xa7, 0xdd, 0xb7, 0x5b); // {5373BF17-937E-438B-A307-CD50E125DFF9} DEFINE_GUID(ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV4_DNS_RECV_KEY, 0x5373bf17, 0x937e, 0x438b, 0xa3, 0x7, 0xcd, 0x50, 0xe1, 0x25, 0xdf, 0xf9); // {355F9524-8CE0-4C85-902F-EDF0252556D4} DEFINE_GUID(ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV6_DNS_CONN_KEY, 0x355f9524, 0x8ce0, 0x4c85, 0x90, 0x2f, 0xed, 0xf0, 0x25, 0x25, 0x56, 0xd4); // {282B9C48-4029-4D27-8FE0-8C3C4B84F952} DEFINE_GUID(ST_FW_FILTER_PERMIT_SPLIT_APPS_IPV6_DNS_RECV_KEY, 0x282b9c48, 0x4029, 0x4d27, 0x8f, 0xe0, 0x8c, 0x3c, 0x4b, 0x84, 0xf9, 0x52); // {D8602FF5-436B-414A-A221-7B4DE8CE96C7} DEFINE_GUID(ST_FW_FILTER_BLOCK_ALL_SPLIT_APPS_TUNNEL_IPV4_CONN_KEY, 0xd8602ff5, 0x436b, 0x414a, 0xa2, 0x21, 0x7b, 0x4d, 0xe8, 0xce, 0x96, 0xc7); // {FC3F8D71-33F7-4D24-9306-A3DEE3F7C865} DEFINE_GUID(ST_FW_FILTER_BLOCK_ALL_SPLIT_APPS_TUNNEL_IPV4_RECV_KEY, 0xfc3f8d71, 0x33f7, 0x4d24, 0x93, 0x6, 0xa3, 0xde, 0xe3, 0xf7, 0xc8, 0x65); // {05CB3C5E-6F64-44F7-81B1-C890563FA280} DEFINE_GUID(ST_FW_FILTER_BLOCK_ALL_SPLIT_APPS_TUNNEL_IPV6_CONN_KEY, 0x5cb3c5e, 0x6f64, 0x44f7, 0x81, 0xb1, 0xc8, 0x90, 0x56, 0x3f, 0xa2, 0x80); // {C854E73A-81C8-4814-9A55-55BAF2C3BD17} DEFINE_GUID(ST_FW_FILTER_BLOCK_ALL_SPLIT_APPS_TUNNEL_IPV6_RECV_KEY, 0xc854e73a, 0x81c8, 0x4814, 0x9a, 0x55, 0x55, 0xba, 0xf2, 0xc3, 0xbd, 0x17); // // This sublayer is defined and registered by `winfw`. // We're going to reuse it to avoid having different sublayers fight over // whether something should be blocked or permitted. // DEFINE_GUID(ST_FW_WINFW_BASELINE_SUBLAYER_KEY, 0xc78056ff, 0x2bc1, 0x4211, 0xaa, 0xdd, 0x7f, 0x35, 0x8d, 0xef, 0x20, 0x2d); // // This sublayer is defined and registered by `winfw`. // It's used to restrict traffic with destination port 53 (DNS). // We need to install a filter there to make exceptions for excluded processes. // DEFINE_GUID(ST_FW_WINFW_DNS_SUBLAYER_KEY, 0x60090787, 0xcca1, 0x4937, 0xaa, 0xce, 0x51, 0x25, 0x6e, 0xf4, 0x81, 0xf3); // {FDC95593-04EF-415C-AE68-46BD8B4821A8} DEFINE_GUID(ST_FW_PROVIDER_CONTEXT_KEY, 0xfdc95593, 0x4ef, 0x415c, 0xae, 0x68, 0x46, 0xbd, 0x8b, 0x48, 0x21, 0xa8);
6,192
C++
.h
111
54.189189
79
0.734414
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,080
classify.h
mullvad_win-split-tunnel/src/firewall/classify.h
#pragma once #include "wfp.h" namespace firewall { void ClassificationReset ( FWPS_CLASSIFY_OUT0 *ClassifyOut ); void ClassificationApplyHardPermit ( FWPS_CLASSIFY_OUT0 *ClassifyOut ); void ClassificationApplySoftPermit ( FWPS_CLASSIFY_OUT0 *ClassifyOut ); void ClassificationApplyHardBlock ( FWPS_CLASSIFY_OUT0 *ClassifyOut ); } // namespace firewall
363
C++
.h
25
13.08
32
0.858006
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,081
wfp.h
mullvad_win-split-tunnel/src/firewall/wfp.h
#pragma once // // Magical include order with defines etc. // Infuriating. // #include <ntddk.h> #include <wdm.h> #include <initguid.h> #pragma warning(push) #pragma warning(disable:4201) #define NDIS630 #include <ndis.h> #include <fwpsk.h> #pragma warning(pop) #include <fwpmk.h> #include <mstcpip.h>
304
C++
.h
16
17.875
42
0.758741
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,082
mode.h
mullvad_win-split-tunnel/src/firewall/mode.h
#pragma once #include <wdm.h> #include <wdf.h> #include "../ipaddr.h" namespace firewall { enum class SPLITTING_MODE { // Placeholder MODE_0 = 0, // Exclude IPv4/IPv6 MODE_1, // Exclude IPv4 MODE_2, // Exclude IPv4, Permit non-tunnel IPv6 MODE_3, // Exclude IPv4, Block tunnel-IPv6 MODE_4, // Exclude IPv6 MODE_5, // Exclude IPv6, Permit non-tunnel IPv4 MODE_6, // Exclude IPv6, Block tunnel-IPv4 MODE_7, // Block tunnel IPv4, Permit non-tunnel IPv6 MODE_8, // Block tunnel IPv6, Permit non-tunnel IPv4 MODE_9 }; NTSTATUS DetermineSplittingMode ( const ST_IP_ADDRESSES *IpAddresses, SPLITTING_MODE *Mode ); } // namespace firewall
667
C++
.h
36
16.527778
45
0.740681
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,083
context.h
mullvad_win-split-tunnel/src/firewall/context.h
#pragma once #include <wdm.h> #include <wdf.h> #include "firewall.h" #include "mode.h" #include "pending.h" #include "../ipaddr.h" #include "../procbroker/procbroker.h" #include "../eventing/eventing.h" namespace firewall { struct IP_ADDRESSES_MGMT { WDFSPINLOCK Lock; ST_IP_ADDRESSES Addresses; SPLITTING_MODE SplittingMode; }; struct TRANSACTION_MGMT { // Lock that is held for the duration of a transaction. WDFWAITLOCK Lock; // Indicator of active transaction. bool Active; // Thread ID of transaction owner. HANDLE OwnerId; }; struct ACTIVE_FILTERS { bool BindRedirectIpv4; bool BindRedirectIpv6; bool ConnectRedirectIpv4; bool ConnectRedirectIpv6; bool PermitNonTunnelIpv4; bool PermitNonTunnelIpv6; bool BlockTunnelIpv4; bool BlockTunnelIpv6; }; struct CONTEXT { bool SplittingEnabled; ACTIVE_FILTERS ActiveFilters; CALLBACKS Callbacks; HANDLE WfpSession; IP_ADDRESSES_MGMT IpAddresses; pending::CONTEXT *PendedClassifications; eventing::CONTEXT *Eventing; TRANSACTION_MGMT Transaction; // // Context used with the appfilters module. // void *AppFiltersContext; }; } // namespace firewall
1,142
C++
.h
53
19.679245
56
0.803172
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,084
appfilters.h
mullvad_win-split-tunnel/src/firewall/appfilters.h
#pragma once #include <wdm.h> #include <inaddr.h> #include <in6addr.h> #include "../defs/types.h" // // This module is used to manage app-specific filters. // // App-specific filters apply only to apps being split and use the full app path // to qualify candidates. // namespace firewall::appfilters { NTSTATUS Initialize ( HANDLE WfpSession, void **Context ); void TearDown ( void **Context ); NTSTATUS TransactionBegin ( void *Context ); void TransactionCommit ( void *Context ); void TransactionAbort ( void *Context ); // // RegisterFilterBlockAppTunnelTrafficTx2() // // Register WFP filters, with linked callout, that will block connections in the tunnel // from applications being split. // // This is used to block existing connections inside the tunnel for applications that are // just now being split. // // All available tunnel addresses must be provided. // // IMPORTANT: These functions need to be running inside a WFP transaction as well as a // local transaction managed by this module. // NTSTATUS RegisterFilterBlockAppTunnelTrafficTx2 ( void *Context, const LOWER_UNICODE_STRING *ImageName, const IN_ADDR *TunnelIpv4, const IN6_ADDR *TunnelIpv6 ); NTSTATUS RemoveFilterBlockAppTunnelTrafficTx2 ( void *Context, const LOWER_UNICODE_STRING *ImageName ); // // ResetTx2() // // Remove all app-specific blocking filters. // // IMPORTANT: This function needs to be running inside a WFP transaction as well as a // local transaction managed by this module. // NTSTATUS ResetTx2 ( void *Context ); // // UpdateFiltersTx2() // // Rewrite filters with updated IP addresses. // // IMPORTANT: This function needs to be running inside a WFP transaction as well as a // local transaction managed by this module. // NTSTATUS UpdateFiltersTx2 ( void *Context, const IN_ADDR *TunnelIpv4, const IN6_ADDR *TunnelIpv6 ); } // namespace firewall::appfilters
1,887
C++
.h
96
18.34375
90
0.788526
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,085
filters.h
mullvad_win-split-tunnel/src/firewall/filters.h
#pragma once #include "wfp.h" #include "context.h" namespace firewall { // // RegisterFilterBindRedirectIpv4Tx() // // Register filter, with linked callout, that will pass all bind requests through the bind callout // for validation/redirection. // // Applicable binds are rewritten for apps being split. // // "Tx" (in transaction) suffix means there's no clean-up in failure paths. // NTSTATUS RegisterFilterBindRedirectIpv4Tx ( HANDLE WfpSession ); NTSTATUS RemoveFilterBindRedirectIpv4Tx ( HANDLE WfpSession ); // // RegisterFilterBindRedirectIpv6Tx() // // Refer comment on corresponding function for IPv4. // NTSTATUS RegisterFilterBindRedirectIpv6Tx ( HANDLE WfpSession ); NTSTATUS RemoveFilterBindRedirectIpv6Tx ( HANDLE WfpSession ); // // RegisterFilterConnectRedirectIpv4Tx() // // Register filter, with linked callout, that will pass all connection requests through // the connection callout for validation/redirection. // // The callout will look for and amend broken localhost client connections. // // "Tx" (in transaction) suffix means there's no clean-up in failure paths. // NTSTATUS RegisterFilterConnectRedirectIpv4Tx ( HANDLE WfpSession ); NTSTATUS RemoveFilterConnectRedirectIpv4Tx ( HANDLE WfpSession ); // // RegisterFilterConnectRedirectIpv6Tx() // // Refer comment on corresponding function for IPv4. // NTSTATUS RegisterFilterConnectRedirectIpv6Tx ( HANDLE WfpSession ); NTSTATUS RemoveFilterConnectRedirectIpv6Tx ( HANDLE WfpSession ); // // RegisterFilterPermitNonTunnelIpv4Tx() // // Register filters, with linked callout, that permit non-tunnel IPv4 traffic // associated with applications being split. // // This ensures winfw filters are not applied to these apps. // // The TunnelIpv4 argument is optional but must be specified if the tunnel adapter // uses an IPv4 interface. // // "Tx" (in transaction) suffix means there's no clean-up in failure paths. // NTSTATUS RegisterFilterPermitNonTunnelIpv4Tx ( HANDLE WfpSession, const IN_ADDR *TunnelIpv4 ); NTSTATUS RemoveFilterPermitNonTunnelIpv4Tx ( HANDLE WfpSession ); // // RegisterFilterPermitNonTunnelIpv6Tx() // // Refer comment on corresponding function for IPv4. // NTSTATUS RegisterFilterPermitNonTunnelIpv6Tx ( HANDLE WfpSession, const IN6_ADDR *TunnelIpv6 ); NTSTATUS RemoveFilterPermitNonTunnelIpv6Tx ( HANDLE WfpSession ); // // RegisterFilterBlockTunnelIpv4Tx() // // Block all tunnel IPv4 traffic for applications being split. // To be used when the primary physical adapter doesn't have an IPv4 interface. // NTSTATUS RegisterFilterBlockTunnelIpv4Tx ( HANDLE WfpSession, const IN_ADDR *TunnelIp ); NTSTATUS RemoveFilterBlockTunnelIpv4Tx ( HANDLE WfpSession ); // // RegisterFilterBlockTunnelIpv6Tx() // // Refer comment on corresponding function for IPv4. // NTSTATUS RegisterFilterBlockTunnelIpv6Tx ( HANDLE WfpSession, const IN6_ADDR *TunnelIp ); NTSTATUS RemoveFilterBlockTunnelIpv6Tx ( HANDLE WfpSession ); } // namespace firewall
2,973
C++
.h
149
18.691275
98
0.826025
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,086
callouts.h
mullvad_win-split-tunnel/src/firewall/callouts.h
#pragma once #include <wdm.h> namespace firewall { NTSTATUS RegisterCalloutClassifyBindTx ( PDEVICE_OBJECT DeviceObject, HANDLE WfpSession ); NTSTATUS UnregisterCalloutClassifyBind ( ); NTSTATUS RegisterCalloutClassifyConnectTx ( PDEVICE_OBJECT DeviceObject, HANDLE WfpSession ); NTSTATUS UnregisterCalloutClassifyConnect ( ); NTSTATUS RegisterCalloutPermitSplitAppsTx ( PDEVICE_OBJECT DeviceObject, HANDLE WfpSession ); NTSTATUS UnregisterCalloutPermitSplitApps ( ); NTSTATUS RegisterCalloutBlockSplitAppsTx ( PDEVICE_OBJECT DeviceObject, HANDLE WfpSession ); NTSTATUS UnregisterCalloutBlockSplitApps ( ); } // namespace firewall
650
C++
.h
45
13.022222
32
0.893939
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,087
firewall.h
mullvad_win-split-tunnel/src/firewall/firewall.h
#pragma once #include <wdm.h> #include "../ipaddr.h" #include "../defs/types.h" #include "../procbroker/procbroker.h" #include "../eventing/eventing.h" namespace firewall { struct CONTEXT; /////////////////////////////////////////////////////////////////////////////// // // Callback definitions. // Client(s) of the firewall subsystem provide the implementations. // /////////////////////////////////////////////////////////////////////////////// enum class PROCESS_SPLIT_VERDICT { DO_SPLIT, DONT_SPLIT, // PID is unknown UNKNOWN }; typedef PROCESS_SPLIT_VERDICT (NTAPI *QUERY_PROCESS_FUNC) ( HANDLE ProcessId, void *Context ); typedef struct tag_CALLBACKS { QUERY_PROCESS_FUNC QueryProcess; void *Context; } CALLBACKS; /////////////////////////////////////////////////////////////////////////////// // // Public functions. // /////////////////////////////////////////////////////////////////////////////// NTSTATUS Initialize ( CONTEXT **Context, PDEVICE_OBJECT DeviceObject, const CALLBACKS *Callbacks, procbroker::CONTEXT *ProcessEventBroker, eventing::CONTEXT *Eventing ); NTSTATUS TearDown ( CONTEXT **Context ); NTSTATUS EnableSplitting ( CONTEXT *Context, const ST_IP_ADDRESSES *IpAddresses ); NTSTATUS DisableSplitting ( CONTEXT *Context ); NTSTATUS RegisterUpdatedIpAddresses ( CONTEXT *Context, const ST_IP_ADDRESSES *IpAddresses ); NTSTATUS TransactionBegin ( CONTEXT *Context ); NTSTATUS TransactionCommit ( CONTEXT *Context, bool ForceAleReauthorization = false ); NTSTATUS TransactionAbort ( CONTEXT *Context ); NTSTATUS RegisterAppBecomingSplitTx ( CONTEXT *Context, const LOWER_UNICODE_STRING *ImageName ); NTSTATUS RegisterAppBecomingUnsplitTx ( CONTEXT *Context, const LOWER_UNICODE_STRING *ImageName ); } // namespace firewall
1,794
C++
.h
100
16.47
79
0.660693
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,088
logging.h
mullvad_win-split-tunnel/src/firewall/logging.h
#pragma once #include "wfp.h" #include "mode.h" namespace firewall { void LogBindRedirect ( HANDLE ProcessId, const SOCKADDR_IN *Target, const IN_ADDR *Override ); void LogBindRedirect ( HANDLE ProcessId, const SOCKADDR_IN6 *Target, const IN6_ADDR *Override ); void LogConnectRedirectPass ( HANDLE ProcessId, const IN_ADDR *LocalAddress, USHORT LocalPort, const IN_ADDR *RemoteAddress, USHORT RemotePort ); void LogConnectRedirectPass ( HANDLE ProcessId, const IN6_ADDR *LocalAddress, USHORT LocalPort, const IN6_ADDR *RemoteAddress, USHORT RemotePort ); void LogConnectRedirect ( HANDLE ProcessId, const IN_ADDR *LocalAddress, USHORT LocalPort, const IN_ADDR *LocalAddressOverride, const IN_ADDR *RemoteAddress, USHORT RemotePort ); void LogConnectRedirect ( HANDLE ProcessId, const IN6_ADDR *LocalAddress, USHORT LocalPort, const IN6_ADDR *LocalAddressOverride, const IN6_ADDR *RemoteAddress, USHORT RemotePort ); void LogPermitConnection ( HANDLE ProcessId, const IN_ADDR *LocalAddress, USHORT LocalPort, const IN_ADDR *RemoteAddress, USHORT RemotePort, bool outgoing ); void LogPermitConnection ( HANDLE ProcessId, const IN6_ADDR *LocalAddress, USHORT LocalPort, const IN6_ADDR *RemoteAddress, USHORT RemotePort, bool outgoing ); void LogBlockConnection ( HANDLE ProcessId, const IN_ADDR *LocalAddress, USHORT LocalPort, const IN_ADDR *RemoteAddress, USHORT RemotePort, bool outgoing ); void LogBlockConnection ( HANDLE ProcessId, const IN6_ADDR *LocalAddress, USHORT LocalPort, const IN6_ADDR *RemoteAddress, USHORT RemotePort, bool outgoing ); void LogActivatedSplittingMode ( SPLITTING_MODE Mode ); }; // namespace firewall
1,698
C++
.h
103
14.834951
38
0.829855
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,089
constants.h
mullvad_win-split-tunnel/src/firewall/constants.h
#pragma once #include <wdm.h> namespace { static const UINT64 ST_MAX_FILTER_WEIGHT = MAXUINT64; static const UINT64 ST_HIGH_FILTER_WEIGHT = MAXUINT64 - 10; static const UINT16 DNS_SERVER_PORT = 53; } // anonymous namespace
228
C++
.h
8
26.875
59
0.786047
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,090
pending.h
mullvad_win-split-tunnel/src/firewall/pending.h
#pragma once #include "wfp.h" #include <wdf.h> #include "../procbroker/procbroker.h" // // This module is currently used for pending redirection classifications, // but could plausibly be extended to handle other types of classifications, // as and when the need arises. // namespace firewall::pending { struct CONTEXT; NTSTATUS Initialize ( CONTEXT **Context, procbroker::CONTEXT *ProcessEventBroker ); void TearDown ( CONTEXT **Context ); NTSTATUS PendRequest ( CONTEXT *Context, HANDLE ProcessId, void *ClassifyContext, UINT64 FilterId, UINT16 LayerId, FWPS_CLASSIFY_OUT0 *ClassifyOut ); NTSTATUS FailRequest ( HANDLE ProcessId, void *ClassifyContext, UINT64 FilterId, UINT16 LayerId, FWPS_CLASSIFY_OUT0 *ClassifyOut ); } // namespace firewall::pending
812
C++
.h
43
16.581395
76
0.772368
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,091
queryprocess.h
mullvad_win-split-tunnel/src/defs/queryprocess.h
#pragma once // // Structures related to querying process information. // typedef struct tag_ST_QUERY_PROCESS { HANDLE ProcessId; } ST_QUERY_PROCESS; typedef struct tag_ST_QUERY_PROCESS_RESPONSE { HANDLE ProcessId; HANDLE ParentProcessId; BOOLEAN Split; // Byte length for non-null terminated wide char string. USHORT ImageNameLength; WCHAR ImageName[ANYSIZE_ARRAY]; } ST_QUERY_PROCESS_RESPONSE;
409
C++
.h
19
19.842105
57
0.815104
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,092
state.h
mullvad_win-split-tunnel/src/defs/state.h
#pragma once // // All possible states in the driver. // enum ST_DRIVER_STATE { // Default state after being loaded. ST_DRIVER_STATE_NONE = 0, // DriverEntry has completed successfully. // Basically only driver and device objects are created at this point. ST_DRIVER_STATE_STARTED = 1, // All subsystems are initialized. ST_DRIVER_STATE_INITIALIZED = 2, // User mode has registered all processes in the system. ST_DRIVER_STATE_READY = 3, // IP addresses are registered. // A valid configuration is registered. ST_DRIVER_STATE_ENGAGED = 4, // Driver could not tear down subsystems. ST_DRIVER_STATE_ZOMBIE = 5, };
633
C++
.h
21
28.142857
71
0.753719
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,093
ioctl.h
mullvad_win-split-tunnel/src/defs/ioctl.h
#pragma once // // IOCTLs for controlling the driver. // #define ST_DEVICE_TYPE 0x8000 #define IOCTL_ST_INITIALIZE \ CTL_CODE(ST_DEVICE_TYPE, 1, METHOD_NEITHER, FILE_ANY_ACCESS) #define IOCTL_ST_DEQUEUE_EVENT \ CTL_CODE(ST_DEVICE_TYPE, 2, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_ST_REGISTER_PROCESSES \ CTL_CODE(ST_DEVICE_TYPE, 3, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_ST_REGISTER_IP_ADDRESSES \ CTL_CODE(ST_DEVICE_TYPE, 4, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_ST_GET_IP_ADDRESSES \ CTL_CODE(ST_DEVICE_TYPE, 5, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_ST_SET_CONFIGURATION \ CTL_CODE(ST_DEVICE_TYPE, 6, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_ST_GET_CONFIGURATION \ CTL_CODE(ST_DEVICE_TYPE, 7, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_ST_CLEAR_CONFIGURATION \ CTL_CODE(ST_DEVICE_TYPE, 8, METHOD_NEITHER, FILE_ANY_ACCESS) #define IOCTL_ST_GET_STATE \ CTL_CODE(ST_DEVICE_TYPE, 9, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_ST_QUERY_PROCESS \ CTL_CODE(ST_DEVICE_TYPE, 10, METHOD_BUFFERED, FILE_ANY_ACCESS) // // IOCTL_ST_RESET: // // Use before attempting to unload the driver. // Subsystems will be torn down, resources released etc. // // On success, the new state will be ST_DRIVER_STATE_STARTED. // On error, the new state will be ST_DRIVER_STATE_ZOMBIE. // #define IOCTL_ST_RESET \ CTL_CODE(ST_DEVICE_TYPE, 11, METHOD_NEITHER, FILE_ANY_ACCESS)
1,426
C++
.h
36
37.944444
63
0.762527
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,094
process.h
mullvad_win-split-tunnel/src/defs/process.h
#pragma once // // Structures related to initial process registration. // typedef struct tag_ST_PROCESS_DISCOVERY_ENTRY { HANDLE ProcessId; HANDLE ParentProcessId; // Offset into buffer region that follows all entries. // The image name uses the device path. SIZE_T ImageNameOffset; // Byte length for non-null terminated wide char string. USHORT ImageNameLength; } ST_PROCESS_DISCOVERY_ENTRY; typedef struct tag_ST_PROCESS_DISCOVERY_HEADER { // Number of entries immediately following the header. SIZE_T NumEntries; // Total byte length: header + entries + string buffer. SIZE_T TotalLength; } ST_PROCESS_DISCOVERY_HEADER;
641
C++
.h
23
26.130435
57
0.79902
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,095
types.h
mullvad_win-split-tunnel/src/defs/types.h
#pragma once // // types.h // // Miscellaneous types and defines used internally. // #define ST_POOL_TAG 'UTPS' enum class ST_PAGEABLE { YES = 0, NO }; // // Type-safety when passing around lower case device paths. // Same definition as UNICODE_STRING so they can be cast between. // typedef struct tag_LOWER_UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWCH Buffer; } LOWER_UNICODE_STRING; enum ST_PROCESS_SPLIT_STATUS { // Traffic should be split. ST_PROCESS_SPLIT_STATUS_ON_BY_CONFIG = 0, // Traffic should be split. ST_PROCESS_SPLIT_STATUS_ON_BY_INHERITANCE, // Traffic should not be split. ST_PROCESS_SPLIT_STATUS_OFF };
664
C++
.h
32
18.90625
65
0.7504
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,096
events.h
mullvad_win-split-tunnel/src/defs/events.h
#pragma once enum ST_EVENT_ID { ST_EVENT_ID_START_SPLITTING_PROCESS = 0, // ST_SPLITTING_EVENT ST_EVENT_ID_STOP_SPLITTING_PROCESS, // ST_SPLITTING_EVENT ST_EVENT_ID_ERROR_FLAG = 0x80000000, ST_EVENT_ID_ERROR_START_SPLITTING_PROCESS, // ST_SPLITTING_ERROR_EVENT ST_EVENT_ID_ERROR_STOP_SPLITTING_PROCESS, // ST_SPLITTING_ERROR_EVENT ST_EVENT_ID_ERROR_MESSAGE // ST_ERROR_MESSAGE_EVENT }; typedef struct tag_ST_EVENT_HEADER { ST_EVENT_ID EventId; // Size of payload. SIZE_T EventSize; // Message defined payload. UCHAR EventData[ANYSIZE_ARRAY]; } ST_EVENT_HEADER; enum ST_SPLITTING_STATUS_CHANGE_REASON { ST_SPLITTING_REASON_BY_INHERITANCE = 1, ST_SPLITTING_REASON_BY_CONFIG = 2, ST_SPLITTING_REASON_PROCESS_ARRIVING = 4, ST_SPLITTING_REASON_PROCESS_DEPARTING = 8 }; typedef struct tag_ST_SPLITTING_EVENT { HANDLE ProcessId; ST_SPLITTING_STATUS_CHANGE_REASON Reason; // Byte length for non-null terminated wide char string. USHORT ImageNameLength; WCHAR ImageName[ANYSIZE_ARRAY]; } ST_SPLITTING_EVENT; typedef struct tag_ST_SPLITTING_ERROR_EVENT { HANDLE ProcessId; // Byte length for non-null terminated wide char string. USHORT ImageNameLength; WCHAR ImageName[ANYSIZE_ARRAY]; } ST_SPLITTING_ERROR_EVENT; typedef struct tag_ST_ERROR_MESSAGE_EVENT { NTSTATUS Status; // Byte length for non-null terminated wide char string. USHORT ErrorMessageLength; WCHAR ErrorMessage[ANYSIZE_ARRAY]; } ST_ERROR_MESSAGE_EVENT;
1,462
C++
.h
51
26.764706
71
0.79038
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,097
config.h
mullvad_win-split-tunnel/src/defs/config.h
#pragma once // // Structures related to configuration. // typedef struct tag_ST_CONFIGURATION_ENTRY { // Offset into buffer region that follows all entries. // The image name uses the device path. SIZE_T ImageNameOffset; // Byte length for non-null terminated wide char string. USHORT ImageNameLength; } ST_CONFIGURATION_ENTRY; typedef struct tag_ST_CONFIGURATION_HEADER { // Number of entries immediately following the header. SIZE_T NumEntries; // Total byte length: header + entries + string buffer. SIZE_T TotalLength; } ST_CONFIGURATION_HEADER;
565
C++
.h
21
25.238095
57
0.794063
mullvad/win-split-tunnel
37
9
1
GPL-3.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,098
SubmenuManager.cpp
shriprem_FWDataViz/src/SubmenuManager.cpp
#include "SubmenuManager.h" #include "Dialogs/VisualizerPanel.h" #include "Resources/SamplesMenuDefs.h" extern FuncItem pluginMenuItems[MI_COUNT]; extern VisualizerPanel _vizPanel; void SubmenuManager::listSampleFiles() { HMENU hSubMenu = getPluginSubMenu(); if (hSubMenu == NULL) return; HMENU hMenuSingleRec = CreatePopupMenu(); ModifyMenu(hSubMenu, MI_DEMO_SINGLE_REC_FILES, MF_BYPOSITION | MF_POPUP, (UINT_PTR)hMenuSingleRec, MENU_DEMO_SINGLE_REC_FILES); HMENU hMenuMultiRec = CreatePopupMenu(); ModifyMenu(hSubMenu, MI_DEMO_MULTI_REC_FILES, MF_BYPOSITION | MF_POPUP, (UINT_PTR)hMenuMultiRec, MENU_DEMO_MULTI_REC_FILES); HMENU hMenuMultiLine = CreatePopupMenu(); ModifyMenu(hSubMenu, MI_DEMO_MULTI_LINE_FILES, MF_BYPOSITION | MF_POPUP, (UINT_PTR)hMenuMultiLine, MENU_DEMO_MULTI_LINE_FILES); itemCount = std::size(gSampleFiles); if (!nppMessage(NPPM_ALLOCATECMDID, itemCount, (LPARAM)&itemIDStart)) return; nppMessage(NPPM_GETPLUGINHOMEPATH, MAX_PATH, (LPARAM)pluginSamplesDir); PathAppend(pluginSamplesDir, PLUGIN_FOLDER_NAME); PathAppend(pluginSamplesDir, L"Samples"); HMENU hWhich; TCHAR sampleFile[MAX_PATH]; for (size_t i{}; i < itemCount; ++i) { switch (gSampleFiles[i].sample_type) { case SINGLE_REC: hWhich = hMenuSingleRec; break; case MULTI_REC: hWhich = hMenuMultiRec; break; case MULTI_LINE: hWhich = hMenuMultiLine; break; default: continue; } PathCombine(sampleFile, pluginSamplesDir, gSampleFiles[i].file_name.c_str()); if (Utils::checkFileExists(sampleFile)) AppendMenu(hWhich, MF_STRING, itemIDStart + i, Utils::NarrowToWide(gSampleFiles[i].display_name).c_str()); } } void SubmenuManager::loadSampleFile(WPARAM wParam, LPARAM) const { size_t cmdID{ LOWORD(wParam) - itemIDStart }; if (cmdID < 0 || cmdID > itemCount) return; TCHAR sampleFile[MAX_PATH]; PathCombine(sampleFile, pluginSamplesDir, gSampleFiles[cmdID].file_name.c_str()); if (!Utils::checkFileExists(sampleFile)) return; nppMessage(NPPM_DOOPEN, 0, (LPARAM)sampleFile); ShowVisualizerPanel(TRUE); _configIO.defaultVizConfig(); _vizPanel.visualizeFile(gSampleFiles[cmdID].file_type, FALSE, FALSE, TRUE); } void SubmenuManager::initSamplesPopup(HMENU hPopup) { HMENU hSubMenu = getPluginSubMenu(); if (hSubMenu == NULL) return; HMENU hMenuSingle = GetSubMenu(hSubMenu, MI_DEMO_SINGLE_REC_FILES); AppendMenu(hPopup, MF_POPUP, (UINT_PTR)hMenuSingle, MENU_DEMO_SINGLE_REC_FILES); HMENU hMenuMultiRec = GetSubMenu(hSubMenu, MI_DEMO_MULTI_REC_FILES); AppendMenu(hPopup, MF_POPUP, (UINT_PTR)hMenuMultiRec, MENU_DEMO_MULTI_REC_FILES); HMENU hMenuMultiLine = GetSubMenu(hSubMenu, MI_DEMO_MULTI_LINE_FILES); AppendMenu(hPopup, MF_POPUP, (UINT_PTR)hMenuMultiLine, MENU_DEMO_MULTI_LINE_FILES); } HMENU SubmenuManager::getPluginSubMenu() { HMENU hPluginMenu = (HMENU)nppMessage(NPPM_GETMENUHANDLE); int menuItemCount = GetMenuItemCount(hPluginMenu); for (int i{}; i < menuItemCount; ++i) { TCHAR pluginItemText[MAX_PATH]; int pluginItemLen{}; pluginItemLen = GetMenuString(hPluginMenu, i, pluginItemText, MAX_PATH, MF_BYPOSITION); if (pluginItemLen > 0 && wstring{ pluginItemText } == MENU_PANEL_NAME) { HMENU hSubMenu = GetSubMenu(hPluginMenu, i); if (GetMenuState(hSubMenu, (UINT)pluginMenuItems[0]._cmdID, MF_BYCOMMAND) != -1) return hSubMenu; } } return NULL; }
3,599
C++
.cpp
77
41.012987
130
0.71723
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,099
VisualizerMain.cpp
shriprem_FWDataViz/src/VisualizerMain.cpp
//This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #include "PluginDefinition.h" #include "SubmenuManager.h" #include "Dialogs/VisualizerPanel.h" #include "Darkmode/NPP_Plugin_Darkmode.h" extern FuncItem pluginMenuItems[MI_COUNT]; extern NppData nppData; extern VisualizerPanel _vizPanel; extern SubmenuManager _submenu; BOOL APIENTRY DllMain(HANDLE hModule, DWORD reasonForCall, LPVOID /*lpReserved*/) { switch (reasonForCall) { case DLL_PROCESS_ATTACH: pluginInit(hModule); break; case DLL_PROCESS_DETACH: pluginCleanUp(); break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; } return TRUE; } extern "C" __declspec(dllexport) void setInfo(NppData notpadPlusData) { nppData = notpadPlusData; commandMenuInit(); } extern "C" __declspec(dllexport) const TCHAR * getName() { return MENU_PANEL_NAME; } extern "C" __declspec(dllexport) FuncItem * getFuncsArray(int *nbF) { *nbF = MI_COUNT; return pluginMenuItems; } extern "C" __declspec(dllexport) void beNotified(SCNotification *notifyCode) { switch (notifyCode->nmhdr.code) { case NPPN_READY: _submenu.listSampleFiles(); break; case NPPN_BUFFERACTIVATED: _vizPanel.onBufferActivate(); break; case NPPN_TBMODIFICATION: { Utils::addToolbarIcon(MI_FWVIZ_PANEL, IDB_VIZ_TOOL_BTN_STD_FIELDS, IDI_VIZ_TOOL_BTN_FLUENT_FIELDS, IDI_VIZ_TOOL_BTN_DARK_FIELDS); break; } case NPPN_DARKMODECHANGED: NPPDM_QueryNPPDarkmode(); refreshDarkMode(); break; case SCN_UPDATEUI: if (notifyCode->updated & (SC_UPDATE_CONTENT | SC_UPDATE_SELECTION | SC_UPDATE_V_SCROLL)) _vizPanel.renderCurrentPage(); break; case NPPN_FILEBEFORECLOSE: _vizPanel.delDocInfo(static_cast<intptr_t>(notifyCode->nmhdr.idFrom)); break; case NPPN_SHUTDOWN: commandMenuCleanUp(); break; default: return; } } extern "C" __declspec(dllexport) LRESULT messageProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: _submenu.loadSampleFile(wParam, lParam); break; default: break; } return TRUE; } #ifdef UNICODE extern "C" __declspec(dllexport) BOOL isUnicode() { return TRUE; } #endif //UNICODE
3,077
C++
.cpp
94
27.468085
138
0.695064
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,100
PluginDefinition.cpp
shriprem_FWDataViz/src/PluginDefinition.cpp
//This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #include "PluginDefinition.h" #include "ConfigIO.h" #include "SubmenuManager.h" #include "Dialogs/VisualizerPanel.h" #ifdef UNICODE #define generic_itoa _itow #else #define generic_itoa itoa #endif FuncItem pluginMenuItems[MI_COUNT]; NppData nppData; HINSTANCE _gModule; ConfigIO _configIO; SubmenuManager _submenu; VisualizerPanel _vizPanel; void pluginInit(HANDLE hModule) { _gModule = (HINSTANCE)hModule; _vizPanel.init(_gModule, NULL); } void pluginCleanUp(){} void commandMenuInit() { _configIO.init(); NPPDM_InitDarkMode(nppData._nppHandle); ShortcutKey *shKeyOpen = new ShortcutKey; shKeyOpen->_isAlt = false; shKeyOpen->_isCtrl = true; shKeyOpen->_isShift = false; shKeyOpen->_key = VK_F8; setCommand(MI_FWVIZ_PANEL, MENU_SHOW_PANEL, ToggleVisualizerPanel, shKeyOpen, _vizPanel.isVisible()); setCommand(MI_CONFIG_DIALOG, MENU_CONFIG_FILE_TYPES, ShowConfigDialog); setCommand(MI_CONFIG_THEMES, MENU_CONFIG_THEMES, ShowThemeDialog); setCommand(MI_SEPARATOR_1, L"-", NULL); ShortcutKey *shKeyJump = new ShortcutKey; shKeyJump->_isAlt = true; shKeyJump->_isCtrl = true; shKeyJump->_isShift = false; shKeyJump->_key = VK_LEFT; setCommand(MI_FIELD_JUMP, MENU_FIELD_JUMP, ShowJumpDialog, shKeyJump); ShortcutKey *shKeyLeft = new ShortcutKey; shKeyLeft->_isAlt = true; shKeyLeft->_isCtrl = false; shKeyLeft->_isShift = false; shKeyLeft->_key = VK_LEFT; setCommand(MI_FIELD_LEFT, MENU_FIELD_LEFT, FieldLeft, shKeyLeft); ShortcutKey * shKeyRight = new ShortcutKey; shKeyRight->_isAlt = true; shKeyRight->_isCtrl = false; shKeyRight->_isShift = false; shKeyRight->_key = VK_RIGHT; setCommand(MI_FIELD_RIGHT, MENU_FIELD_RIGHT, FieldRight, shKeyRight); ShortcutKey *shKeyCopy = new ShortcutKey; shKeyCopy->_isAlt = true; shKeyCopy->_isCtrl = false; shKeyCopy->_isShift = false; shKeyCopy->_key = VK_OEM_COMMA; setCommand(MI_FIELD_COPY, MENU_FIELD_COPY, FieldCopy, shKeyCopy); ShortcutKey *shKeyPaste = new ShortcutKey; shKeyPaste->_isAlt = true; shKeyPaste->_isCtrl = false; shKeyPaste->_isShift = false; shKeyPaste->_key = VK_OEM_PERIOD; setCommand(MI_FIELD_PASTE, MENU_FIELD_PASTE, FieldPaste, shKeyPaste); setCommand(MI_DATA_EXTRACTION, MENU_DATA_EXTRACTION, ShowDataExtractDialog); setCommand(MI_SEPARATOR_2, L"-", NULL); setCommand(MI_DEMO_SINGLE_REC_FILES, MENU_DEMO_SINGLE_REC_FILES, NULL); setCommand(MI_DEMO_MULTI_REC_FILES, MENU_DEMO_MULTI_REC_FILES, NULL); setCommand(MI_DEMO_MULTI_LINE_FILES, MENU_DEMO_MULTI_LINE_FILES, NULL); setCommand(MI_SEPARATOR_3, L"-", NULL); setCommand(MI_ABOUT_DIALOG, MENU_ABOUT, ShowAboutDialog); } void commandMenuCleanUp() { delete pluginMenuItems[MI_FWVIZ_PANEL]._pShKey; delete pluginMenuItems[MI_FIELD_JUMP]._pShKey; delete pluginMenuItems[MI_FIELD_LEFT]._pShKey; delete pluginMenuItems[MI_FIELD_RIGHT]._pShKey; delete pluginMenuItems[MI_FIELD_COPY]._pShKey; delete pluginMenuItems[MI_FIELD_PASTE]._pShKey; } // Initialize plugin commands bool setCommand(size_t index, const wstring& cmdName, PFUNCPLUGINCMD pFunc, ShortcutKey *sk, bool checkOnInit) { if (index >= MI_COUNT) return false; if (!pFunc) return false; lstrcpy(pluginMenuItems[index]._itemName, cmdName.c_str()); pluginMenuItems[index]._pFunc = pFunc; pluginMenuItems[index]._pShKey = sk; pluginMenuItems[index]._init2Check = checkOnInit; return true; } HWND getCurrentScintilla() { int which{ -1 }; nppMessage(NPPM_GETCURRENTSCINTILLA, 0, (LPARAM)&which); if (which < 0) return (HWND)NULL; return (HWND)(which ? nppData._scintillaSecondHandle : nppData._scintillaMainHandle); } bool getDirectScintillaFunc(PSCIFUNC_T& fn, void*& ptr) { HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return FALSE; fn = (LRESULT(__cdecl*)(void*, int, WPARAM, LPARAM)) SendMessage(hScintilla, SCI_GETDIRECTFUNCTION, 0, 0); ptr = (void*) SendMessage(hScintilla, SCI_GETDIRECTPOINTER, 0, 0); return TRUE; } LRESULT nppMessage(UINT messageID, WPARAM wparam, LPARAM lparam) { return SendMessage(nppData._nppHandle, messageID, wparam, lparam); } // Dockable Visualizer Dialog void ShowVisualizerPanel(bool show) { if (show && !_vizPanel.isVisible()) { _vizPanel.setParent(nppData._nppHandle); tTbData data {}; if (!_vizPanel.isCreated()) { _vizPanel.create(&data); data.uMask = DWS_DF_CONT_RIGHT | DWS_ICONTAB | DWS_USEOWNDARKMODE; data.pszModuleName = _vizPanel.getPluginFileName(); data.dlgID = MI_FWVIZ_PANEL; data.pszName = MENU_PANEL_NAME; data.hIconTab = (HICON)::LoadImage(_gModule, MAKEINTRESOURCE(IDI_VIZ_TOOL_BTN_STD_FIELDS), IMAGE_ICON, 14, 14, LR_LOADMAP3DCOLORS | LR_LOADTRANSPARENT); nppMessage(NPPM_DMMREGASDCKDLG, 0, (LPARAM)&data); _vizPanel.initPanel(); } } _vizPanel.display(show); } void ToggleVisualizerPanel() { ShowVisualizerPanel(!_vizPanel.isVisible()); } void RefreshVisualizerPanel() { _vizPanel.loadListFileTypes(); _vizPanel.loadListThemes(); } void ShowConfigDialog() { _vizPanel.showConfigDialog(); } void ShowThemeDialog() { _vizPanel.showThemeDialog(); } void ShowJumpDialog() { _vizPanel.showJumpDialog(); } void FieldLeft() { _vizPanel.fieldLeft(); } void FieldRight() { _vizPanel.fieldRight(); } void FieldCopy() { _vizPanel.fieldCopy(); } void FieldPaste() { _vizPanel.fieldPaste(); } void ShowDataExtractDialog() { _vizPanel.showExtractDialog(); } void ShowAboutDialog() { _vizPanel.showAboutDialog(); } void refreshDarkMode() { if (_vizPanel.isCreated()) _vizPanel.refreshDarkMode(); }
6,446
C++
.cpp
174
33.5
119
0.733655
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,101
Utils.cpp
shriprem_FWDataViz/src/Utils.cpp
#include "Utils.h" extern HINSTANCE _gModule; extern FuncItem pluginMenuItems[MI_COUNT]; // ***************** PRIVATE ***************** enum fontStyle { FS_REGULAR, FS_BOLD, FS_ITALIC, FS_UNDERLINE }; bool changeFontStyle(HWND hDlg, int controlID, fontStyle style) { HWND hwndCtrl = GetDlgItem(hDlg, controlID); LOGFONT lf{ 0 }; HFONT hFont = (HFONT)SendMessage(hwndCtrl, WM_GETFONT, NULL, NULL); if (!GetObject(hFont, sizeof(lf), &lf)) return FALSE; switch (style) { case FS_REGULAR: lf.lfWeight = FW_REGULAR; lf.lfItalic = FALSE; lf.lfUnderline = FALSE; break; case FS_BOLD: lf.lfWeight = FW_BOLD; break; case FS_ITALIC: lf.lfItalic = TRUE; break; case FS_UNDERLINE: lf.lfUnderline = TRUE; break; } hFont = CreateFontIndirect(&lf); SendMessage(hwndCtrl, WM_SETFONT, (WPARAM)hFont, MAKELPARAM(true, 0)); return TRUE; } // ***************** PUBLIC ***************** int Utils::StringtoInt(const string& str, int base) { if (str.empty()) return 0; try { return stoi(str, nullptr, base); } catch (...) { return 0; } } int Utils::StringtoInt(const wstring& str, int base) { if (str.empty()) return 0; try { return stoi(str, nullptr, base); } catch (...) { return 0; } } LPCWSTR Utils::ToUpper(LPWSTR str) { return std::use_facet<std::ctype<wchar_t>>(std::locale()).toupper(str, str + wcslen(str)); } wstring Utils::NarrowToWide(const string& str) { return std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(str); } string Utils::WideToNarrow(const wstring& wStr) { return std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(wStr); } bool Utils::isInvalidRegex(const string& expr) { try { std::regex re(expr); } catch (const std::regex_error&) { return true; } return false; } bool Utils::isInvalidRegex(const wstring& expr, HWND hWnd, const wstring& context) { try { std::wregex re(expr); } catch (const std::regex_error& e) { MessageBox(hWnd, (context + ((!context.empty()) ? L"\r\n" : L"") + NarrowToWide(e.what())).c_str(), UTILS_REGEX_ERROR, MB_OK | MB_ICONERROR); return true; } return false; } COLORREF Utils::intToRGB(int color) { return RGB(GetRValue(color), GetGValue(color), GetBValue(color)); } wstring Utils::getSpecialFolder(int folderID) { TCHAR sFolderPath[MAX_PATH]{}; const HRESULT ret = SHGetFolderPath(NULL, folderID, NULL, SHGFP_TYPE_CURRENT, sFolderPath); return ((ret == S_OK) ? wstring{ sFolderPath } : L""); } wstring Utils::getKnownFolderPath(REFKNOWNFOLDERID folderID) { PWSTR path; const HRESULT ret = SHGetKnownFolderPath(folderID, KF_FLAG_DEFAULT, NULL, &path); if (ret != S_OK) return L""; wstring sFolderPath{ path }; CoTaskMemFree(path); return sFolderPath; } HWND Utils::addTooltip(HWND hDlg, int controlID, const wstring& pTitle, const wstring& pMessage, bool bBalloon) { if (!controlID || !hDlg || pMessage == L"") return FALSE; // Get the window of the tool. HWND hwndCtrl = GetDlgItem(hDlg, controlID); UINT ttsBalloon = bBalloon ? TTS_BALLOON : NULL; // Create the tooltip. HWND hwndTip = CreateWindowEx(NULL, TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_ALWAYSTIP | ttsBalloon, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hDlg, NULL, _gModule, NULL); if (!hwndCtrl || !hwndTip) return (HWND)NULL; // Associate the tooltip with the tool. TOOLINFO toolInfo{}; toolInfo.cbSize = sizeof(toolInfo); toolInfo.hwnd = hDlg; toolInfo.uFlags = TTF_IDISHWND | TTF_SUBCLASS; toolInfo.uId = (UINT_PTR)hwndCtrl; toolInfo.lpszText = (LPWSTR)pMessage.c_str(); SendMessage(hwndTip, TTM_ADDTOOL, 0, (LPARAM)&toolInfo); SendMessage(hwndTip, TTM_SETTITLE, TTI_INFO, (LPARAM)pTitle.c_str()); SendMessage(hwndTip, TTM_SETMAXTIPWIDTH, 0, (LPARAM)PREFS_TIP_MAX_WIDTH); return hwndTip; } HWND Utils::addTooltip(HWND hDlg, int controlID, const wstring& pTitle, const wstring& pMessage, int duration, bool bBalloon) { HWND hwndTip{ addTooltip(hDlg, controlID, pTitle, pMessage, bBalloon) }; SendMessage(hwndTip, TTM_SETDELAYTIME, TTDT_AUTOPOP, (LPARAM)(duration * 1000)); return hwndTip; } void Utils::updateTooltip(HWND hDlg, int controlID, HWND hTip, const wstring& pMessage) { TOOLINFO toolInfo{}; toolInfo.cbSize = sizeof(toolInfo); toolInfo.hwnd = hDlg; toolInfo.uId = (UINT_PTR)GetDlgItem(hDlg, controlID); toolInfo.lpszText = (LPWSTR)pMessage.c_str(); SendMessage(hTip, TTM_UPDATETIPTEXT, 0, (LPARAM)&toolInfo); } void Utils::addToolbarIcon(int menuIndex, int std, int fluent, int dark) { toolbarIconsWithDarkMode tbIcon{}; tbIcon.hToolbarBmp = LoadBitmap(_gModule, MAKEINTRESOURCE(std)); tbIcon.hToolbarIcon = LoadIcon(_gModule, MAKEINTRESOURCE(fluent)); tbIcon.hToolbarIconDarkMode = LoadIcon(_gModule, MAKEINTRESOURCE(dark)); nppMessage(NPPM_ADDTOOLBARICON_FORDARKMODE, pluginMenuItems[menuIndex]._cmdID, (LPARAM)&tbIcon); } void Utils::checkMenuItem(int menuIndex, bool check) { nppMessage(NPPM_SETMENUITEMCHECK, pluginMenuItems[menuIndex]._cmdID, check); } void Utils::showEditBalloonTip(HWND hEdit, LPCWSTR title, LPCWSTR text) { EDITBALLOONTIP tip{}; tip.cbStruct = sizeof(tip); tip.pszTitle = title; tip.pszText = text; tip.ttiIcon = TTI_ERROR; SendMessage(hEdit, EM_SHOWBALLOONTIP, NULL, (LPARAM)&tip); MessageBeep(MB_OK); } bool Utils::checkBaseOS(winVer os) { return (nppMessage(NPPM_GETWINDOWSVERSION) >= os); } float Utils::getNPPVersion() { long versionNum{ static_cast<long>(nppMessage(NPPM_GETNPPVERSION, TRUE)) }; return std::stof(to_wstring(HIWORD(versionNum)) + L"." + to_wstring(LOWORD(versionNum))); } bool Utils::checkKeyHeldDown(int vKey) { return (GetKeyState(vKey) & 0x8000) > 0; } wstring Utils::getListBoxItem(HWND hList, bool currentSelection, const int itemIndex) { int index{}; if (currentSelection) { index = static_cast<int>(SendMessage(hList, LB_GETCURSEL, 0, 0)); if (index == LB_ERR) return L""; } else index = itemIndex; int itemLength{ static_cast<int>(SendMessage(hList, LB_GETTEXTLEN, index, 0)) }; wstring itemText(itemLength + 1, '\0'); SendMessage(hList, LB_GETTEXT, index, (LPARAM)itemText.c_str()); return itemText; } void Utils::setComboBoxSelection(HWND hList, int index) { SendMessage(hList, CB_SETCURSEL, index, 0); InvalidateRect(hList, nullptr, FALSE); } bool Utils::getClipboardText(HWND hwnd, wstring& clipText) { bool bRet{ FALSE }; if (!IsClipboardFormatAvailable(CF_UNICODETEXT)) return bRet; if (!OpenClipboard(hwnd)) return bRet; HGLOBAL hglb = GetClipboardData(CF_UNICODETEXT); if (hglb != NULL) { LPTSTR lpClipData = (LPTSTR)GlobalLock(hglb); if (lpClipData != NULL) { bRet = TRUE; clipText = wstring{ lpClipData }; GlobalUnlock(hglb); } CloseClipboard(); } return bRet; } wstring Utils::getVersionInfo(LPCWSTR key) { wstring sVersionInfo; wchar_t sModuleFilePath[MAX_PATH]; DWORD verHandle{}; DWORD verSize{}; UINT querySize{}; LPTSTR lpBuffer{}; struct LANGANDCODEPAGE { WORD wLanguage; WORD wCodePage; } *lpTranslate{}; GetModuleFileName(_gModule, sModuleFilePath, MAX_PATH); verSize = GetFileVersionInfoSize(sModuleFilePath, &verHandle); if (verSize < 1) return L""; string versionData(verSize, '\0'); if (!GetFileVersionInfo(sModuleFilePath, NULL, verSize, versionData.data())) return L""; VerQueryValue(versionData.data(), L"\\VarFileInfo\\Translation", (VOID FAR* FAR*)& lpTranslate, &querySize); wstring verSubBlock(100, '\0'); swprintf(verSubBlock.data(), 100, L"\\StringFileInfo\\%04X%04X\\%s", lpTranslate[0].wLanguage, lpTranslate[0].wCodePage, key); if (VerQueryValue(versionData.data(), verSubBlock.c_str(), (VOID FAR* FAR*)& lpBuffer, &querySize) && querySize) sVersionInfo = wstring{ lpBuffer }; return sVersionInfo; } void Utils::loadBitmap(HWND hDlg, int controlID, int resource) { HWND hwndCtrl = GetDlgItem(hDlg, controlID); HBITMAP hBitmap = LoadBitmap(_gModule, MAKEINTRESOURCE(resource)); if (hBitmap) { SendMessage(hwndCtrl, BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap); DeleteObject(hBitmap); } } void Utils::setFont(HWND hDlg, int controlID, wstring& name, int height, int weight, bool italic, bool underline) { HWND hwndCtrl = GetDlgItem(hDlg, controlID); LOGFONT lf{ 0 }; wcscpy(lf.lfFaceName, name.c_str()); HDC hdc = GetDC(hDlg); lf.lfHeight = -MulDiv(height, GetDeviceCaps(hdc, LOGPIXELSY), 72); ReleaseDC(hDlg, hdc); lf.lfWeight = weight; lf.lfItalic = italic; lf.lfUnderline = underline; HFONT hFont = CreateFontIndirect(&lf); SendMessage(hwndCtrl, WM_SETFONT, (WPARAM)hFont, MAKELPARAM(true, 0)); } bool Utils::setFontRegular(HWND hDlg, int controlID) { return changeFontStyle(hDlg, controlID, FS_REGULAR); } bool Utils::setFontBold(HWND hDlg, int controlID) { return changeFontStyle(hDlg, controlID, FS_BOLD); } bool Utils::setFontItalic(HWND hDlg, int controlID) { return changeFontStyle(hDlg, controlID, FS_ITALIC); } bool Utils::setFontUnderline(HWND hDlg, int controlID) { return changeFontStyle(hDlg, controlID, FS_UNDERLINE); } int Utils::scaleDPIX(int x) { HDC hdc = GetDC(NULL); if (!hdc) return 0; int scaleX{ MulDiv(x, GetDeviceCaps(hdc, LOGPIXELSX), 96) }; ReleaseDC(NULL, hdc); return scaleX; } int Utils::scaleDPIY(int y) { HDC hdc = GetDC(NULL); if (!hdc) return 0; int scaleY{ MulDiv(y, GetDeviceCaps(hdc, LOGPIXELSY), 96) }; ReleaseDC(NULL, hdc); return scaleY; } int Utils::getTextPixelWidth(HWND hDlg, const wstring& text) { SIZE textSize{}; HDC hDC{ GetDC(hDlg) }; SelectObject(hDC, (HFONT)SendMessage(hDlg, WM_GETFONT, 0, 0)); GetTextExtentPoint32(hDC, text.c_str(), static_cast<int>(text.length()), &textSize); ReleaseDC(hDlg, hDC); return textSize.cx; } bool Utils::checkDirectoryExists(LPCWSTR lpDirPath) { DWORD dwAttrib = GetFileAttributes(lpDirPath); return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); } bool Utils::checkFileExists(LPCWSTR lpFilePath) { DWORD dwAttrib = GetFileAttributes(lpFilePath); return (dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); }
10,644
C++
.cpp
294
31.972789
127
0.696237
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,102
ConfigIO.cpp
shriprem_FWDataViz/src/ConfigIO.cpp
#include "ConfigIO.h" void ConfigIO::init() { TCHAR sPluginDirectory[MAX_PATH]{}; nppMessage(NPPM_GETPLUGINHOMEPATH, MAX_PATH, (LPARAM)sPluginDirectory); PathAppend(sPluginDirectory, PLUGIN_FOLDER_NAME); nppMessage(NPPM_GETPLUGINSCONFIGDIR, MAX_PATH, (LPARAM)pluginConfigDir); // If no existing config path, create it if (!Utils::checkDirectoryExists(pluginConfigDir)) CreateDirectory(pluginConfigDir, NULL); // If no existing config folder for this plugin, create it PathAppend(pluginConfigDir, PLUGIN_FOLDER_NAME); if (!Utils::checkDirectoryExists(pluginConfigDir)) CreateDirectory(pluginConfigDir, NULL); // If no existing config backup folder for this plugin, create it PathCombine(pluginConfigBackupDir, pluginConfigDir, L"Backup\\"); if (!Utils::checkDirectoryExists(pluginConfigBackupDir)) CreateDirectory(pluginConfigBackupDir, NULL); // Reconcile config files const wstring sDefaultPrefix{ L"default_" }; TCHAR sDefaultsFile[MAX_PATH]; TCHAR sConfigFile[MAX_PATH]; TCHAR sThemeDatFile[MAX_PATH]; // Rename any existing Themes.dat file to Themes.ini PathCombine(sThemeDatFile, pluginConfigDir, L"Themes.dat"); PathCombine(sConfigFile, pluginConfigDir, L"Themes.ini"); if (Utils::checkFileExists(sThemeDatFile) && !Utils::checkFileExists(sConfigFile)) MoveFile(sThemeDatFile, sConfigFile); // If config files are missing, copy them from the plugins folder for (int i{}; i < CONFIG_FILE_COUNT; ++i) { PathCombine(sConfigFile, pluginConfigDir, CONFIG_FILES[i].c_str()); WCONFIG_FILE_PATHS[i] = wstring{ sConfigFile }; CONFIG_FILE_PATHS[i] = Utils::WideToNarrow(sConfigFile); if (!Utils::checkFileExists(sConfigFile)) { PathCombine(sDefaultsFile, sPluginDirectory, (sDefaultPrefix + CONFIG_FILES[i]).c_str()); CopyFile(sDefaultsFile, sConfigFile, TRUE); } } // initialize instance variables userVizConfig(); PathCombine(defaultConfigFile, sPluginDirectory, (sDefaultPrefix + CONFIG_FILES[CONFIG_VIZ]).c_str()); PathCombine(defaultThemeFile, sPluginDirectory, (sDefaultPrefix + CONFIG_FILES[CONFIG_THEMES]).c_str()); PathCombine(defaultFoldStructFile, sPluginDirectory, (sDefaultPrefix + CONFIG_FILES[CONFIG_FOLDSTRUCTS]).c_str()); } int ConfigIO::setVizConfig(const string& docFileType) { int sectionCount{}; string sectionList{}; if (docFileType.empty()) { userVizConfig(); return 0; } sectionCount = getConfigAllSections(sectionList, CONFIG_FILE_PATHS[CONFIG_VIZ]); if (sectionCount > 0 && sectionList.find(docFileType) != string::npos) { userVizConfig(); return 1; } sectionCount = getConfigAllSections(sectionList, Utils::WideToNarrow(defaultConfigFile)); if (sectionCount > 0 && sectionList.find(docFileType) != string::npos) { defaultVizConfig(); return 2; } userVizConfig(); return -1; } void ConfigIO::userVizConfig() { wCurrentConfigFile = WCONFIG_FILE_PATHS[CONFIG_VIZ]; currentConfigFile = CONFIG_FILE_PATHS[CONFIG_VIZ]; wCurrentThemeFile = WCONFIG_FILE_PATHS[CONFIG_THEMES]; wCurrentFoldStructFile = WCONFIG_FILE_PATHS[CONFIG_FOLDSTRUCTS]; } void ConfigIO::defaultVizConfig() { wCurrentConfigFile = wstring{ defaultConfigFile }; currentConfigFile = Utils::WideToNarrow(defaultConfigFile); wCurrentThemeFile = wstring{ defaultThemeFile }; wCurrentFoldStructFile = wstring{ defaultFoldStructFile }; } wstring ConfigIO::getConfigFile(CF_TYPES cfType) { if (cfType < 0 || cfType >= CONFIG_FILE_COUNT) return L""; return WCONFIG_FILE_PATHS[cfType]; } wstring ConfigIO::getActiveConfigFile(CF_TYPES cfType) { switch (cfType) { case CONFIG_VIZ: return wCurrentConfigFile; case CONFIG_THEMES: return wCurrentThemeFile; case CONFIG_FOLDSTRUCTS: return wCurrentFoldStructFile; default: return WCONFIG_FILE_PATHS[cfType]; } } string ConfigIO::getConfigStringA(const string& section, const string& key, const string& defaultVal, string file) const { const int bufSize{ FW_LINE_MAX_LENGTH }; string ftBuf(bufSize, '\0'); if (file.empty()) file = currentConfigFile; GetPrivateProfileStringA(section.c_str(), key.c_str(), defaultVal.c_str(), ftBuf.data(), bufSize, file.c_str()); return string{ ftBuf.c_str()}; } string ConfigIO::getConfigStringA(const wstring& section, const string& key, const string& defaultVal, wstring file) const { return getConfigStringA(Utils::WideToNarrow(section), key, defaultVal, Utils::WideToNarrow(file)); } wstring ConfigIO::getConfigWideChar(const string& section, const string& key, const string& defaultVal, string file) const { return Utils::NarrowToWide(getConfigStringA(section, key, defaultVal, file)); } wstring ConfigIO::getConfigWideChar(const wstring& section, const string& key, const string& defaultVal, wstring file) const { return Utils::NarrowToWide(getConfigStringA(section, key, defaultVal, file)); } void ConfigIO::setConfigStringA(const string& section, const string& key, const string& value, string file) const { if (file.empty()) file = currentConfigFile; WritePrivateProfileStringA(section.c_str(), key.c_str(), value.c_str(), file.c_str()); } void ConfigIO::setConfigMultiByte(const string& section, const string& key, const wstring& value, string file) const { setConfigStringA(section, key, Utils::WideToNarrow(value), file); } int ConfigIO::getConfigInt(const string& section, const string& key, const int& defaultVal, string file) const { string defVal{ to_string(defaultVal) }; return Utils::StringtoInt(getConfigStringA(section, key, defVal, file)); } int ConfigIO::getConfigInt(const wstring& section, const string& key, const int& defaultVal, wstring file) const { string defVal{ to_string(defaultVal) }; return Utils::StringtoInt(getConfigStringA(section, key, defVal, file)); } wstring ConfigIO::getStyleValue(const wstring& theme, const string& styleName, wstring file) const { return getConfigWideChar(theme, styleName, "", (file.empty()) ? wCurrentThemeFile : file); } void ConfigIO::getFullStyle(const wstring& theme, const string& styleName, StyleInfo& style, wstring file) const { wstring val = getStyleValue(theme, styleName, file); if (val.length() < 16) { style.backColor = static_cast<int>(nppMessage(NPPM_GETEDITORDEFAULTBACKGROUNDCOLOR)); style.foreColor = static_cast<int>(nppMessage(NPPM_GETEDITORDEFAULTFOREGROUNDCOLOR)); style.bold = 1; style.italics = 1; return; } style.backColor = Utils::StringtoInt(val.substr(0, 6), 16); style.foreColor = Utils::StringtoInt(val.substr(7, 6), 16); style.bold = Utils::StringtoInt(val.substr(14, 1)); style.italics = Utils::StringtoInt(val.substr(15, 1)); } string ConfigIO::getFieldStyleText(const wstring& fieldName) const { return getConfigStringA("Styles", Utils::WideToNarrow(fieldName), "", CONFIG_FILE_PATHS[CONFIG_FIELD_TYPES]); } void ConfigIO::parseFieldStyle(const string& styleText, StyleInfo& style) { if (styleText.length() != 16) return; style.backColor = Utils::StringtoInt(styleText.substr(0, 6), 16); style.foreColor = Utils::StringtoInt(styleText.substr(7, 6), 16); style.bold = Utils::StringtoInt(styleText.substr(14, 1)); style.italics = Utils::StringtoInt(styleText.substr(15, 1)); } int ConfigIO::getFoldStructCount(wstring file) const { if (file.empty()) file = wCurrentFoldStructFile; return Utils::StringtoInt(getConfigStringA(L"Base", "FoldStructCount", "0", file)); } string ConfigIO::getFoldStructValueA(string foldStructType, string key, wstring file) const { if (file.empty()) file = wCurrentFoldStructFile; return getConfigStringA(foldStructType, key, "", Utils::WideToNarrow(file)); } string ConfigIO::getFoldStructValue(wstring foldStructType, string key, wstring file) const { if (file.empty()) file = wCurrentFoldStructFile; return getConfigStringA(foldStructType, key, "", file); } void ConfigIO::getFoldStructFoldingInfo(wstring foldStructType, vector<FoldingInfo>& vFoldInfo, wstring file) { if (file.empty()) file = wCurrentFoldStructFile; string headerRecs{ getFoldStructValue(foldStructType, "HeaderRecords", file) }; vector<string> headerRecList{}; int headerCount{ Tokenize(headerRecs, headerRecList) }; vFoldInfo.clear(); vFoldInfo.resize(headerCount); for (int i{}; i < headerCount; ++i) { int recTypeIndex{ Utils::StringtoInt(headerRecList[i].substr(3))}; vFoldInfo[i].recTypeIndex = recTypeIndex; vFoldInfo[i].priority = getConfigInt(foldStructType, headerRecList[i] + "_Priority", 0, file); vFoldInfo[i].recursive = (getConfigStringA(foldStructType, headerRecList[i] + "_Recursive", "N", file) == "Y"); vFoldInfo[i].endRecords = getConfigWideChar(foldStructType, headerRecList[i] + "_EndRecords", "", file); } } wstring ConfigIO::getPreference(const string key, const string defaultVal) const { return getConfigWideChar("Preferences", key, defaultVal, CONFIG_FILE_PATHS[CONFIG_PREFS]); } void ConfigIO::setPreference(const string key, const wstring value) const { setConfigStringA("Preferences", key.c_str(), Utils::WideToNarrow(value.c_str()), CONFIG_FILE_PATHS[CONFIG_PREFS].c_str()); } bool ConfigIO::getPreferenceBool(const string key, const bool defaultVal) const { return getConfigStringA("Preferences", key, defaultVal ? "Y" : "N", CONFIG_FILE_PATHS[CONFIG_PREFS]) == "Y"; } void ConfigIO::setPreferenceBool(const string key, const bool value) const { setConfigStringA("Preferences", key, value ? "Y" : "N", CONFIG_FILE_PATHS[CONFIG_PREFS]); } int ConfigIO::getPreferenceInt(const string key, const int defaultVal) const { return getConfigInt("Preferences", key, defaultVal, CONFIG_FILE_PATHS[CONFIG_PREFS]); } void ConfigIO::setPreferenceInt(const string key, const int value) const { setConfigStringA("Preferences", key, to_string(value), CONFIG_FILE_PATHS[CONFIG_PREFS]); } void ConfigIO::setPanelMBCharState(UINT state) const { setConfigStringA("Preferences", "PanelMBCharState", (state == BST_INDETERMINATE) ? "FT" : ((state == BST_CHECKED) ? "Y" : "N"), CONFIG_FILE_PATHS[CONFIG_PREFS]); } bool ConfigIO::getMultiByteLexing(string fileType) const { string state{ getConfigStringA("Preferences", "PanelMBCharState", "FT", CONFIG_FILE_PATHS[CONFIG_PREFS]) }; if (state == "FT") return (getConfigStringA(fileType, "MultiByteChars", "N", currentConfigFile) == "Y"); else return (state == "Y"); } int ConfigIO::getConfigAllSections(string& sections, string file) { const int bufSize{ FW_LINE_MAX_LENGTH }; string ftBuf(bufSize, '\0'); DWORD charCount{}; charCount = GetPrivateProfileStringA(NULL, "", "", ftBuf.data(), bufSize, file.c_str()); if (charCount < 1) return 0; int sectionCount{}; for (unsigned int i{}; i < charCount; ++i) { if (ftBuf[i] == 0) { ftBuf[i] = ','; ++sectionCount; } } sections = ftBuf.c_str(); return sectionCount; } int ConfigIO::getConfigAllSectionsList(vector<string>& sectionsList, string file) { string sections{}; int sectionCount{ getConfigAllSections(sections, file) }; if (sectionCount < 1) return 0; return Tokenize(sections, sectionsList); } int ConfigIO::getConfigAllSectionsList(vector<wstring>& sectionsList, wstring file) { string sections{}; int sectionCount{ getConfigAllSections(sections, Utils::WideToNarrow(file)) }; if (sectionCount < 1) return 0; return Tokenize(Utils::NarrowToWide(sections), sectionsList); } int ConfigIO::getConfigAllKeys(const string& section, string& keys, const string file) { const int bufSize{ FW_LINE_MAX_LENGTH }; string keyBuf(bufSize, '\0'); DWORD charCount{}; charCount = GetPrivateProfileStringA(section.c_str(), NULL, "", keyBuf.data(), bufSize, file.c_str()); if (charCount < 1) return 0; int keyCount{}; for (unsigned int i{}; i < charCount; ++i) { if (keyBuf[i] == 0) { keyBuf[i] = ','; ++keyCount; } } keys = keyBuf.c_str(); return keyCount; } int ConfigIO::getConfigAllKeysList(const string& section, vector<string>& keysList, const string file) { string keys{}; int keyCount{ getConfigAllKeys(section, keys, file) }; if (keyCount < 1) return 0; return Tokenize(keys, keysList); } int ConfigIO::getConfigAllKeysList(const string& section, vector<wstring>& keysList, const string file) { string keys{}; int keyCount{ getConfigAllKeys(section, keys, file) }; if (keyCount < 1) return 0; return Tokenize(Utils::NarrowToWide(keys), keysList); } int ConfigIO::getConfigValueList(vector<string>& valList, const string& section, const string& key, const string& defaultVal, string file) { return Tokenize(getConfigStringA(section, key, defaultVal, file), valList); } int ConfigIO::getThemesList(vector<wstring>& valList, wstring file) { if (file.empty()) file = wCurrentThemeFile; return Tokenize(getConfigWideChar(L"Base", "Themes", "", file), valList); } int ConfigIO::Tokenize(const string& text, vector<string>& results, const string& delim) { std::size_t nStart{}, nEnd; results.clear(); if (text.empty()) return 0; while ((nEnd = text.find(delim, nStart)) != string::npos) { if (nEnd > nStart) results.emplace_back(text.substr(nStart, nEnd - nStart)); nStart = nEnd + 1; } if (nStart < text.length()) results.emplace_back(text.substr(nStart)); return static_cast<int>(results.size()); } int ConfigIO::Tokenize(const wstring& text, vector<wstring>& results, const wstring& delim) { std::size_t nStart{}, nEnd; results.clear(); if (text.empty()) return 0; while ((nEnd = text.find(delim, nStart)) != wstring::npos) { if (nEnd > nStart) results.emplace_back(text.substr(nStart, nEnd - nStart)); nStart = nEnd + 1; } if (nStart < text.length()) results.emplace_back(text.substr(nStart)); return static_cast<int>(results.size()); } int ConfigIO::Tokenize(const string& text, vector<int>& results, const string& delim) { vector<string> interims; results.clear(); if (text.empty()) return 0; Tokenize(text, interims, delim); for (string istr : interims) results.emplace_back(Utils::StringtoInt(istr)); return static_cast<int>(results.size()); } void ConfigIO::ActivateNewLineTabs(wstring& str) { str = std::regex_replace(str, std::wregex(L"\\\\n"), L"\n"); str = std::regex_replace(str, std::wregex(L"\\\\t"), L"\t"); } void ConfigIO::deleteKey(const string& section, const string& key, string file) const { if (file.empty()) file = currentConfigFile; WritePrivateProfileStringA(section.c_str(), key.c_str(), NULL, file.c_str()); } void ConfigIO::deleteKey(const wstring& section, const wstring& key, wstring file) const { if (file.empty()) file = wCurrentConfigFile; WritePrivateProfileString(section.c_str(), key.c_str(), NULL, file.c_str()); } void ConfigIO::deleteSection(const string& section, string file) { WritePrivateProfileStringA(section.c_str(), NULL, NULL, file.c_str()); } string ConfigIO::readConfigFile(wstring file) const { if (file.empty()) file = wCurrentConfigFile; using std::ios; if (std::ifstream ifs{ file, ios::binary | ios::ate }) { int size = static_cast<int>(ifs.tellg()); string str(size, '\0'); ifs.seekg(0); ifs.read(str.data(), size); return str; } return ""; } bool ConfigIO::queryConfigFileName(HWND hwnd, bool bOpen, bool backupFolder, wstring& backupConfigFile) const { OPENFILENAME ofn; TCHAR filePath[MAX_PATH]{}; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hwnd; ofn.lpstrFile = filePath; ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = sizeof(filePath); ofn.lpstrFilter = L"All\0*.*\0Ini Files\0*.ini\0"; ofn.lpstrDefExt = L"ini"; ofn.nFilterIndex = 2; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrTitle = bOpen ? FWVIZ_OPEN_BKUP_CONFIG_DLG : FWVIZ_SAVE_BKUP_CONFIG_DLG; ofn.Flags = bOpen ? (OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST) : OFN_OVERWRITEPROMPT; if (backupFolder) ofn.lpstrInitialDir = pluginConfigBackupDir; else { wstring desktopPath = Utils::getKnownFolderPath(FOLDERID_Desktop); ofn.lpstrInitialDir = desktopPath.c_str(); } BOOL bOK = bOpen ? GetOpenFileName(&ofn) : GetSaveFileName(&ofn); if (bOK) backupConfigFile = ofn.lpstrFile; return bOK; } void ConfigIO::saveConfigFile(const wstring& fileData, wstring file) { using std::ios; if (std::ofstream fs{ file, ios::out | ios::binary | ios::trunc }) { string mbFileData{ Utils::WideToNarrow(fileData) }; fs.write(mbFileData.data(), mbFileData.length()); } flushConfigFile(); } int ConfigIO::getBackupTempFileName(wstring& tempFileName) const { TCHAR tmpFilePath[MAX_PATH]; if (GetTempFileName(pluginConfigBackupDir, L"FWViz_", 0, tmpFilePath) == 0) { tempFileName = L""; return -1; } tempFileName = tmpFilePath; return 0; } void ConfigIO::backupConfigFile(wstring file) const { using fsp = std::filesystem::path; char backupFile[MAX_PATH + 1]; wchar_t backupFilePath[MAX_PATH + 1]; wstring backupTemplate{ wstring{ fsp(file).stem().c_str() }.substr(0, 30) }; backupTemplate += L"_%Y%m%d_%H%M%S" + wstring{fsp(file).extension().c_str()}; time_t rawTime; struct tm* timeInfo; time(&rawTime); timeInfo = localtime(&rawTime); strftime(backupFile, MAX_PATH, Utils::WideToNarrow(backupTemplate).c_str(), timeInfo); PathCombine(backupFilePath, pluginConfigBackupDir, Utils::NarrowToWide(backupFile).c_str()); CopyFile(file.c_str(), backupFilePath, FALSE); } void ConfigIO::viewBackupFolder() const { ShellExecute(NULL, L"open", pluginConfigBackupDir, NULL, NULL, SW_SHOWNORMAL); } bool ConfigIO::checkConfigFilesforUTF8() { bool status{ true }; if (!fixIfNotUTF8File(WCONFIG_FILE_PATHS[CONFIG_VIZ])) status = false; if (!fixIfNotUTF8File(WCONFIG_FILE_PATHS[CONFIG_THEMES])) status = false; if (!fixIfNotUTF8File(WCONFIG_FILE_PATHS[CONFIG_FOLDSTRUCTS])) status = false; return status; } bool ConfigIO::fixIfNotUTF8File(CF_TYPES cfType) { if (cfType < 0 || cfType >= CONFIG_FILE_COUNT) return false; return fixIfNotUTF8File(WCONFIG_FILE_PATHS[cfType]); } ConfigIO::ENC_TYPE ConfigIO::getBOM(wstring file) { using std::ios; if (std::wifstream fs{ file, ios::binary }) { unsigned short bom[3]{}; bom[0] = fs.get(); bom[1] = fs.get(); bom[2] = fs.get(); fs.close(); if (bom[0] == 0xFF && bom[1] == 0xFE) return UCS16_LE; else if (bom[0] == 0xFE && bom[1] == 0xFF) return UCS16_BE; else if (bom[0] == 0xEF && bom[1] == 0xBB && bom[2] == 0xBF) return UTF8_BOM; } return UTF8; } bool ConfigIO::fixIfNotUTF8File(wstring file) { using std::ios; ENC_TYPE encoding{ getBOM(file) }; if (encoding == UTF8) return true; backupConfigFile(file); switch (encoding) { case UTF8_BOM: if (std::ifstream ifs{ file, ios::binary | ios::ate }) { int size = static_cast<int>(ifs.tellg()) - 3; string str(size, '\0'); ifs.seekg(3); ifs.read(str.data(), size); ifs.close(); string mbData{ str.c_str() }; if (std::ofstream ofs{ file, ios::out | ios::binary | ios::trunc}) { ofs.write(mbData.c_str(), mbData.length()); } } break; case UCS16_BE: case UCS16_LE: if (std::wifstream wifs{ file, ios::binary | ios::ate }) { wifs.imbue(std::locale(wifs.getloc(), new std::codecvt_utf16<wchar_t, 0x10FFFF, std::consume_header>)); int size = static_cast<int>(wifs.tellg()); wstring wstr(size, '\0'); wifs.seekg(0); wifs.read(wstr.data(), size); wifs.close(); string mbData{ Utils::WideToNarrow(wstr).c_str() }; if (std::ofstream ofs{ file, ios::out | ios::binary | ios::trunc }) { ofs.write(mbData.c_str(), mbData.length()); } } break; } return (getBOM(file) == UTF8); } void ConfigIO::flushConfigFile() { WritePrivateProfileString(NULL, NULL, NULL, NULL); }
20,410
C++
.cpp
461
39.809111
126
0.708721
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,103
AboutDialog.cpp
shriprem_FWDataViz/src/Dialogs/AboutDialog.cpp
#include "AboutDialog.h" void AboutDialog::doDialog(HINSTANCE hInst) { if (!isCreated()) { Window::init(hInst, nppData._nppHandle); create(IDD_ABOUT_DIALOG); } localize(); goToCenter(); SendMessage(_hParent, NPPM_DMMSHOW, 0, (LPARAM)_hSelf); } void AboutDialog::refreshDarkMode() { NPPDM_AutoThemeChildControls(_hSelf); redraw(); } void AboutDialog::localize() { #ifdef _WIN64 wstring buildBit{ L" (64-bit)" }; #else wstring buildBit{ L" (32-bit)" }; #endif // _WIN64 SetWindowText(_hSelf, ABOUT_DIALOG_TITLE); SetDlgItemText(_hSelf, IDC_ABOUT_NAME, getVersionInfo(L"FileDescription").c_str()); SetDlgItemText(_hSelf, IDC_ABOUT_VERSION, (L"Version: " + getVersionInfo(L"FileVersion") + buildBit).c_str()); SetDlgItemTextA(_hSelf, IDC_ABOUT_BUILD_TIME, ("Build time: " + string(__DATE__) + " - " + string(__TIME__)).c_str()); SetDlgItemText(_hSelf, IDC_ABOUT_ATTRIBUTION, getVersionInfo(L"LegalCopyright").c_str()); SetDlgItemText(_hSelf, IDOK, ABOUT_BTN_LABEL_OK); } INT_PTR CALLBACK AboutDialog::run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: NPPDM_InitSysLink(GetDlgItem(_hSelf, IDC_ABOUT_PROD_URL)); NPPDM_AutoSubclassAndThemeChildControls(_hSelf); break; case WM_COMMAND: switch LOWORD(wParam) { case IDCANCEL: case IDOK: display(FALSE); return TRUE; } break; case WM_NOTIFY: switch (((LPNMHDR)lParam)->code) { case NM_CLICK: case NM_RETURN: ShellExecute(NULL, L"open", getVersionInfo(L"CompanyName").c_str(), NULL, NULL, SW_SHOW); display(FALSE); return TRUE; } break; case WM_CTLCOLORDLG: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLORSTATIC: if (GetDlgCtrlID((HWND)lParam) == IDC_ABOUT_PROD_URL) { return NPPDM_OnCtlColorSysLink(reinterpret_cast<HDC>(wParam)); } if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker((HDC)wParam); } break; case WM_PRINTCLIENT: if (NPPDM_IsEnabled()) return TRUE; break; } return FALSE; }
2,270
C++
.cpp
71
26.408451
98
0.655204
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,104
FieldTypeDialog.cpp
shriprem_FWDataViz/src/Dialogs/FieldTypeDialog.cpp
#include "FieldTypeDialog.h" void FieldTypeDialog::doDialog(HINSTANCE hInst) { if (!isCreated()) { Window::init(hInst, nppData._nppHandle); create(IDD_FIELD_TYPE_DEFINER_DIALOG); } initComponent(_hSelf); fieldDefConfigFile = Utils::WideToNarrow(_configIO.getConfigFile(_configIO.CONFIG_FIELD_TYPES)); hFieldsLB = GetDlgItem(_hSelf, IDC_FIELD_TYPE_LIST_BOX); SendDlgItemMessage(_hSelf, IDC_FIELD_TYPE_DESC_EDIT, EM_LIMITTEXT, MAX_PATH, NULL); Utils::loadBitmap(_hSelf, IDC_FIELD_TYPE_INFO_BUTTON, IDB_VIZ_INFO_BITMAP); Utils::addTooltip(_hSelf, IDC_FIELD_TYPE_INFO_BUTTON, L"", VIZ_PANEL_INFO_TIP, FALSE); if constexpr(_gLanguage != LANG_ENGLISH) localize(); goToCenter(); SendMessage(_hParent, NPPM_DMMSHOW, 0, (LPARAM)_hSelf); fillFields(); } void FieldTypeDialog::refreshDarkMode() { NPPDM_AutoThemeChildControls(_hSelf); redraw(); } INT_PTR FieldTypeDialog::run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: switch LOWORD(wParam) { case IDC_FIELD_TYPE_LIST_BOX: switch HIWORD(wParam) { case LBN_SELCHANGE: onFieldSelect(); break; } break; case IDC_FIELD_TYPE_INFO_BUTTON: ShellExecute(NULL, L"open", FIELD_TYPE_INFO_README, NULL, NULL, SW_SHOW); break; case IDC_FIELD_TYPE_DESC_EDIT: switch HIWORD(wParam) { case EN_CHANGE: if (!loadingEdits) { cleanStyleDefs = FALSE; enableFieldSelection(); } break; } break; case IDC_FIELD_TYPE_NEW_BTN: fieldEditNew(); break; case IDC_FIELD_TYPE_CLONE_BTN: fieldEditClone(); break; case IDC_FIELD_TYPE_DEL_BTN: fieldEditDelete(); break; case IDC_STYLE_DEF_BACK_EDIT: case IDC_STYLE_DEF_FORE_EDIT: switch (HIWORD(wParam)) { case EN_CHANGE: bool back = (LOWORD(wParam) == IDC_STYLE_DEF_BACK_EDIT); setStyleDefColor(FALSE, getStyleDefColor(back), back); if (!loadingEdits) { cleanStyleDefs = FALSE; enableFieldSelection(); } break; } break; case IDC_STYLE_DEF_BACKCOLOR: chooseStyleDefColor(TRUE); break; case IDC_STYLE_DEF_FORECOLOR: chooseStyleDefColor(FALSE); break; case IDC_STYLE_DEF_BOLD: case IDC_STYLE_DEF_ITALICS: setOutputFontStyle(); cleanStyleDefs = FALSE; enableFieldSelection(); break; case IDC_STYLE_DEF_PREVIEW_BOX: setPangram(); break; case IDC_FIELD_STYLE_DEF_SAVE_BTN: styleDefSave(); break; case IDC_FIELD_STYLE_DEF_RESET_BTN: (newFieldDef) ? fieldEditDelete() : onFieldSelect(); break; case IDCANCEL: case IDCLOSE: display(FALSE); return TRUE; case IDC_JUMP_FIELD_LIST: switch HIWORD(wParam) { case CBN_SELCHANGE: break; } break; } break; case WM_CTLCOLORSTATIC: if (styleDefColor) { INT_PTR ptr = colorStaticControl(wParam, lParam); if (ptr != NULL) return ptr; } switch (GetDlgCtrlID((HWND)lParam)) { case IDC_FIELD_TYPE_REGEX_LABEL: return NPPDM_OnCtlColorIfEnabled(reinterpret_cast<HDC>(wParam), FALSE); default: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } } break; case WM_CTLCOLORDLG: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLOREDIT: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorSofter(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLORLISTBOX: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorListbox(wParam, lParam); } break; case WM_PRINTCLIENT: if (NPPDM_IsEnabled()) return TRUE; break; case WM_INITDIALOG: NPPDM_AutoSubclassAndThemeChildControls(_hSelf); break; } return FALSE; } void FieldTypeDialog::localize() { SetWindowText(_hSelf, FIELD_TYPE_DEF_DLG_TITLE); SetDlgItemText(_hSelf, IDC_FIELD_TYPE_GROUP_BOX, FIELD_TYPE_GROUP_BOX); SetDlgItemText(_hSelf, IDC_FIELD_TYPE_NEW_BTN, FIELD_TYPE_NEW_BTN); SetDlgItemText(_hSelf, IDC_FIELD_TYPE_CLONE_BTN, FIELD_TYPE_CLONE_BTN); SetDlgItemText(_hSelf, IDC_FIELD_TYPE_DEL_BTN, FIELD_TYPE_DEL_BTN); SetDlgItemText(_hSelf, IDC_FIELD_TYPE_DESC_LABEL, FIELD_TYPE_DESC_LABEL); SetDlgItemText(_hSelf, IDC_FIELD_TYPE_REGEX_LABEL, FIELD_TYPE_REGEX_LABEL); SetDlgItemText(_hSelf, IDC_FIELD_STYLE_DEF_SAVE_BTN, FIELD_STYLE_DEF_SAVE_BTN); SetDlgItemText(_hSelf, IDC_FIELD_STYLE_DEF_RESET_BTN, FIELD_STYLE_DEF_RESET_BTN); StyleDefComponent::localize(); } int FieldTypeDialog::getCurrentFieldIndex() const { int idxFT; idxFT = static_cast<int>(SendMessage(hFieldsLB, LB_GETCURSEL, NULL, NULL)); if (idxFT == LB_ERR) return LB_ERR; return idxFT; } string FieldTypeDialog::getNewStyle() { int backColor{ static_cast<int>(nppMessage(NPPM_GETEDITORDEFAULTBACKGROUNDCOLOR)) }; int foreColor{ static_cast<int>(nppMessage(NPPM_GETEDITORDEFAULTFOREGROUNDCOLOR)) }; char styleDef[17]; snprintf(styleDef, 17, "%06X %06X 00", backColor, foreColor); return string{ styleDef }; } string FieldTypeDialog::getStyleConfig() { int backColor{ getStyleDefColor(TRUE) }; int foreColor{ getStyleDefColor(FALSE) }; bool bold{ (IsDlgButtonChecked(_hSelf, IDC_STYLE_DEF_BOLD) == BST_CHECKED) }; bool italics{ (IsDlgButtonChecked(_hSelf, IDC_STYLE_DEF_ITALICS) == BST_CHECKED) }; char styleDef[15]; snprintf(styleDef, 15, "%06X %06X ", backColor, foreColor); return string{ styleDef } + (bold ? "1" : "0") + (italics ? "1" : "0"); } void FieldTypeDialog::fillFields() { SendMessage(hFieldsLB, LB_RESETCONTENT, NULL, NULL); int keyCount{}; vector<wstring> keyList{}; keyCount = _configIO.getConfigAllKeysList("Styles", keyList, fieldDefConfigFile); if (keyCount < 1) { fieldEditNew(); return; } for (int i{}; i < keyCount; ++i) { SendMessage(hFieldsLB, LB_ADDSTRING, NULL, (LPARAM)keyList[i].c_str()); } SendMessage(hFieldsLB, LB_SETCURSEL, 0, NULL); onFieldSelect(); } void FieldTypeDialog::onFieldSelect() { int idxFT{ getCurrentFieldIndex() }; if (idxFT == LB_ERR) return; wstring label(MAX_PATH, '\0'); SendMessage(hFieldsLB, LB_GETTEXT, idxFT, (LPARAM)label.c_str()); label = label.c_str(); fieldDefLabel = label; fieldDefRegex = _configIO.getConfigWideChar("Validations", Utils::WideToNarrow(label), "", fieldDefConfigFile); fieldDefStyle = _configIO.getConfigStringA("Styles", Utils::WideToNarrow(label), "", fieldDefConfigFile); fillStyleDefs(); } void FieldTypeDialog::enableFieldSelection() { EnableWindow(GetDlgItem(_hSelf, IDC_FIELD_TYPE_LIST_BOX), cleanStyleDefs); EnableWindow(GetDlgItem(_hSelf, IDC_FIELD_TYPE_NEW_BTN), cleanStyleDefs); EnableWindow(GetDlgItem(_hSelf, IDC_FIELD_TYPE_CLONE_BTN), cleanStyleDefs); wstring fieldLabel(MAX_PATH + 1, '\0'); GetDlgItemText(_hSelf, IDC_FIELD_TYPE_DESC_EDIT, fieldLabel.data(), MAX_PATH + 1); EnableWindow(GetDlgItem(_hSelf, IDC_FIELD_STYLE_DEF_SAVE_BTN), !wstring(fieldLabel.c_str()).empty()); if (cleanStyleDefs) { SetDlgItemText(_hSelf, IDC_FIELD_STYLE_DEF_SAVE_BTN, FIELD_STYLE_DEF_SAVE_BTN); Utils::setFontRegular(_hSelf, IDC_FIELD_STYLE_DEF_SAVE_BTN); } else { SetDlgItemText(_hSelf, IDC_FIELD_STYLE_DEF_SAVE_BTN, (wstring(FIELD_STYLE_DEF_SAVE_BTN) + L"*").c_str()); Utils::setFontBold(_hSelf, IDC_FIELD_STYLE_DEF_SAVE_BTN); } } void FieldTypeDialog::fieldEditNew() { SendMessage(hFieldsLB, LB_ADDSTRING, NULL, (LPARAM)L""); int lbLast{ static_cast<int>(SendMessage(hFieldsLB, LB_GETCOUNT, NULL, NULL)) - 1 }; SendMessage(hFieldsLB, LB_SETCURSEL, lbLast, NULL); fieldDefLabel = L""; fieldDefRegex = L""; fieldDefStyle = getNewStyle(); fillStyleDefs(); newFieldDef = TRUE; cleanStyleDefs = FALSE; enableFieldSelection(); } void FieldTypeDialog::fieldEditClone() { fieldDefLabel += L"_clone"; SendMessage(hFieldsLB, LB_ADDSTRING, NULL, (LPARAM)fieldDefLabel.c_str()); int lbLast{ static_cast<int>(SendMessage(hFieldsLB, LB_GETCOUNT, NULL, NULL)) - 1 }; SendMessage(hFieldsLB, LB_SETCURSEL, lbLast, NULL); fillStyleDefs(); newFieldDef = TRUE; cleanStyleDefs = FALSE; enableFieldSelection(); } void FieldTypeDialog::fieldEditDelete() { int idxFT{ getCurrentFieldIndex() }; if (idxFT == LB_ERR) return; if (!newFieldDef) { _configIO.deleteKey("Styles", Utils::WideToNarrow(fieldDefLabel), fieldDefConfigFile); //>>_configIO.deleteKey("Validations", Utils::WideToNarrow(fieldDefLabel), fieldDefConfigFile); } SendMessage(hFieldsLB, LB_DELETESTRING, idxFT, NULL); int lbLast{ static_cast<int>(SendMessage(hFieldsLB, LB_GETCOUNT, NULL, NULL)) - 1 }; if (lbLast < 0) { fieldEditNew(); return; } SendMessage(hFieldsLB, LB_SETCURSEL, ((idxFT <= lbLast) ? idxFT : lbLast), NULL); newFieldDef = FALSE; onFieldSelect(); } void FieldTypeDialog::setStyleDefColor(bool setEdit, int color, bool back) { loadingEdits = TRUE; StyleDefComponent::setStyleDefColor(setEdit, color, back); loadingEdits = FALSE; } void FieldTypeDialog::fillStyleDefs() { loadingEdits = TRUE; SetDlgItemText(_hSelf, IDC_FIELD_TYPE_DESC_EDIT, fieldDefLabel.c_str()); //>>SetDlgItemText(_hSelf, IDC_FIELD_TYPE_REGEX_EDIT, fieldDefRegex.c_str()); loadingEdits = FALSE; if (fieldDefStyle.length() != 16) fieldDefStyle = getNewStyle(); StyleInfo style{}; _configIO.parseFieldStyle(fieldDefStyle, style); StyleDefComponent::fillStyleDefs(style); enableFieldSelection(); } void FieldTypeDialog::styleDefSave() { if (cleanStyleDefs) return; int idxFT{ getCurrentFieldIndex() }; if (idxFT == LB_ERR) return; wchar_t fieldLabel[MAX_PATH + 1]; GetDlgItemText(_hSelf, IDC_FIELD_TYPE_DESC_EDIT, fieldLabel, MAX_PATH + 1); if (wstring{ fieldLabel }.empty()) return; wchar_t fieldRegex[MAX_PATH + 1]; GetDlgItemText(_hSelf, IDC_FIELD_TYPE_REGEX_EDIT, fieldRegex, MAX_PATH + 1); if (!newFieldDef) { _configIO.deleteKey("Styles", Utils::WideToNarrow(fieldDefLabel), fieldDefConfigFile); //>>_configIO.deleteKey("Validations", Utils::WideToNarrow(fieldDefLabel), fieldDefConfigFile); } fieldDefLabel = fieldLabel; fieldDefRegex = fieldRegex; fieldDefStyle = getStyleConfig(); _configIO.setConfigStringA("Styles", Utils::WideToNarrow(fieldDefLabel), fieldDefStyle, fieldDefConfigFile); //>>_configIO.setConfigStringA("Validations", Utils::WideToNarrow(fieldDefLabel), fieldDefStyle, fieldDefConfigFile); SendMessage(hFieldsLB, LB_DELETESTRING, idxFT, NULL); SendMessage(hFieldsLB, LB_INSERTSTRING, idxFT, (LPARAM)fieldLabel); SendMessage(hFieldsLB, LB_SETCURSEL, idxFT, NULL); newFieldDef = FALSE; cleanStyleDefs = TRUE; enableFieldSelection(); } void FieldTypeDialog::chooseStyleDefColor(bool back) { StyleDefComponent::chooseStyleDefColor(back); enableFieldSelection(); }
11,512
C++
.cpp
299
32.511706
120
0.683052
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,105
VisualizerPanel.cpp
shriprem_FWDataViz/src/Dialogs/VisualizerPanel.cpp
#include "VisualizerPanel.h" #include "ConfigureDialog.h" #include "ThemeDialog.h" #include "PreferencesDialog.h" #include "JumpToField.h" #include "DataExtractDialog.h" #include "FoldStructDialog.h" #include "AboutDialog.h" #include <WindowsX.h> extern HINSTANCE _gModule; extern SubmenuManager _submenu; extern FuncItem pluginMenuItems[MI_COUNT]; ConfigureDialog _configDlg; ThemeDialog _themeDlg; PreferencesDialog _prefsDlg; JumpToField _jumpDlg; DataExtractDialog _dataExtractDlg; FoldStructDialog _foldStructDlg; AboutDialog _aboutDlg; INT_PTR CALLBACK VisualizerPanel::run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: switch LOWORD(wParam) { case IDC_VIZPANEL_FILETYPE_SELECT: switch HIWORD(wParam) { case CBN_SELCHANGE: if (SendMessage(hFTList, CB_GETCURSEL, 0, 0) > 0) visualizeFile("", FALSE, FALSE, FALSE); else clearVisualize(FALSE); break; } break; case IDC_VIZPANEL_INFO_BUTTON: { #if FW_DEBUG_DOC_INFO wstring docInfoStr{}; for (const DocInfo DI : docInfoList) { docInfoStr = docInfoStr + L"File Path: " + DI.fileName + L"\r\nFileType: " + Utils::NarrowToWide(DI.docType) + L"\r\nTheme: " + Utils::NarrowToWide(DI.docTheme) + L"\r\n==================================\r\n"; } MessageBox(_hSelf, docInfoStr.c_str(), L"", MB_OK); #else ShellExecute(NULL, L"open", VIZPANEL_INFO_README, NULL, NULL, SW_SHOW); #endif // FW_DEBUG_DOC_INFO } break; case IDC_VIZPANEL_FILE_SAMPLES_BTN: popupSamplesMenu(); break; case IDC_VIZPANEL_FILETYPE_CONFIG: showConfigDialog(); break; case IDC_VIZPANEL_THEME_SELECT: switch HIWORD(wParam) { case CBN_SELCHANGE: visualizeTheme(); break; } break; case IDC_VIZPANEL_THEME_CONFIG: showThemeDialog(); break; case IDC_VIZPANEL_CLEAR_BTN: if (_configIO.getPreferenceBool(PREF_CLEARVIZ_AUTO, FALSE)) { CheckDlgButton(_hSelf, IDC_VIZPANEL_AUTO_DETECT_FT, BST_UNCHECKED); setADFTCheckbox(); } SendMessage(hFTList, CB_SETCURSEL, (WPARAM)-1, 0); clearVisualize(FALSE); break; case IDCANCEL: case IDCLOSE: setFocusOnEditor(); display(FALSE); break; case IDC_VIZPANEL_PREFERENCES_BTN: _prefsDlg.doDialog((HINSTANCE)_gModule); break; case IDC_VIZPANEL_AUTO_DETECT_FT: setADFTCheckbox(); break; case IDC_VIZPANEL_MCBS_OVERRIDE: setPanelMBCharState(); break; case IDC_VIZPANEL_DEFAULT_BACKGROUND: setDefaultBackground(); break; case IDC_VIZPANEL_SHOW_CALLTIP: setShowCalltip(); break; case IDC_VIZPANEL_FIELD_COPY_TRIM: _configIO.setPreferenceBool(PREF_COPY_TRIM, IsDlgButtonChecked(_hSelf, IDC_VIZPANEL_FIELD_COPY_TRIM) == BST_CHECKED); break; case IDC_VIZPANEL_JUMP_FIELD_BTN: showJumpDialog(); break; case IDC_VIZPANEL_FIELD_LEFT_BUTTON: fieldLeft(); setFocusOnEditor(); break; case IDC_VIZPANEL_FIELD_RIGHT_BUTTON: fieldRight(); setFocusOnEditor(); break; case IDC_VIZPANEL_FIELD_COPY_BUTTON: fieldCopy(); setFocusOnEditor(); break; case IDC_VIZPANEL_FIELD_PASTE_BUTTON: fieldPaste(); setFocusOnEditor(); break; case IDC_VIZPANEL_PASTE_LEFT_LABEL: case IDC_VIZPANEL_PASTE_RPAD_LABEL: setFieldAlign(TRUE); break; case IDC_VIZPANEL_PASTE_RIGHT_LABEL: case IDC_VIZPANEL_PASTE_LPAD_LABEL: setFieldAlign(FALSE); break; case IDC_VIZPANEL_PASTE_RPAD_FIELD: case IDC_VIZPANEL_PASTE_LPAD_FIELD: { int ctrlID{ LOWORD(wParam) }; bool leftEdge{ ctrlID == IDC_VIZPANEL_PASTE_RPAD_FIELD }; switch HIWORD(wParam) { case EN_CHANGE: wchar_t padChars[MAX_PATH]; GetWindowText(GetDlgItem(_hSelf, ctrlID), padChars, MAX_PATH); _configIO.setPreference(leftEdge ? PREF_PASTE_RPAD : PREF_PASTE_LPAD, padChars); break; case EN_SETFOCUS: setFieldAlign(leftEdge); break; } break; } case IDC_VIZPANEL_EXTRACT_DATA_BTN: if (_configIO.fixIfNotUTF8File(_configIO.CONFIG_EXTRACTS)) showExtractDialog(); break; case IDC_VIZPANEL_FOLD_INFO_BUTTON: ShellExecute(NULL, L"open", VIZPANEL_FOLD_INFO_README, NULL, NULL, SW_SHOW); break; case IDC_VIZPANEL_FOLDING_APPLY_BTN: if (_configIO.fixIfNotUTF8File(_configIO.CONFIG_FOLDSTRUCTS)) { setDocFolded(FALSE); applyFolding(""); } setFocusOnEditor(); break; case IDC_VIZPANEL_FOLDING_REMOVE_BTN: removeFolding(); setFocusOnEditor(); break; case IDC_VIZPANEL_FOLDING_DEFINE_BTN: showFoldStructDialog(); break; case IDC_VIZPANEL_FOLDING_FOLD_BTN: foldLevelMenu(); break; case IDC_VIZPANEL_FOLDING_TOGGLE_BTN: toggleFolding(); setFocusOnEditor(); break; case IDC_VIZPANEL_FOLDING_UNFOLD_BTN: unfoldLevelMenu(); break; case IDC_VIZPANEL_ABOUT_BUTTON: showAboutDialog(); break; case IDC_VIZPANEL_FILE_INFO_BUTTON: { wstring fileList = _configIO.getActiveConfigFile(_configIO.CONFIG_VIZ) + L"\n" + _configIO.getActiveConfigFile(_configIO.CONFIG_THEMES) + L"\n" + _configIO.getActiveConfigFile(_configIO.CONFIG_FOLDSTRUCTS) + L"\n" + wstring(80, '-') + VIZ_PANEL_FILE_INFO_TIP; Utils::updateTooltip(_hSelf, IDC_VIZPANEL_FILE_INFO_BUTTON, hTipIniFiles, fileList.data()); break; } } break; case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: SetFocus(hFTList); break; case WM_SHOWWINDOW: Utils::checkMenuItem(MI_FWVIZ_PANEL, wParam); if (wParam) visualizeFile("", TRUE, TRUE, TRUE); break; case WM_NOTIFY: { LPNMHDR pnmh = reinterpret_cast<LPNMHDR>(lParam); if (pnmh->hwndFrom == _hParent && LOWORD(pnmh->code) == DMN_CLOSE) { display(FALSE); unlexed = (_configIO.getPreferenceBool(PREF_CLEARVIZ_PANEL, FALSE)); if (unlexed) clearVisualize(FALSE); } break; } case WM_SIZE: onPanelResize(lParam); break; case WM_INITDIALOG: NPPDM_AutoSubclassAndThemeChildControls(_hSelf); break; case WM_CTLCOLORDLG: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLOREDIT: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorSofter(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLORSTATIC: switch (GetDlgCtrlID((HWND)lParam)) { case IDC_VIZPANEL_THEME_LABEL: return NPPDM_OnCtlColorIfEnabled(reinterpret_cast<HDC>(wParam), themeEnabled); case IDC_VIZPANEL_PASTE_LEFT_LABEL: case IDC_VIZPANEL_PASTE_RIGHT_LABEL: case IDC_VIZPANEL_PASTE_RPAD_LABEL: case IDC_VIZPANEL_PASTE_LPAD_LABEL: return NPPDM_OnCtlColorIfEnabled(reinterpret_cast<HDC>(wParam), fieldEnabled); case IDC_VIZPANEL_PASTE_RPAD_INDIC: case IDC_VIZPANEL_PASTE_LPAD_INDIC: return NPPDM_OnCtlHiliteIfEnabled(reinterpret_cast<HDC>(wParam), fieldEnabled); default: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } } break; case WM_CTLCOLORLISTBOX: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorListbox(wParam, lParam); } break; case WM_PRINTCLIENT: if (NPPDM_IsEnabled()) return TRUE; break; default: return DockingDlgInterface::run_dlgProc(message, wParam, lParam); } return FALSE; } void VisualizerPanel::initPanel() { bool recentOS = Utils::checkBaseOS(WV_VISTA); wstring fontName = recentOS ? L"Consolas" : L"Courier New"; int fontHeight = recentOS ? 10 : 8; using Utils::addTooltip; using Utils::loadBitmap; using Utils::setFont; utf8Config = _configIO.checkConfigFilesforUTF8(); if (!utf8Config) return; PreferencesDialog::applyFoldLineColorAlpha(); setFont(_hSelf, IDC_VIZPANEL_FIELD_LABEL, fontName, fontHeight, FW_BOLD, FALSE, TRUE); setFont(_hSelf, IDC_VIZPANEL_FIELD_INFO, fontName, fontHeight); loadBitmap(_hSelf, IDC_VIZPANEL_INFO_BUTTON, IDB_VIZ_INFO_BITMAP); addTooltip(_hSelf, IDC_VIZPANEL_INFO_BUTTON, L"", VIZ_PANEL_INFO_TIP, FALSE); loadBitmap(_hSelf, IDC_VIZPANEL_FILE_SAMPLES_BTN, IDB_VIZ_FILE_SAMPLES_BITMAP); addTooltip(_hSelf, IDC_VIZPANEL_FILE_SAMPLES_BTN, L"", VIZ_PANEL_FILE_SAMPLES_TIP, FALSE); loadBitmap(_hSelf, IDC_VIZPANEL_FILETYPE_CONFIG, IDB_VIZ_FILE_CONFIG_BITMAP); addTooltip(_hSelf, IDC_VIZPANEL_FILETYPE_CONFIG, L"", VIZ_PANEL_FILE_CONFIG_TIP, FALSE); loadBitmap(_hSelf, IDC_VIZPANEL_THEME_CONFIG, IDB_VIZ_COLOR_CONFIG_BITMAP); addTooltip(_hSelf, IDC_VIZPANEL_THEME_CONFIG, L"", VIZ_PANEL_THEME_CONFIG_TIP, FALSE); SetWindowText(GetDlgItem(_hSelf, IDC_VIZPANEL_PASTE_RPAD_FIELD), _configIO.getPreference(PREF_PASTE_RPAD).c_str()); SetWindowText(GetDlgItem(_hSelf, IDC_VIZPANEL_PASTE_LPAD_FIELD), _configIO.getPreference(PREF_PASTE_LPAD).c_str()); addTooltip(_hSelf, IDC_VIZPANEL_CLEAR_BTN, L"", VIZ_PANEL_CLEAR_BTN_TIP, FW_TIP_MEDIUM, TRUE); addTooltip(_hSelf, IDC_VIZPANEL_FIELD_COPY_TRIM, L"", VIZ_PANEL_FIELD_TRIM_TIP, FW_TIP_SHORT, TRUE); addTooltip(_hSelf, IDC_VIZPANEL_FIELD_LEFT_BUTTON, L"", VIZ_PANEL_FIELD_LEFT_TIP, FW_TIP_SHORT, TRUE); hTipHopRight = addTooltip(_hSelf, IDC_VIZPANEL_FIELD_RIGHT_BUTTON, L"", _configIO.getPreferenceBool(PREF_HOP_RT_LEFT_EDGE, FALSE) ? VIZ_PANEL_FLD_ALT_RIGHT_TIP : VIZ_PANEL_FIELD_RIGHT_TIP, FW_TIP_SHORT, TRUE); addTooltip(_hSelf, IDC_VIZPANEL_FIELD_COPY_BUTTON, L"", VIZ_PANEL_FIELD_COPY_TIP, FW_TIP_MEDIUM, TRUE); addTooltip(_hSelf, IDC_VIZPANEL_FIELD_PASTE_BUTTON, L"", VIZ_PANEL_FIELD_PASTE_TIP, FW_TIP_LONG, TRUE); addTooltip(_hSelf, IDC_VIZPANEL_PASTE_LEFT_LABEL, L"", VIZ_PANEL_FIELD_RPAD_TIP, FW_TIP_LONG, TRUE); addTooltip(_hSelf, IDC_VIZPANEL_PASTE_RPAD_LABEL, L"", VIZ_PANEL_FIELD_RPAD_TIP, FW_TIP_LONG, TRUE); addTooltip(_hSelf, IDC_VIZPANEL_PASTE_RPAD_INDIC, L"", VIZ_PANEL_FIELD_RPAD_TIP, FW_TIP_LONG, TRUE); addTooltip(_hSelf, IDC_VIZPANEL_PASTE_RIGHT_LABEL, L"", VIZ_PANEL_FIELD_LPAD_TIP, FW_TIP_LONG, TRUE); addTooltip(_hSelf, IDC_VIZPANEL_PASTE_LPAD_LABEL, L"", VIZ_PANEL_FIELD_LPAD_TIP, FW_TIP_LONG, TRUE); addTooltip(_hSelf, IDC_VIZPANEL_PASTE_LPAD_INDIC, L"", VIZ_PANEL_FIELD_LPAD_TIP, FW_TIP_LONG, TRUE); loadBitmap(_hSelf, IDC_VIZPANEL_FOLD_INFO_BUTTON, IDB_VIZ_INFO_BITMAP); addTooltip(_hSelf, IDC_VIZPANEL_FOLD_INFO_BUTTON, L"", VIZ_PANEL_INFO_TIP, FALSE); loadBitmap(_hSelf, IDC_VIZPANEL_FILE_INFO_BUTTON, IDB_VIZ_INI_FILES_BITMAP); hTipIniFiles = addTooltip(_hSelf, IDC_VIZPANEL_FILE_INFO_BUTTON, VIZ_PANEL_FILE_INFO_TITLE, VIZ_PANEL_FILE_INFO_TIP, FW_TIP_MEDIUM, TRUE); loadBitmap(_hSelf, IDC_VIZPANEL_ABOUT_BUTTON, IDB_VIZ_ABOUT_BITMAP); addTooltip(_hSelf, IDC_VIZPANEL_ABOUT_BUTTON, L"", ABOUT_DIALOG_TITLE, TRUE); setFont(_hSelf, IDC_VIZPANEL_MCBS_OVERRIDE_IND, fontName, 9); if constexpr(_gLanguage != LANG_ENGLISH) localize(); } void VisualizerPanel::localize() { SetWindowText(_hSelf, MENU_PANEL_NAME); SetDlgItemText(_hSelf, IDC_VIZPANEL_FILETYPE_LABEL, VIZ_PANEL_FILETYPE_LABEL); SetDlgItemText(_hSelf, IDC_VIZPANEL_THEME_LABEL, VIZ_PANEL_THEME_LABEL); SetDlgItemText(_hSelf, IDC_VIZPANEL_CLEAR_BTN, VIZ_PANEL_CLEAR_BUTTON); SetDlgItemText(_hSelf, IDCLOSE, VIZ_PANEL_CLOSE); SetDlgItemText(_hSelf, IDC_VIZPANEL_PREFERENCES_BTN, VIZ_PANEL_PREFERENCES); SetDlgItemText(_hSelf, IDC_VIZPANEL_AUTO_DETECT_FT, VIZ_PANEL_AUTO_DETECT_FT); SetDlgItemText(_hSelf, IDC_VIZPANEL_MCBS_OVERRIDE, VIZ_PANEL_MCBS_OVERRIDE); SetDlgItemText(_hSelf, IDC_VIZPANEL_DEFAULT_BACKGROUND, VIZPANEL_DEFAULT_BACKGROUND); SetDlgItemText(_hSelf, IDC_VIZPANEL_SHOW_CALLTIP, VIZPANEL_SHOW_CALLTIP); SetDlgItemText(_hSelf, IDC_VIZPANEL_FIELD_COPY_TRIM, VIZ_PANEL_FIELD_COPY_TRIM); SetDlgItemText(_hSelf, IDC_VIZPANEL_FIELD_LABEL, VIZ_PANEL_FIELD_LABEL); SetDlgItemText(_hSelf, IDC_VIZPANEL_JUMP_FIELD_BTN, VIZ_PANEL_JUMP_FIELD_BTN); SetDlgItemText(_hSelf, IDC_VIZPANEL_EXTRACT_DATA_BTN, VIZ_PANEL_EXTRACT_DATA_BTN); SetDlgItemText(_hSelf, IDC_VIZPANEL_FIELD_COPY_BUTTON, VIZ_PANEL_FIELD_COPY_BTN); SetDlgItemText(_hSelf, IDC_VIZPANEL_FIELD_PASTE_BUTTON, VIZ_PANEL_FIELD_PASTE_BTN); SetDlgItemText(_hSelf, IDC_VIZPANEL_PASTE_LEFT_LABEL, VIZ_PANEL_PASTE_LEFT_LABEL); SetDlgItemText(_hSelf, IDC_VIZPANEL_PASTE_RIGHT_LABEL, VIZ_PANEL_PASTE_RIGHT_LABEL); SetDlgItemText(_hSelf, IDC_VIZPANEL_PASTE_RPAD_LABEL, VIZ_PANEL_PASTE_RPAD_LABEL); SetDlgItemText(_hSelf, IDC_VIZPANEL_PASTE_LPAD_LABEL, VIZ_PANEL_PASTE_LPAD_LABEL); SetDlgItemText(_hSelf, IDC_VIZPANEL_FOLDING_GROUP_BOX, VIZPANEL_FOLD_GROUP_BOX); SetDlgItemText(_hSelf, IDC_VIZPANEL_FOLDING_APPLY_BTN, VIZPANEL_FOLD_APPLY_BTN); SetDlgItemText(_hSelf, IDC_VIZPANEL_FOLDING_REMOVE_BTN, VIZPANEL_FOLD_REMOVE_BTN); SetDlgItemText(_hSelf, IDC_VIZPANEL_FOLDING_DEFINE_BTN, VIZPANEL_FOLD_DEFINE_BTN); SetDlgItemText(_hSelf, IDC_VIZPANEL_FOLDING_FOLD_BTN, VIZPANEL_FOLD_FOLD_BTN); SetDlgItemText(_hSelf, IDC_VIZPANEL_FOLDING_TOGGLE_BTN, VIZPANEL_FOLD_TOGGLE_BTN); SetDlgItemText(_hSelf, IDC_VIZPANEL_FOLDING_UNFOLD_BTN, VIZPANEL_FOLD_UNFOLD_BTN); } void VisualizerPanel::display(bool toShow) { DockingDlgInterface::display(toShow); if (!utf8Config) return; panelMounted = toShow; if (!toShow) { if (_configDlg.isCreated() && _configDlg.isVisible()) _configDlg.display(FALSE); if (_themeDlg.isCreated() && _themeDlg.isVisible()) _themeDlg.display(FALSE); if (_prefsDlg.isCreated() && _prefsDlg.isVisible()) _prefsDlg.display(FALSE); if (_jumpDlg.isCreated() && _jumpDlg.isVisible()) _jumpDlg.display(FALSE); if (_dataExtractDlg.isCreated() && _dataExtractDlg.isVisible()) _dataExtractDlg.display(FALSE); if (_foldStructDlg.isCreated() && _foldStructDlg.isVisible()) _foldStructDlg.display(FALSE); if (_aboutDlg.isCreated() && _aboutDlg.isVisible()) _aboutDlg.display(FALSE); unlexed = (_configIO.getPreferenceBool(PREF_CLEARVIZ_PANEL, FALSE)); if (unlexed) clearVisualize(FALSE); return; } hFTList = GetDlgItem(_hSelf, IDC_VIZPANEL_FILETYPE_SELECT); hThemesLB = GetDlgItem(_hSelf, IDC_VIZPANEL_THEME_SELECT); hFieldInfo = GetDlgItem(_hSelf, IDC_VIZPANEL_FIELD_INFO); CheckDlgButton(_hSelf, IDC_VIZPANEL_AUTO_DETECT_FT, _configIO.getPreferenceBool(PREF_ADFT) ? BST_CHECKED : BST_UNCHECKED); initMBCharsCheckbox(); CheckDlgButton(_hSelf, IDC_VIZPANEL_DEFAULT_BACKGROUND, _configIO.getPreferenceBool(PREF_DEF_BACKGROUND, FALSE) ? BST_CHECKED : BST_UNCHECKED); CheckDlgButton(_hSelf, IDC_VIZPANEL_SHOW_CALLTIP, _configIO.getPreferenceBool(PREF_SHOW_CALLTIP, FALSE) ? BST_CHECKED : BST_UNCHECKED); CheckDlgButton(_hSelf, IDC_VIZPANEL_FIELD_COPY_TRIM, _configIO.getPreferenceBool(PREF_COPY_TRIM, FALSE) ? BST_CHECKED : BST_UNCHECKED); unlexed = TRUE; visualizeFile("", TRUE, TRUE, TRUE); if (unlexed) SetFocus(hFTList); else setFocusOnEditor(); } void VisualizerPanel::refreshDarkMode() { NPPDM_AutoThemeChildControls(_hSelf); redraw(); SendMessage(GetDlgItem(_hSelf, IDC_PREF_FOLD_LINE_ALPHA_SLIDER), TBM_SETRANGEMIN, FALSE, 0); if (_configDlg.isCreated()) _configDlg.refreshDarkMode(); if (_themeDlg.isCreated()) _themeDlg.refreshDarkMode(); if (_prefsDlg.isCreated()) _prefsDlg.refreshDarkMode(); if (_jumpDlg.isCreated()) _jumpDlg.refreshDarkMode(); if (_dataExtractDlg.isCreated()) _dataExtractDlg.refreshDarkMode(); if (_foldStructDlg.isCreated()) _foldStructDlg.refreshDarkMode(); if (_aboutDlg.isCreated()) _aboutDlg.refreshDarkMode(); } void VisualizerPanel::initMBCharsCheckbox() { int showMCBS{ _configIO.getPreferenceBool(PREF_MBCHARS_SHOW, FALSE) ? SW_SHOW : SW_HIDE }; ShowWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_MCBS_OVERRIDE), showMCBS); ShowWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_MCBS_OVERRIDE_IND), showMCBS); wstring mbcState{ _configIO.getPreference(PREF_MBCHARS_STATE, "FT") }; if (mbcState == L"FT") CheckDlgButton(_hSelf, IDC_VIZPANEL_MCBS_OVERRIDE, BST_INDETERMINATE); else CheckDlgButton(_hSelf, IDC_VIZPANEL_MCBS_OVERRIDE, (mbcState == L"Y") ? BST_CHECKED : BST_UNCHECKED); } void VisualizerPanel::updateHopRightTip() { Utils::updateTooltip(_hSelf, IDC_VIZPANEL_FIELD_RIGHT_BUTTON, hTipHopRight, (_configIO.getPreferenceBool(PREF_HOP_RT_LEFT_EDGE, FALSE)) ? VIZ_PANEL_FLD_ALT_RIGHT_TIP : VIZ_PANEL_FIELD_RIGHT_TIP); } void VisualizerPanel::setParent(HWND parent2set) { _hParent = parent2set; } void VisualizerPanel::loadListFileTypes() { SendMessage(hFTList, CB_RESETCONTENT, NULL, NULL); if (!utf8Config) return; vector<string> fileTypes; int ftCount{ _configIO.getConfigValueList(fileTypes, "Base", "FileTypes") }; vFileTypes.clear(); vFileTypes.resize(ftCount); SendMessage(hFTList, CB_ADDSTRING, NULL, (LPARAM)L"-"); for (int i{}; i < ftCount; ++i) { wstring fileLabel{ _configIO.getConfigWideChar(fileTypes[i], "FileLabel") }; vFileTypes[i].fileType = fileTypes[i]; vFileTypes[i].fileLabel = fileLabel; SendMessage(hFTList, CB_ADDSTRING, NULL, (LPARAM)fileLabel.c_str()); } } void VisualizerPanel::loadListThemes() const { SendMessage(hThemesLB, CB_RESETCONTENT, NULL, NULL); if (!utf8Config) return; vector<wstring> themesList; _configIO.getThemesList(themesList); for (const wstring theme : themesList) { SendMessage(hThemesLB, CB_ADDSTRING, NULL, (LPARAM)theme.c_str()); } } void VisualizerPanel::syncListFileTypes() { if (!panelMounted) return; HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; string fileType; getDocFileType(fileType); if (fileType.empty()) { if (_configIO.getPreferenceBool(PREF_ADFT)) detectFileType(hScintilla, fileType); } else _configIO.setVizConfig(fileType); loadListFileTypes(); if (!fileType.empty()) { Utils::setComboBoxSelection(hFTList, static_cast<int>( SendMessage(hFTList, CB_FINDSTRING, (WPARAM)-1, (LPARAM)_configIO.getConfigWideChar(fileType, "FileLabel").c_str()))); } enableThemeList(!fileType.empty()); } void VisualizerPanel::syncListThemes() { wstring theme; getDocTheme(theme); loadListThemes(); Utils::setComboBoxSelection(hThemesLB, theme.empty() ? -1 : static_cast<int>(SendMessage(hThemesLB, CB_FINDSTRING, (WPARAM)-1, (LPARAM)theme.c_str()))); } void VisualizerPanel::enableFieldControls(bool enable) { if (!isVisible()) return; EnableWindow(hFieldInfo, enable); bool recEnabled{ enable && (caretRecordRegIndex >= 0) }; EnableWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_JUMP_FIELD_BTN), recEnabled); EnableWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_EXTRACT_DATA_BTN), recEnabled); EnableWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_FIELD_LEFT_BUTTON), recEnabled); EnableWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_FIELD_RIGHT_BUTTON), recEnabled); fieldEnabled = recEnabled && (caretFieldIndex >= 0); EnableWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_FIELD_COPY_BUTTON), fieldEnabled); EnableWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_FIELD_PASTE_BUTTON), fieldEnabled); EnableWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_PASTE_RPAD_FIELD), fieldEnabled); EnableWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_PASTE_LPAD_FIELD), fieldEnabled); InvalidateRect(GetDlgItem(_hSelf, IDC_VIZPANEL_PASTE_RPAD_INDIC), nullptr, TRUE); InvalidateRect(GetDlgItem(_hSelf, IDC_VIZPANEL_PASTE_LPAD_INDIC), nullptr, TRUE); InvalidateRect(GetDlgItem(_hSelf, IDC_VIZPANEL_PASTE_LEFT_LABEL), nullptr, TRUE); InvalidateRect(GetDlgItem(_hSelf, IDC_VIZPANEL_PASTE_RIGHT_LABEL), nullptr, TRUE); InvalidateRect(GetDlgItem(_hSelf, IDC_VIZPANEL_PASTE_RPAD_LABEL), nullptr, TRUE); InvalidateRect(GetDlgItem(_hSelf, IDC_VIZPANEL_PASTE_LPAD_LABEL), nullptr, TRUE); HMENU hPluginMenu = (HMENU)nppMessage(NPPM_GETMENUHANDLE); UINT recMenu{ static_cast<UINT>(MF_BYCOMMAND | (recEnabled ? MF_ENABLED : MF_DISABLED)) }; EnableMenuItem(hPluginMenu, (UINT)pluginMenuItems[MI_FIELD_JUMP]._cmdID, recMenu); EnableMenuItem(hPluginMenu, (UINT)pluginMenuItems[MI_DATA_EXTRACTION]._cmdID, recMenu); EnableMenuItem(hPluginMenu, (UINT)pluginMenuItems[MI_FIELD_LEFT]._cmdID, recMenu); EnableMenuItem(hPluginMenu, (UINT)pluginMenuItems[MI_FIELD_RIGHT]._cmdID, recMenu); UINT fieldMenu{ static_cast<UINT>(MF_BYCOMMAND | (fieldEnabled ? MF_ENABLED : MF_DISABLED)) }; EnableMenuItem(hPluginMenu, (UINT)pluginMenuItems[MI_FIELD_COPY]._cmdID, fieldMenu); EnableMenuItem(hPluginMenu, (UINT)pluginMenuItems[MI_FIELD_PASTE]._cmdID, fieldMenu); } void VisualizerPanel::enableThemeList(bool enable) { if (!panelMounted) return; themeEnabled = enable; InvalidateRect(GetDlgItem(_hSelf, IDC_VIZPANEL_THEME_LABEL), nullptr, TRUE); EnableWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_THEME_SELECT), enable); } void VisualizerPanel::visualizeFile(string fileType, bool bCachedFT, bool bAutoFT, bool bSyncFT) { HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; if (bCachedFT) { getDocFileType(fileType); _configIO.setVizConfig(fileType); } if (fileType.empty()) { if (bAutoFT) { if (_configIO.getPreferenceBool(PREF_ADFT)) detectFileType(hScintilla, fileType); } else { int index{ static_cast<int>(SendMessage(hFTList, CB_GETCURSEL, 0, 0)) }; if (index > 0) fileType = vFileTypes[index - 1].fileType; } } if (IsWindowVisible(GetDlgItem(_hSelf, IDC_VIZPANEL_MCBS_OVERRIDE_IND))) setPanelMBCharIndicator(fileType); if (fileType.empty()) { syncListFileTypes(); syncListThemes(); return; } wstring theme{}; getDocTheme(theme); clearVisualize(FALSE); setDocFileType(fileType); if (bSyncFT) syncListFileTypes(); setDocTheme(Utils::WideToNarrow(theme), theme.empty() ? fileType : ""); syncListThemes(); loadUsedThemes(); loadLexer(); renderCurrentPage(); string fsType{ detectFoldStructType(fileType) }; if (!fsType.empty() && (_configIO.getFoldStructValueA(fsType, "FoldLevelAuto") == "Y")) applyFolding(fsType); enableFoldableControls(!fsType.empty()); setFocusOnEditor(); } void VisualizerPanel::delDocInfo(intptr_t bufferID) { wstring filePath(MAX_PATH, '\0'); nppMessage(NPPM_GETFULLPATHFROMBUFFERID, bufferID, (LPARAM)filePath.c_str()); filePath = filePath.c_str(); for (size_t i{}; i < vDocInfo.size(); ++i) { if (vDocInfo[i].fileName == filePath) { vDocInfo.erase(vDocInfo.begin() + i); return; } } } void VisualizerPanel::showConfigDialog() { if (_configIO.fixIfNotUTF8File(_configIO.CONFIG_VIZ)) _configDlg.doDialog((HINSTANCE)_gModule); } void VisualizerPanel::showThemeDialog() { if (_configIO.fixIfNotUTF8File(_configIO.CONFIG_THEMES)) _themeDlg.doDialog((HINSTANCE)_gModule); } void VisualizerPanel::jumpToField(const string fileType, const int recordIndex, const int fieldIdx) { string currFileType{}; if (!getDocFileType(currFileType) || (fileType != currFileType)) { MessageBox(_hSelf, VIZ_PANEL_JUMP_CHANGED_DOC, VIZ_PANEL_JUMP_FIELD_TITLE, MB_OK | MB_ICONSTOP); return; } if (recordIndex != caretRecordRegIndex) { MessageBox(_hSelf, VIZ_PANEL_JUMP_CHANGED_REC, VIZ_PANEL_JUMP_FIELD_TITLE, MB_OK | MB_ICONSTOP); return; } moveToFieldEdge(fileType, fieldIdx, TRUE, FALSE, TRUE); } void VisualizerPanel::fieldLeft() { moveToFieldEdge("", caretFieldIndex, FALSE, FALSE, FALSE); } void VisualizerPanel::fieldRight() { bool hopRight_LeftEdge{ _configIO.getPreferenceBool(PREF_HOP_RT_LEFT_EDGE, FALSE) }; moveToFieldEdge("", caretFieldIndex + (hopRight_LeftEdge ? 1 : 0), FALSE, !hopRight_LeftEdge, FALSE); } void VisualizerPanel::fieldCopy() { if (caretFieldIndex < 0) return; HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; intptr_t leftPos{}, rightPos{}; if (getFieldEdges("", caretFieldIndex, 0, leftPos, rightPos) < 0) return; intptr_t fieldLen{ rightPos - leftPos }; if (fieldLen < 1) return; // if no trimming is required, copy to clipbard and return early if (!_configIO.getPreferenceBool(PREF_COPY_TRIM, FALSE)) { SendMessage(hScintilla, SCI_COPYRANGE, leftPos, rightPos); return; } string padText{}; padText = Utils::WideToNarrow(_configIO.getPreference(leftAlign ? PREF_PASTE_RPAD : PREF_PASTE_LPAD)); if (padText.empty()) padText = " "; intptr_t padLen{ static_cast<intptr_t>(padText.length()) }; intptr_t leftTrimLen{}, rightTrimLen{}; string colText(fieldLen + 1, '\0'); Sci_TextRangeFull sciTR{}; sciTR.lpstrText = colText.data(); sciTR.chrg.cpMin = leftPos; sciTR.chrg.cpMax = rightPos; SendMessage(hScintilla, SCI_GETTEXTRANGE, NULL, (LPARAM)&sciTR); colText = string{ colText.c_str() }; if (leftAlign && fieldLen >= padLen) { // find right-most full/partial match intptr_t lastPadLen{ padLen }; intptr_t matchStart{ fieldLen - padLen }; intptr_t matchingPos{}; while (lastPadLen > 0) { bool matchFailed{ FALSE }; for (intptr_t i{}; i < lastPadLen; ++i) { matchingPos = matchStart + i; if (colText.at(matchingPos) != padText.at(i)) { matchFailed = TRUE; --lastPadLen; ++matchStart; break; } } if (!matchFailed && (matchingPos == fieldLen - 1)) break; } #if FW_DEBUG_COPY_TRIM MessageBoxA(_hSelf, ("(" + to_string(colText.length()) + ", " + to_string(padText.length()) + ")").c_str(), "(ColLen, PadLen)", MB_OK); MessageBoxA(_hSelf, ("(" + to_string(lastPadLen) + ", " + to_string(matchStart) + ", " + to_string(matchingPos) + ")").c_str(), "(LastPadLen, MatchStart, MatchPos)", MB_OK); #endif rightTrimLen = lastPadLen; // if right-most match found, find prior matches if (lastPadLen > 0) { while (fieldLen >= rightTrimLen + padLen) { if (colText.substr(fieldLen - rightTrimLen - padLen, padLen) == padText) rightTrimLen += padLen; else break; } } } else if (!leftAlign) { // trim LPADs for right align bool keepTrimming{ TRUE }; while (keepTrimming && (leftTrimLen < fieldLen)) { for (int i{}; i < padLen; ++i) { if (colText.at(leftTrimLen) == padText.at(i)) { ++leftTrimLen; } else { keepTrimming = FALSE; break; } } } } if (leftPos + leftTrimLen < rightPos - rightTrimLen) SendMessage(hScintilla, SCI_COPYRANGE, leftPos + leftTrimLen, rightPos - rightTrimLen); #if FW_DEBUG_COPY_TRIM colText = colText.substr(leftTrimLen, colText.length() - leftTrimLen - rightTrimLen); MessageBoxA(_hSelf, ("(" + to_string(leftTrimLen) + ", " + to_string(rightTrimLen) + ")").c_str(), "(LeftTrimLen, RightTrimLen)", MB_OK); MessageBox(_hSelf, Utils::NarrowToWide("<|" + colText + "|>").c_str(), Utils::NarrowToWide("<|" + padText + "|>").c_str(), MB_OK); #endif } void VisualizerPanel::fieldPaste() { if (caretFieldIndex < 0) return; HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; intptr_t leftPos{}, rightPos{}; if (getFieldEdges("", caretFieldIndex, 0, leftPos, rightPos) < 0) return; intptr_t fieldCurrLen{ rightPos - leftPos }; if (fieldCurrLen < 1) return; int fieldLength{ vRecInfo[caretRecordRegIndex].fieldWidths[caretFieldIndex] }; wstring clipText; Utils::getClipboardText(GetParent(_hSelf), clipText); int clipLength{ static_cast<int>(clipText.length()) }; if (clipLength < 1) return; if (clipLength > fieldLength) { clipText = clipText.substr(leftAlign ? 0 : (clipLength - fieldLength), fieldLength); } else if (clipLength < fieldLength) { int gapLength{ fieldLength - clipLength }; wstring padText{ _configIO.getPreference(leftAlign ? PREF_PASTE_RPAD : PREF_PASTE_LPAD) }; if (padText.empty()) padText = L" "; wstring fillText{}; while (static_cast<int>(fillText.length()) < gapLength) { fillText.append(padText); } fillText = fillText.substr(0, gapLength); clipText = leftAlign ? (clipText + fillText) : (fillText + clipText); } SendMessage(hScintilla, SCI_DELETERANGE, leftPos, fieldCurrLen); SendMessage(hScintilla, SCI_INSERTTEXT, leftPos, (LPARAM)(Utils::WideToNarrow(clipText).c_str())); } void VisualizerPanel::visualizeTheme() { wchar_t fDesc[MAX_PATH]{}; SendMessage(hThemesLB, WM_GETTEXT, MAX_PATH, (LPARAM)fDesc); wstring theme{ fDesc }; if (theme.length() < 2) { clearVisualize(); return; } setDocTheme(Utils::WideToNarrow(theme)); loadUsedThemes(); renderCurrentPage(); } void VisualizerPanel::clearVisualize(bool sync) { if (!fwVizRegexed.empty()) { HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; SendMessage(hScintilla, SCI_STARTSTYLING, 0, NULL); SendMessage(hScintilla, SCI_SETSTYLING, SendMessage(hScintilla, SCI_GETLENGTH, NULL, NULL), STYLE_DEFAULT); } setDocFileType(""); setDocTheme(""); clearLexer(); if (sync) { syncListFileTypes(); syncListThemes(); } } int VisualizerPanel::loadTheme(const wstring theme) { PSCIFUNC_T sciFunc; void* sciPtr; if (!getDirectScintillaFunc(sciFunc, sciPtr)) return -1; bool useDefaultBackColor{ _configIO.getPreferenceBool(PREF_DEF_BACKGROUND, FALSE) }; int defaultBackColor{ static_cast<int>(nppMessage(NPPM_GETEDITORDEFAULTBACKGROUNDCOLOR)) }; int styleCount{ Utils::StringtoInt(_configIO.getStyleValue(theme, "Count")) }; // Do not load more than FW_STYLE_THEMES_MAX_ITEMS styles (including EOL styleInfo) styleCount = (loadedStyleCount + styleCount >= FW_STYLE_THEMES_MAX_ITEMS) ? (FW_STYLE_THEMES_MAX_ITEMS - loadedStyleCount - 1) : styleCount; if (styleCount < 1) return 0; int styleIndex{ FW_STYLE_THEMES_START_INDEX + loadedStyleCount }; ThemeInfo TI{}; TI.name = theme; TI.styleCount = styleCount; TI.rangeStartIndex = styleIndex + 1; // Offset by 1 to account for EOL Style vThemes.emplace_back(TI); StyleInfo styleInfo{}; _configIO.getFullStyle(theme, "EOL", styleInfo); sciFunc(sciPtr, SCI_STYLESETBACK, styleIndex, (useDefaultBackColor ? defaultBackColor : styleInfo.backColor)); sciFunc(sciPtr, SCI_STYLESETFORE, styleIndex, styleInfo.foreColor); sciFunc(sciPtr, SCI_STYLESETBOLD, styleIndex, styleInfo.bold); sciFunc(sciPtr, SCI_STYLESETITALIC, styleIndex, styleInfo.italics); ++styleIndex; char bufKey[8]; for (int i{}; i < styleCount; ++i) { snprintf(bufKey, 8, "BFBI_%02i", i); _configIO.getFullStyle(theme, bufKey, styleInfo); sciFunc(sciPtr, SCI_STYLESETBACK, styleIndex, (useDefaultBackColor ? defaultBackColor : styleInfo.backColor)); sciFunc(sciPtr, SCI_STYLESETFORE, styleIndex, styleInfo.foreColor); sciFunc(sciPtr, SCI_STYLESETBOLD, styleIndex, styleInfo.bold); sciFunc(sciPtr, SCI_STYLESETITALIC, styleIndex, styleInfo.italics); ++styleIndex; } #if FW_DEBUG_SET_STYLES wstring dbgMessage; int back, fore, bold, italics; for (int i{ styleIndex - styleCount }; i < styleIndex; ++i) { back = static_cast<int>(sciFunc(sciPtr, SCI_STYLEGETBACK, i, NULL)); fore = static_cast<int>(sciFunc(sciPtr, SCI_STYLEGETFORE, i, NULL)); bold = static_cast<int>(sciFunc(sciPtr, SCI_STYLEGETBOLD, i, NULL)); italics = static_cast<int>(sciFunc(sciPtr, SCI_STYLEGETITALIC, i, NULL)); dbgMessage = L"C0" + to_wstring(i - styleIndex + styleCount) + L"_STYLES = " + to_wstring(back) + L", " + to_wstring(fore) + L", " + to_wstring(bold) + L", " + to_wstring(italics); MessageBox(_hSelf, dbgMessage.c_str(), L"Theme Styles", MB_OK); } #endif return styleCount + 1; // Add 1 to include EOL styleInfo } int VisualizerPanel::loadUsedThemes() { loadedStyleCount = 0; vThemes.clear(); initCalltipStyle(); string fileType; if (!getDocFileType(fileType)) return 0; _configIO.setVizConfig(fileType); wstring fileTheme; if (!getDocTheme(fileTheme)) return 0; loadedStyleCount += loadTheme(fileTheme); // Load Record Type themes different than File Type theme vector<string> recTypesList; int recTypeCount{ _configIO.getConfigValueList(recTypesList, fileType, "RecordTypes") }; for (int i{}; i < recTypeCount; ++i) { wstring recTheme{}; recTheme = _configIO.getConfigWideChar(fileType, (recTypesList[i] + "_Theme")); if (recTheme == L"") continue; bool loaded{ FALSE }; for (size_t j{}; j < vThemes.size(); ++j) { if (recTheme == vThemes[j].name) { loaded = TRUE; break; } } if (!loaded) loadedStyleCount += loadTheme(recTheme); } return static_cast<int>(vThemes.size()); } int VisualizerPanel::loadLexer() { if (unlexed && !panelMounted) return 0; PSCIFUNC_T sciFunc; void* sciPtr; if (!getDirectScintillaFunc(sciFunc, sciPtr)) return -1; string fileType; if (!getDocFileType(fileType)) { clearLexer(); return 0; } if (fwVizRegexed.compare(fileType) != 0) clearLexer(); if (vRecInfo.size() > 0) return static_cast<int>(vRecInfo.size()); const std::wregex trimSpace{ std::wregex(L"(^( )+)|(( )+$)") }; int styleIndex{ FW_STYLE_THEMES_START_INDEX + FW_STYLE_THEMES_MAX_ITEMS }; struct loadedStyle { int index; string style; }; vector<loadedStyle> loadedStyles{}; vector<string> recTypes; int recTypeCount{ _configIO.getConfigValueList(recTypes, fileType, "RecordTypes") }; vRecInfo.resize(recTypeCount); for (int i{}; i < recTypeCount; ++i) { string& recType = recTypes[i]; RecordInfo& RT = vRecInfo[i]; RT.label = _configIO.getConfigWideChar(fileType, (recType + "_Label"), recType, ""); RT.marker = _configIO.getConfigStringA(fileType, (recType + "_Marker"), ".", ""); if (Utils::isInvalidRegex(RT.marker)) RT.marker = ""; RT.regExpr = regex{ RT.marker + ".*" }; RT.theme = _configIO.getConfigWideChar(fileType, (recType + "_Theme")); string fieldWidthList; int fieldCount; fieldWidthList = _configIO.getConfigStringA(fileType, (recType + "_FieldWidths")); fieldCount = _configIO.Tokenize(fieldWidthList, RT.fieldWidths); RT.fieldStarts.clear(); RT.fieldStarts.resize(fieldCount); for (int fnum{}, startPos{}; fnum < fieldCount; ++fnum) { RT.fieldStarts[fnum] = startPos; startPos += RT.fieldWidths[fnum]; } wstring fieldLabelList, fieldType; size_t colonPos{}; fieldLabelList = _configIO.getConfigWideChar(fileType, (recType + "_FieldLabels")); fieldCount = _configIO.Tokenize(fieldLabelList, RT.fieldLabels); RT.fieldStyles.clear(); RT.fieldStyles.resize(fieldCount); for (int fnum{}; fnum < fieldCount; ++fnum) { wstring& field{ RT.fieldLabels[fnum] }; RT.fieldStyles[fnum] = -1; colonPos = field.find(':'); if (colonPos != string::npos) { fieldType = field.substr(colonPos + 1); fieldType = regex_replace(fieldType, trimSpace, L""); string styleText{ _configIO.getFieldStyleText(fieldType) }; if (styleText.length() != 16) { RT.fieldStyles[fnum] = STYLE_DEFAULT; continue; } // If this styleInfo is already loaded, just map to that styleInfo slot bool styleMatched{ FALSE }; for (size_t k{}; k < loadedStyles.size(); ++k) { if (styleText == loadedStyles[k].style) { RT.fieldStyles[fnum] = loadedStyles[k].index; styleMatched = TRUE; break; } } if (styleMatched) continue; if (styleIndex < FW_STYLE_FIELDS_MIN_INDEX) continue; StyleInfo fieldStyle; _configIO.parseFieldStyle(styleText, fieldStyle); sciFunc(sciPtr, SCI_STYLESETBACK, styleIndex, fieldStyle.backColor); sciFunc(sciPtr, SCI_STYLESETFORE, styleIndex, fieldStyle.foreColor); sciFunc(sciPtr, SCI_STYLESETBOLD, styleIndex, fieldStyle.bold); sciFunc(sciPtr, SCI_STYLESETITALIC, styleIndex, fieldStyle.italics); RT.fieldStyles[fnum] = styleIndex; loadedStyles.emplace_back(loadedStyle{ styleIndex, styleText }); --styleIndex; } } } fwVizRegexed = fileType; unlexed = FALSE; #if FW_DEBUG_LOAD_REGEX int fieldCount; for (int i{}; i < recTypeCount; ++i) { wstring dbgMessage; wstring& recType = recTypes[i]; RecordInfo& RT = recInfoList[i]; dbgMessage = recType + L"\nRec_Label = " + RT.label + L"\nRec_Marker = " + _configIO.NarrowToWide(RT.marker) + L"\nRec_Theme = " + RT.theme + L"\nFieldWidths=\n"; fieldCount = static_cast<int>(RT.fieldWidths.size()); for (int j{}; j < fieldCount; ++j) { dbgMessage += L" (" + to_wstring(RT.fieldStarts[j]) + L", " + to_wstring(RT.fieldWidths[j]) + L"),"; } MessageBox(_hSelf, dbgMessage.c_str(), L"", MB_OK); } #endif return recTypeCount; } void VisualizerPanel::applyLexer(const intptr_t startLine, intptr_t endLine) { if (unlexed && !panelMounted) return; PSCIFUNC_T sciFunc; void* sciPtr; if (!getDirectScintillaFunc(sciFunc, sciPtr)) return; string fileType; if (!getDocFileType(fileType)) return; wstring fileTheme; if (!getDocTheme(fileTheme)) return; if (vThemes.size() < 1) return; int shiftPerRec{ vThemes[0].styleCount }; if (shiftPerRec < 1) return; intptr_t lineCount; lineCount = sciFunc(sciPtr, SCI_GETLINECOUNT, NULL, NULL); if (endLine > lineCount) endLine = lineCount; // set shiftPerRec to an integer just less than half of base theme's styleCount shiftPerRec = (shiftPerRec < 5) ? 1 : ((shiftPerRec + 1) >> 1) - 1; string lineTextCStr(FW_LINE_MAX_LENGTH, '\0'); string recStartText{}, eolMarker{}; intptr_t caretLine, eolMarkerPos, recStartLine{}, currentPos, startPos, endPos, recStartPos{}; size_t eolMarkerLen; const size_t regexedCount{ vRecInfo.size() }; bool newRec{ TRUE }; eolMarker = _configIO.getConfigStringA(fileType, "RecordTerminator"); eolMarkerLen = eolMarker.length(); bool byteCols{ !_configIO.getMultiByteLexing(fileType) }; caretLine = sciFunc(sciPtr, SCI_LINEFROMPOSITION, sciFunc(sciPtr, SCI_GETCURRENTPOS, NULL, NULL), NULL); caretRecordRegIndex = -1; caretRecordStartPos = 0; caretRecordEndPos = 0; #if FW_DEBUG_LEXER_COUNT ++lexCount; #endif for (auto currentLine{ startLine }; currentLine < endLine; ++currentLine) { if (sciFunc(sciPtr, SCI_LINELENGTH, currentLine, NULL) > FW_LINE_MAX_LENGTH) continue; sciFunc(sciPtr, SCI_GETLINE, currentLine, (LPARAM)lineTextCStr.c_str()); startPos = sciFunc(sciPtr, SCI_POSITIONFROMLINE, currentLine, NULL); endPos = sciFunc(sciPtr, SCI_GETLINEENDPOSITION, currentLine, NULL); string_view lineText{ lineTextCStr.c_str(), static_cast<size_t>(endPos - startPos) }; if (newRec) { recStartLine = currentLine; recStartPos = startPos; recStartText = lineText; } if (newRec && lineText.empty()) continue; if (eolMarkerLen == 0) { newRec = TRUE; eolMarkerPos = endPos; } else if (lineText.length() > eolMarkerLen && (lineText.substr(lineText.length() - eolMarkerLen) == eolMarker)) { newRec = TRUE; eolMarkerPos = endPos - eolMarkerLen; } else if (currentLine < endLine) { newRec = FALSE; continue; } else { eolMarkerPos = endPos; } currentPos = recStartPos; int colorOffset{}; size_t regexIndex{}; while (regexIndex < regexedCount) { if (regex_match(recStartText, vRecInfo[regexIndex].regExpr)) { if (caretLine >= recStartLine && caretLine <= currentLine) { caretRecordRegIndex = static_cast<int>(regexIndex); caretRecordStartPos = static_cast<int>(recStartPos); caretRecordEndPos = static_cast<int>(endPos); caretEolMarkerPos = static_cast<int>(eolMarkerPos); } break; } ++regexIndex; colorOffset += shiftPerRec; } if (regexIndex >= regexedCount) continue; const vector<int>& recFieldWidths{ vRecInfo[regexIndex].fieldWidths }; const size_t fieldCount{ recFieldWidths.size() }; wstring recTheme{ vRecInfo[regexIndex].theme }; size_t themeIndex{}; if ((recTheme != L"") && (recTheme != fileTheme)) { for (size_t i{ 0 }; i < vThemes.size(); ++i) { if (recTheme == vThemes[i].name) { themeIndex = i; colorOffset = 0; break; } } } const int& styleRangeStart{ vThemes[themeIndex].rangeStartIndex }; const int& styleCount{ vThemes[themeIndex].styleCount }; if (styleCount < 1) continue; #if FW_DEBUG_APPLY_LEXER wstring dbgMessage; size_t dbgPos{ currentPos }; dbgMessage = L"FieldWidths[" + to_wstring(regexIndex) + L"] = " + to_wstring(fieldCount) + L"\n"; for (int i{}; i < static_cast<int>(fieldCount); ++i) { dbgMessage += L" (" + to_wstring(dbgPos) + L", " + to_wstring(recFieldWidths[i]) + L", " + to_wstring(eolMarkerPos - eolMarkerLen) + L"), "; dbgPos += recFieldWidths[i]; } MessageBox(_hSelf, dbgMessage.c_str(), L"", MB_OK); #endif size_t styleIndex{}; const vector<int>& recFieldStyles{ vRecInfo[regexIndex].fieldStyles }; if (byteCols) { intptr_t unstyledLen{}; for (size_t i{}; i < fieldCount; ++i) { sciFunc(sciPtr, SCI_STARTSTYLING, currentPos, NULL); unstyledLen = eolMarkerPos - currentPos; currentPos += recFieldWidths[i]; styleIndex = (recFieldStyles[i] >= 0) ? recFieldStyles[i] : styleRangeStart + ((i + colorOffset) % styleCount); if (recFieldWidths[i] < unstyledLen) { sciFunc(sciPtr, SCI_SETSTYLING, recFieldWidths[i], styleIndex); } else { sciFunc(sciPtr, SCI_SETSTYLING, unstyledLen, styleIndex); unstyledLen = 0; sciFunc(sciPtr, SCI_STARTSTYLING, eolMarkerPos, NULL); sciFunc(sciPtr, SCI_SETSTYLING, eolMarkerLen, styleRangeStart - 1); break; } } if (fieldCount > 0 && unstyledLen > 0) { sciFunc(sciPtr, SCI_STARTSTYLING, currentPos, NULL); sciFunc(sciPtr, SCI_SETSTYLING, (endPos - currentPos), styleRangeStart - 1); } #if FW_DEBUG_APPLIED_STYLES if (currentLine == caretLine) { size_t dbgStyleIndex{}; wstring dbgMessage{}, dbgPre{ L", " }, dbgNoPre{}; intptr_t dbgPos{}; dbgPos = recStartPos; dbgMessage = L"Input Styles:\n"; for (size_t i{}; (i < fieldCount) && (dbgPos < eolMarkerPos); ++i) { dbgStyleIndex = (recFieldStyles[i] >= 0) ? recFieldStyles[i] : styleRangeStart + ((i + colorOffset) % styleCount); dbgMessage += (i == 0 ? dbgNoPre : dbgPre) + L"(" + to_wstring(dbgPos) + L", " + to_wstring(recFieldWidths[i]) + L", " + to_wstring(dbgStyleIndex) + L")"; dbgPos += recFieldWidths[i]; } dbgPos = recStartPos; dbgMessage += L"\n\nApplied Styles:\n"; for (size_t i{}; (i < fieldCount) && (dbgPos < eolMarkerPos); ++i) { dbgMessage += (i == 0 ? dbgNoPre : dbgPre) + L"(" + to_wstring(dbgPos) + L", " + to_wstring(recFieldWidths[i]) + L", " + to_wstring(sciFunc(sciPtr, SCI_GETSTYLEAT, dbgPos, NULL)) + L")"; dbgPos += recFieldWidths[i]; } dbgMessage += L"\n\nDocument Length: " + to_wstring(sciFunc(sciPtr, SCI_GETLENGTH, NULL, NULL)); dbgMessage += L"\tEnd Styled: " + to_wstring(sciFunc(sciPtr, SCI_GETENDSTYLED, NULL, NULL)); MessageBox(_hSelf, dbgMessage.c_str(), L"", MB_OK); } #endif } else { intptr_t nextPos{}; for (size_t i{}; i < fieldCount; ++i) { sciFunc(sciPtr, SCI_STARTSTYLING, currentPos, NULL); nextPos = sciFunc(sciPtr, SCI_POSITIONRELATIVE, currentPos, recFieldWidths[i]); styleIndex = (recFieldStyles[i] >= 0) ? recFieldStyles[i] : styleRangeStart + ((i + colorOffset) % styleCount); if (nextPos > 0 && nextPos <= eolMarkerPos) { sciFunc(sciPtr, SCI_SETSTYLING, (nextPos - currentPos), styleIndex); currentPos = nextPos; } else { sciFunc(sciPtr, SCI_SETSTYLING, (eolMarkerPos - currentPos), styleIndex); sciFunc(sciPtr, SCI_STARTSTYLING, eolMarkerPos, NULL); sciFunc(sciPtr, SCI_SETSTYLING, eolMarkerLen, styleRangeStart - 1); currentPos = 0; break; } } if (fieldCount > 0 && currentPos > 0 && eolMarkerPos >= currentPos) { sciFunc(sciPtr, SCI_STARTSTYLING, currentPos, NULL); sciFunc(sciPtr, SCI_SETSTYLING, (endPos - currentPos), styleRangeStart - 1); } } } } void VisualizerPanel::renderCurrentPage() { if (loadLexer() < 1) { clearCaretFieldInfo(); return; } HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; intptr_t linesOnScreen, firstVisible, startLine, endLine; linesOnScreen = SendMessage(hScintilla, SCI_LINESONSCREEN, NULL, NULL); firstVisible = SendMessage(hScintilla, SCI_GETFIRSTVISIBLELINE, NULL, NULL); startLine = SendMessage(hScintilla, SCI_DOCLINEFROMVISIBLE, firstVisible, NULL); endLine = SendMessage(hScintilla, SCI_DOCLINEFROMVISIBLE, firstVisible + linesOnScreen, NULL); applyLexer(startLine, endLine + 1); displayCaretFieldInfo(startLine, endLine); } void VisualizerPanel::clearCaretFieldInfo() { enableFieldControls(FALSE); SetWindowText(hFieldInfo, L""); } void VisualizerPanel::onPanelResize(LPARAM lParam) { RECT rcInfo; GetWindowRect(hFieldInfo, &rcInfo); // Get fieldInfo top-leftEdge coordinates relative to dock panel POINT pt{ rcInfo.left, rcInfo.top }; ScreenToClient(_hSelf, &pt); MoveWindow(hFieldInfo, pt.x, pt.y, (LOWORD(lParam) - pt.x - 3), (rcInfo.bottom - rcInfo.top), TRUE); // About button HWND hAboutBtn{GetDlgItem(_hSelf, IDC_VIZPANEL_ABOUT_BUTTON)}; RECT rcAboutBtn; GetWindowRect(hAboutBtn, &rcAboutBtn); int aboutBtnWidth{rcAboutBtn.right - rcAboutBtn.left}; int aboutBtnHeight{rcAboutBtn.bottom - rcAboutBtn.top}; MoveWindow(hAboutBtn, (LOWORD(lParam) - aboutBtnWidth - 3), (HIWORD(lParam) - aboutBtnHeight - 3), aboutBtnWidth, aboutBtnHeight, TRUE); // Ini Files Info button HWND hIniBtn{GetDlgItem(_hSelf, IDC_VIZPANEL_FILE_INFO_BUTTON)}; RECT rcIniBtn; GetWindowRect(hIniBtn, &rcIniBtn); int iniBtnWidth{rcIniBtn.right - rcIniBtn.left}; int iniBtnHeight{rcIniBtn.bottom - rcIniBtn.top}; MoveWindow(hIniBtn, (LOWORD(lParam) - aboutBtnWidth - iniBtnWidth - 4), (HIWORD(lParam) - iniBtnHeight - 3), iniBtnWidth, iniBtnHeight, TRUE); } int VisualizerPanel::getFieldEdges(const string fileType, const int fieldIdx, const int rightPullback, intptr_t& leftPos, intptr_t& rightPos) { HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return -1; string currFileType{}; if (fileType == "") { if (!getDocFileType(currFileType)) return -1; } else { currFileType = fileType; } RecordInfo& FLD{ vRecInfo[caretRecordRegIndex] }; if (fieldIdx < 0 || fieldIdx >= static_cast<int>(FLD.fieldStarts.size())) return -1; int leftOffset{ FLD.fieldStarts[fieldIdx] }; int rightOffset{ leftOffset + FLD.fieldWidths[fieldIdx] - rightPullback }; if (!_configIO.getMultiByteLexing(currFileType)) { leftPos = caretRecordStartPos + leftOffset; rightPos = caretRecordStartPos + rightOffset; } else { leftPos = SendMessage(hScintilla, SCI_POSITIONRELATIVE, caretRecordStartPos, leftOffset); rightPos = SendMessage(hScintilla, SCI_POSITIONRELATIVE, caretRecordStartPos, rightOffset); } if (leftPos >= caretEolMarkerPos) leftPos = caretEolMarkerPos - 1; if (rightPos >= caretEolMarkerPos) rightPos = caretEolMarkerPos - 1; return 0; } void VisualizerPanel::moveToFieldEdge(const string fileType, const int fieldIdx, bool jumpTo, bool rightEdge, bool hilite) { HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; intptr_t caretPos{ SendMessage(hScintilla, SCI_GETCURRENTPOS, NULL, NULL) }; if (fieldIdx < 0) { if (caretPos >= caretEolMarkerPos) { caretPos = caretEolMarkerPos - 1; SendMessage(hScintilla, SCI_GOTOPOS, caretPos, NULL); } return; } intptr_t leftPos{}, rightPos{}; if (getFieldEdges(fileType, fieldIdx, 1, leftPos, rightPos) < 0) return; if (!jumpTo) { if (rightEdge) { if (caretPos == rightPos && caretPos < caretEolMarkerPos - 1) if (getFieldEdges(fileType, fieldIdx + 1, 1, leftPos, rightPos) < 0) return; } else { if (caretPos == leftPos && caretPos > caretRecordStartPos) if (getFieldEdges(fileType, fieldIdx - 1, 1, leftPos, rightPos) < 0) return; } } SendMessage(hScintilla, SCI_SETXCARETPOLICY, CARET_JUMPS | CARET_EVEN, 0); SendMessage(hScintilla, SCI_GOTOPOS, (rightEdge ? rightPos : leftPos), 0); // Flash caret if (hilite) { HANDLE hThread = CreateThread(NULL, 0, threadPositionHighlighter, 0, 0, NULL); if (hThread) CloseHandle(hThread); } setFocusOnEditor(); } void VisualizerPanel::setFieldAlign(bool left) { leftAlign = left; ShowWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_PASTE_RPAD_INDIC), leftAlign ? SW_SHOW : SW_HIDE); ShowWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_PASTE_LPAD_INDIC), leftAlign ? SW_HIDE : SW_SHOW); } void VisualizerPanel::displayCaretFieldInfo(const intptr_t startLine, const intptr_t endLine) { if (!isVisible()) return; HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; string fileType; if (!getDocFileType(fileType)) return; wstring fieldInfoText{}; intptr_t caretPos; intptr_t caretLine; bool byteCols{ !_configIO.getMultiByteLexing(fileType) }; wstring newLine{ L"\r\n" }; caretFieldIndex = -1; caretPos = SendMessage(hScintilla, SCI_GETCURRENTPOS, NULL, NULL); caretLine = SendMessage(hScintilla, SCI_LINEFROMPOSITION, caretPos, NULL); if (caretLine < startLine || caretLine > endLine) { clearCaretFieldInfo(); return; } if (caretRecordRegIndex < 0) { if (SendMessage(hScintilla, SCI_POSITIONFROMLINE, caretLine, NULL) == SendMessage(hScintilla, SCI_GETLINEENDPOSITION, caretLine, NULL)) { fieldInfoText = CUR_POS_DATA_BLANK_LINE; } else { fieldInfoText = CUR_POS_DATA_UNKOWN_REC; } } else if (caretPos == caretRecordEndPos) { fieldInfoText = CUR_POS_DATA_REC_END; } else if (caretPos >= caretEolMarkerPos) { fieldInfoText = CUR_POS_DATA_REC_TERM; } else { RecordInfo& FLD{ vRecInfo[caretRecordRegIndex] }; intptr_t caretColumn, recLength; int fieldCount, fieldLabelCount, cumulativeWidth{}, matchedField{ -1 }; if (byteCols) { caretColumn = caretPos - caretRecordStartPos; recLength = caretEolMarkerPos - caretRecordStartPos; } else { caretColumn = SendMessage(hScintilla, SCI_COUNTCHARACTERS, caretRecordStartPos, caretPos); recLength = SendMessage(hScintilla, SCI_COUNTCHARACTERS, caretRecordStartPos, caretEolMarkerPos); } fieldInfoText = CUR_POS_DATA_REC_TYPE + FLD.label; fieldCount = static_cast<int>(FLD.fieldStarts.size()); fieldLabelCount = static_cast<int>(FLD.fieldLabels.size()); for (int i{}; i < fieldCount; ++i) { cumulativeWidth += FLD.fieldWidths[i]; if (caretColumn >= FLD.fieldStarts[i] && caretColumn < cumulativeWidth) { matchedField = i; } } fieldInfoText += newLine + CUR_POS_DATA_REC_LENGTH + to_wstring(recLength) + L"/" + to_wstring(cumulativeWidth) + CUR_POS_DATA_CURR_DEFINED; if (matchedField < 0) { fieldInfoText += newLine + CUR_POS_DATA_OVERFLOW; } else { caretFieldIndex = matchedField; fieldInfoText += newLine + CUR_POS_DATA_FIELD_LABEL; if (fieldLabelCount == 0 || matchedField >= fieldLabelCount) fieldInfoText += CUR_POS_DATA_FIELD_NUM + to_wstring(matchedField + 1); else fieldInfoText += FLD.fieldLabels[matchedField]; int fieldBegin{ FLD.fieldStarts[matchedField] }; int fieldLength{ FLD.fieldWidths[matchedField] }; fieldInfoText += newLine + CUR_POS_DATA_FIELD_START + to_wstring(fieldBegin + 1); fieldInfoText += newLine + CUR_POS_DATA_FIELD_WIDTH + to_wstring(fieldLength); fieldInfoText += newLine + CUR_POS_DATA_FIELD_COL + to_wstring(caretColumn - fieldBegin + 1); setFieldAlign(static_cast<int>(caretColumn - fieldBegin) < (fieldBegin + fieldLength - caretColumn)); } } wchar_t byteInfo[200]; UCHAR startChar = static_cast<UCHAR>(SendMessage(hScintilla, SCI_GETCHARAT, caretPos, 0)); if (!(startChar & 0x80)) { swprintf(byteInfo, 200, L"0x%X [%u]", startChar, startChar); fieldInfoText += newLine + CUR_POS_DATA_ANSI_BYTE + wstring(byteInfo); } else { swprintf(byteInfo, 200, L"%X", startChar); fieldInfoText += newLine + CUR_POS_DATA_UTF8_BYTES + wstring(byteInfo); int unicodeHead{ 0 }, unicodeTail{ 0 }; UCHAR nextChar{}; nextChar = static_cast<UCHAR>(SendMessage(hScintilla, SCI_GETCHARAT, caretPos + 1, 0)); swprintf(byteInfo, 200, L" %X", nextChar); fieldInfoText += wstring(byteInfo); unicodeHead = (startChar & 31) << 6; unicodeTail = (nextChar & 63); if ((startChar & 0xE0) == 0xE0) { nextChar = static_cast<UCHAR>(SendMessage(hScintilla, SCI_GETCHARAT, caretPos + 2, 0)); swprintf(byteInfo, 200, L" %X", nextChar); fieldInfoText += wstring(byteInfo); unicodeHead = (startChar & 15) << 12; unicodeTail = (unicodeTail << 6) + (nextChar & 63); if ((startChar & 0xF0) == 0xF0) { nextChar = static_cast<UCHAR>(SendMessage(hScintilla, SCI_GETCHARAT, caretPos + 3, 0)); swprintf(byteInfo, 200, L" %X", nextChar); fieldInfoText += wstring(byteInfo); unicodeHead = (startChar & 7) << 18; unicodeTail = (unicodeTail << 6) + (nextChar & 63); } } swprintf(byteInfo, 200, L" (U+%X)", (unicodeHead + unicodeTail)); fieldInfoText += wstring(byteInfo); } #if FW_DEBUG_LEXER_COUNT fieldInfoText = L"Lex Count: " + to_wstring(lexCount) + L"\r\n" + fieldInfoText; #endif SetWindowText(hFieldInfo, fieldInfoText.c_str()); enableFieldControls(TRUE); if (_configIO.getPreferenceBool(PREF_SHOW_CALLTIP, FALSE)) { int foldLevel{ static_cast<int>(SendMessage(hScintilla, SCI_GETFOLDLEVEL, caretLine, 0)) }; if (foldLevel > 0) { int level{ (foldLevel - SC_FOLDLEVELBASE) & SC_FOLDLEVELNUMBERMASK }; fieldInfoText += L"\n" + wstring(40, '-') + ((foldLevel & SC_FOLDLEVELHEADERFLAG) ? L"\n Fold Header: " + to_wstring(level + 1) : L"\n Fold Level: " + to_wstring(level)); } calltipText = Utils::WideToNarrow(fieldInfoText); PostMessage(hScintilla, SCI_CALLTIPSHOW, caretPos, (LPARAM)calltipText.c_str()); } } void VisualizerPanel::showJumpDialog() { string fileType; if (!getDocFileType(fileType)) return; RecordInfo& FLD{ vRecInfo[caretRecordRegIndex] }; int fieldCount = static_cast<int>(FLD.fieldStarts.size()); int fieldLabelCount = static_cast<int>(FLD.fieldLabels.size()); vector<wstring> fieldLabels; fieldLabels.resize(fieldCount); for (int i{}; i < fieldCount; ++i) { if (fieldLabelCount == 0 || i >= fieldLabelCount) { fieldLabels[i] = CUR_POS_DATA_FIELD_NUM + to_wstring(i + 1); } else { fieldLabels[i] = FLD.fieldLabels[i]; } } _jumpDlg.doDialog((HINSTANCE)_gModule); _jumpDlg.initDialog(fileType, caretRecordRegIndex, caretFieldIndex, fieldLabels); } void VisualizerPanel::showAboutDialog() { _aboutDlg.doDialog((HINSTANCE)_gModule); } void VisualizerPanel::showExtractDialog() { string fileType; if (!getDocFileType(fileType)) return; _dataExtractDlg.doDialog((HINSTANCE)_gModule); _dataExtractDlg.initDialog(fileType, vRecInfo); } bool VisualizerPanel::detectFileType(HWND hScintilla, string& fileType) { if (!panelMounted) return FALSE; bool detected{ detectFileTypeByVizConfig(hScintilla, fileType, FALSE) }; if (!detected) detected = detectFileTypeByVizConfig(hScintilla, fileType, TRUE); return detected; } bool VisualizerPanel::detectFileTypeByVizConfig(HWND hScintilla, string& fileType, bool defaultVizConfig) { if (defaultVizConfig) { _configIO.defaultVizConfig(); } else { _configIO.userVizConfig(); if (!_configIO.checkConfigFilesforUTF8()) return FALSE; } string lineTextCStr(FW_LINE_MAX_LENGTH, '\0'); intptr_t startPos, endPos; vector<string> fileTypes; _configIO.getConfigValueList(fileTypes, "Base", "FileTypes"); for (string fType : fileTypes) { bool matched{ FALSE }; for (int i{}; i < ADFT_MAX; ++i) { char idx[5]; snprintf(idx, 5, "%02d", i + 1); intptr_t line = _configIO.getConfigInt(fType, "ADFT_Line_" + string{ idx }); if (line == 0) continue; string strRegex = _configIO.getConfigStringA(fType, "ADFT_Regex_" + string{ idx }); if (strRegex.empty()) continue; if (Utils::isInvalidRegex(strRegex)) continue; intptr_t lineCount = SendMessage(hScintilla, SCI_GETLINECOUNT, NULL, NULL); line += (line < 0) ? lineCount : -1; if (line < 0 || line >= lineCount) continue; if (strRegex.substr(strRegex.length() - 1) != "$") strRegex += ".*"; if (SendMessage(hScintilla, SCI_LINELENGTH, line, NULL) > FW_LINE_MAX_LENGTH) continue; SendMessage(hScintilla, SCI_GETLINE, line, (LPARAM)lineTextCStr.c_str()); startPos = SendMessage(hScintilla, SCI_POSITIONFROMLINE, line, NULL); endPos = SendMessage(hScintilla, SCI_GETLINEENDPOSITION, line, NULL); string_view lineText{ lineTextCStr.c_str(), static_cast<size_t>(endPos - startPos) }; if (regex_match(string{ lineText }, regex{ strRegex })) matched = TRUE; else { matched = FALSE; break; } } if (matched) { fileType = fType; setDocFileType(fileType); wstring theme{}; if (!getDocTheme(theme)) setDocTheme("", fileType); break; } } if (defaultVizConfig && fileType.empty()) _configIO.userVizConfig(); return (!fileType.empty()); } const wstring VisualizerPanel::getCurrentFileName() { wstring fileName(MAX_PATH, '\0'); nppMessage(NPPM_GETFULLCURRENTPATH, MAX_PATH, (LPARAM)fileName.c_str()); return wstring{ fileName.c_str() }; } void VisualizerPanel::setDocInfo(bool bDocType, string val) { const wstring fileName{ getCurrentFileName() }; for (DocInfo& DI : vDocInfo) { if (fileName == DI.fileName) { if (bDocType) DI.docType = val; if (!bDocType) DI.docTheme = val; return; } } DocInfo fi{fileName, (bDocType ? val : ""), (!bDocType ? val : "")}; vDocInfo.emplace_back(fi); } bool VisualizerPanel::getDocFileType(string& fileType) { const wstring fileName{ getCurrentFileName() }; fileType = ""; for (const DocInfo& DI : vDocInfo) { if (fileName == DI.fileName) { fileType = DI.docType; break; } } return (!fileType.empty()); } bool VisualizerPanel::getDocTheme(wstring& theme) { const wstring fileName{ getCurrentFileName() }; theme = L""; for (const DocInfo& DI : vDocInfo) { if (fileName == DI.fileName) { theme = Utils::NarrowToWide(DI.docTheme); break; } } return (!theme.empty()); } string VisualizerPanel::getDocFoldStructType() { const wstring fileName{ getCurrentFileName() }; for (const DocInfo& DI : vDocInfo) { if (fileName == DI.fileName) return DI.foldStructType; } return ""; } bool VisualizerPanel::getDocFolded() { const wstring fileName{ getCurrentFileName() }; for (const DocInfo& DI : vDocInfo) { if (fileName == DI.fileName) return DI.folded; } return false; } void VisualizerPanel::setDocFileType(string fileType) { if (!panelMounted) return; enableThemeList(!fileType.empty()); setDocInfo(true, fileType); } void VisualizerPanel::setDocTheme(string theme, string fileType) { if (theme.empty() && (!fileType.empty())) theme = _configIO.getConfigStringA(fileType, "FileTheme"); setDocInfo(false, theme); } void VisualizerPanel::setDocFoldStructType(string foldStructType) { const wstring fileName{ getCurrentFileName() }; for (DocInfo& DI : vDocInfo) { if (fileName == DI.fileName) { DI.foldStructType = foldStructType; return; } } } void VisualizerPanel::setDocFolded(bool bFolding) { const wstring fileName{ getCurrentFileName() }; for (DocInfo& DI : vDocInfo) { if (fileName == DI.fileName) { DI.folded = bFolding; return; } } } void VisualizerPanel::setADFTCheckbox() { bool checked{ IsDlgButtonChecked(_hSelf, IDC_VIZPANEL_AUTO_DETECT_FT) == BST_CHECKED }; _configIO.setPreferenceBool(PREF_ADFT, checked); if (checked) visualizeFile("", FALSE, TRUE, TRUE); } void VisualizerPanel::setPanelMBCharState() { _configIO.setPanelMBCharState(IsDlgButtonChecked(_hSelf, IDC_VIZPANEL_MCBS_OVERRIDE)); visualizeFile("", TRUE, (IsDlgButtonChecked(_hSelf, IDC_VIZPANEL_AUTO_DETECT_FT) == BST_CHECKED), TRUE); } void VisualizerPanel::setPanelMBCharIndicator(string fileType) { wstring indicator{}; UINT state{ IsDlgButtonChecked(_hSelf, IDC_VIZPANEL_MCBS_OVERRIDE) }; if (fileType.length() < 2 || state == BST_UNCHECKED) indicator = L""; else if (state == BST_CHECKED) indicator = L"*"; else if (_configIO.getConfigStringA(fileType, "MultiByteChars", "N", "") == "Y") indicator = L"+"; else indicator = L"-"; SetDlgItemText(_hSelf, IDC_VIZPANEL_MCBS_OVERRIDE_IND, indicator.c_str()); } void VisualizerPanel::setDefaultBackground() { _configIO.setPreferenceBool(PREF_DEF_BACKGROUND, (IsDlgButtonChecked(_hSelf, IDC_VIZPANEL_DEFAULT_BACKGROUND) == BST_CHECKED)); visualizeFile("", TRUE, (IsDlgButtonChecked(_hSelf, IDC_VIZPANEL_AUTO_DETECT_FT) == BST_CHECKED), TRUE); } void VisualizerPanel::setShowCalltip() { _configIO.setPreferenceBool(PREF_SHOW_CALLTIP, (IsDlgButtonChecked(_hSelf, IDC_VIZPANEL_SHOW_CALLTIP) == BST_CHECKED)); visualizeFile("", TRUE, (IsDlgButtonChecked(_hSelf, IDC_VIZPANEL_AUTO_DETECT_FT) == BST_CHECKED), TRUE); } void VisualizerPanel::initCalltipStyle() { HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; SendMessage(hScintilla, SCI_STYLESETFONT, STYLE_CALLTIP, (LPARAM)"Consolas"); SendMessage(hScintilla, SCI_STYLESETWEIGHT, STYLE_CALLTIP, 550); SendMessage(hScintilla, SCI_STYLESETFORE, STYLE_CALLTIP, RGB(175, 95, 63)); SendMessage(hScintilla, SCI_STYLESETBACK, STYLE_CALLTIP, RGB(255, 255, 255)); SendMessage(hScintilla, SCI_CALLTIPUSESTYLE, 3, 0); } void VisualizerPanel::onBufferActivate() { unlexed = TRUE; enableFoldableControls(FALSE); if (panelMounted) visualizeFile("", TRUE, TRUE, TRUE); enableFoldedControls(getDocFolded()); } void VisualizerPanel::setFocusOnEditor() { HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; SendMessage(hScintilla, SCI_GRABFOCUS, 0, 0); } void VisualizerPanel::clearLexer() { vRecInfo.clear(); fwVizRegexed = ""; } void VisualizerPanel::popupSamplesMenu() { HMENU hPopupMenu = CreatePopupMenu(); _submenu.initSamplesPopup(hPopupMenu); RECT rc; GetWindowRect(GetDlgItem(_hSelf, IDC_VIZPANEL_FILE_SAMPLES_BTN), &rc); int cmd = TrackPopupMenu(hPopupMenu, TPM_RIGHTALIGN | TPM_TOPALIGN | TPM_LEFTBUTTON | TPM_RETURNCMD, rc.right, rc.bottom, 0, _hSelf, NULL); if (cmd) nppMessage(NPPM_MENUCOMMAND, 0, cmd); // Calling RemoveMenu is needed since the appended items are being referenced from the NPP Main menu. // In RemoveMenu, zero is used as the position since items shift down with each remove call. // 'i' is used only as a loopcounter. int itemCount = GetMenuItemCount(hPopupMenu); for (int i{}; i < itemCount; ++i) { RemoveMenu(hPopupMenu, 0, MF_BYPOSITION); } DestroyMenu(hPopupMenu); } string VisualizerPanel::detectFoldStructType(string fileType) { if (fileType.empty()) return ""; int foldStructCount{ _configIO.getFoldStructCount() }; string fsType(6, '\0'); for (int i{}; i < foldStructCount; ++i) { snprintf(fsType.data(), 6, "FS%03d", i + 1); if (_configIO.getFoldStructValueA(fsType, "FileType") == fileType) { setDocFoldStructType(fsType); return fsType.c_str(); } } return ""; } void VisualizerPanel::applyFolding(string fsType) { if (getDocFolded()) return; string fileType{}; getDocFileType(fileType); if (fileType.empty()) return; PSCIFUNC_T sciFunc; void* sciPtr; if (fsType.empty()) fsType = getDocFoldStructType(); if (fsType.empty()) return; vector<FoldingInfo> foldingInfoList{}; _configIO.getFoldStructFoldingInfo(Utils::NarrowToWide(fsType), foldingInfoList); if (!getDirectScintillaFunc(sciFunc, sciPtr)) return; const size_t regexedCount{ vRecInfo.size() }; string lineTextCStr(FW_LINE_MAX_LENGTH, '\0'); string recStartText{}, eolMarker{}; size_t eolMarkerLen, eolMarkerPos, recStartLine{}, startPos, endPos, recStartPos{}; bool newRec{ TRUE }; vector<FoldingInfo> foldStack{ {} }; int currentLevel{ 0 }; bool bFoldExists{}; eolMarker = _configIO.getConfigStringA(fileType, "RecordTerminator"); eolMarkerLen = eolMarker.length(); #if FW_DEBUG_FOLD_INFO wstring info{ L"Line\tRec. Type\tLevel\n" }; #endif // FW_DEBUG_FOLD_INFO SetCursor(LoadCursor(NULL, IDC_WAIT)); const intptr_t lineCount{ sciFunc(sciPtr, SCI_GETLINECOUNT, NULL, NULL) }; const intptr_t endLine{ lineCount }; for (intptr_t currentLine{}; currentLine < endLine; ++currentLine) { if (sciFunc(sciPtr, SCI_LINELENGTH, currentLine, NULL) > FW_LINE_MAX_LENGTH) { continue; } sciFunc(sciPtr, SCI_GETLINE, currentLine, (LPARAM)lineTextCStr.c_str()); startPos = sciFunc(sciPtr, SCI_POSITIONFROMLINE, currentLine, NULL); endPos = sciFunc(sciPtr, SCI_GETLINEENDPOSITION, currentLine, NULL); string_view lineText{ lineTextCStr.c_str(), static_cast<size_t>(endPos - startPos) }; if (newRec) { recStartLine = currentLine; recStartPos = startPos; recStartText = lineText; } if (newRec && lineText.empty()) { continue; } if (eolMarkerLen == 0) { newRec = TRUE; eolMarkerPos = endPos; } else if (lineText.length() > eolMarkerLen && (lineText.substr(lineText.length() - eolMarkerLen) == eolMarker)) { newRec = TRUE; eolMarkerPos = endPos - eolMarkerLen; } else if (currentLine < endLine) { newRec = FALSE; continue; } else { eolMarkerPos = endPos; } size_t regexIndex{}; while (regexIndex < regexedCount) { if (regex_match(recStartText, vRecInfo[regexIndex].regExpr)) break; ++regexIndex; } if (regexIndex >= regexedCount) { sciFunc(sciPtr, SCI_SETFOLDLEVEL, currentLine, SC_FOLDLEVELBASE | currentLevel); continue; } FoldingInfo* pLevelFI{ &foldStack.back() }; wchar_t recTypeCode[7]; swprintf(recTypeCode, 7, L"REC%03d", static_cast<int>(regexIndex + 1)); bool bFoldLevelRec{}; FoldingInfo* pLineFI{}; for (size_t j{}; j < foldingInfoList.size(); ++j) { pLineFI = &foldingInfoList[j]; if (static_cast<int>(regexIndex + 1) == pLineFI->recTypeIndex) { bFoldLevelRec = TRUE; break; } } if (bFoldLevelRec) { while (currentLevel > 0 && (pLevelFI->priority > pLineFI->priority || (pLevelFI->priority == pLineFI->priority && !pLineFI->recursive) || (!pLevelFI->endRecords.empty() && pLevelFI->endRecords.find(recTypeCode) != string::npos))) { foldStack.pop_back(); pLevelFI = &foldStack.back(); --currentLevel; if (pLevelFI->recursive && pLevelFI->priority <= pLineFI->priority) break; } #if FW_DEBUG_FOLD_INFO //sciFunc(sciPtr, SCI_SETLINEINDENTATION, currentLine, (currentLevel * 2)); if (currentLine < 50) info += to_wstring(currentLine + 1) + L"\t" + recTypeCode + L"\t" + to_wstring(currentLevel + 1) + L"\n"; #endif // FW_DEBUG_FOLD_INFO sciFunc(sciPtr, SCI_SETFOLDLEVEL, currentLine, SC_FOLDLEVELHEADERFLAG | SC_FOLDLEVELBASE | currentLevel); foldStack.emplace_back(*pLineFI); ++currentLevel; bFoldExists = true; } else { if (currentLevel > 0 && !pLevelFI->endRecords.empty() && pLevelFI->endRecords.find(recTypeCode) != string::npos) { foldStack.pop_back(); pLevelFI = &foldStack.back(); sciFunc(sciPtr, SCI_SETFOLDLEVEL, currentLine, SC_FOLDLEVELBASE | currentLevel--); } else sciFunc(sciPtr, SCI_SETFOLDLEVEL, currentLine, SC_FOLDLEVELBASE | currentLevel); #if FW_DEBUG_FOLD_INFO //sciFunc(sciPtr, SCI_SETLINEINDENTATION, currentLine, (currentLevel * 2)); if (currentLine < 50) info += to_wstring(currentLine + 1) + L"\t" + recTypeCode + L"\t" + to_wstring(currentLevel + 1) + L"\n"; #endif // FW_DEBUG_FOLD_INFO } } SetCursor(LoadCursor(NULL, IDC_ARROW)); enableFoldedControls(bFoldExists); setDocFolded(bFoldExists); #if FW_DEBUG_FOLD_INFO MessageBox(_hSelf, (_configIO.getActiveConfigFile(_configIO.CONFIG_FOLDSTRUCTS) + L"\n\n" + info).c_str(), L"Fold Levels Info", MB_OK); #endif // FW_DEBUG_FOLD_INFO } void VisualizerPanel::removeFolding() { // First, unfold all levels expandFoldLevel(TRUE, MAXBYTE); PSCIFUNC_T sciFunc; void* sciPtr; if (!getDirectScintillaFunc(sciFunc, sciPtr)) return; SetCursor(LoadCursor(NULL, IDC_WAIT)); const intptr_t lineCount{ sciFunc(sciPtr, SCI_GETLINECOUNT, NULL, NULL) }; const intptr_t endLine{ lineCount }; for (intptr_t currentLine{}; currentLine < endLine; ++currentLine) { sciFunc(sciPtr, SCI_SETFOLDLEVEL, currentLine, SC_FOLDLEVELBASE); } SetCursor(LoadCursor(NULL, IDC_ARROW)); enableFoldedControls(FALSE); setDocFolded(FALSE); } void VisualizerPanel::enableFoldableControls(bool bFoldable) { EnableWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_FOLDING_APPLY_BTN), bFoldable); } void VisualizerPanel::enableFoldedControls(bool bFolded) { SetWindowText(GetDlgItem(_hSelf, IDC_VIZPANEL_FOLDING_APPLY_BTN), bFolded ? VIZPANEL_FOLD_REAPPLY_BTN : VIZPANEL_FOLD_APPLY_BTN); EnableWindow(GetDlgItem(_hSelf, IDC_VIZPANEL_FOLDING_REMOVE_BTN), bFolded); if (bFolded) { HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; SendMessage(hScintilla, SCI_SETMARGINTYPEN, FOLDING_MARGIN, SC_MARGIN_SYMBOL); SendMessage(hScintilla, SCI_SETMARGINMASKN, FOLDING_MARGIN, SC_MASK_FOLDERS); SendMessage(hScintilla, SCI_SETMARGINSENSITIVEN, FOLDING_MARGIN, TRUE); SendMessage(hScintilla, SCI_SETMARGINWIDTHN, FOLDING_MARGIN, Utils::scaleDPIX(14)); SendMessage(hScintilla, SCI_SETFOLDFLAGS, SC_FOLDFLAG_LINEBEFORE_CONTRACTED | SC_FOLDFLAG_LINEAFTER_CONTRACTED, NULL); if (SendMessage(hScintilla, SCI_MARKERSYMBOLDEFINED, SC_MARKNUM_FOLDEROPEN, 0) < SC_MARK_ARROWDOWN) { SendMessage(hScintilla, SCI_MARKERDEFINE, SC_MARKNUM_FOLDEROPEN, SC_MARK_BOXMINUS); SendMessage(hScintilla, SCI_MARKERDEFINE, SC_MARKNUM_FOLDER, SC_MARK_BOXPLUS); SendMessage(hScintilla, SCI_MARKERDEFINE, SC_MARKNUM_FOLDERSUB, SC_MARK_VLINE); SendMessage(hScintilla, SCI_MARKERDEFINE, SC_MARKNUM_FOLDERTAIL, SC_MARK_LCORNER); SendMessage(hScintilla, SCI_MARKERDEFINE, SC_MARKNUM_FOLDERMIDTAIL, SC_MARK_TCORNER); SendMessage(hScintilla, SCI_MARKERDEFINE, SC_MARKNUM_FOLDEROPENMID, SC_MARK_BOXMINUSCONNECTED); SendMessage(hScintilla, SCI_MARKERDEFINE, SC_MARKNUM_FOLDEREND, SC_MARK_BOXPLUSCONNECTED); } } } void VisualizerPanel::toggleFolding() { HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; intptr_t currentLine, headerLine; currentLine = SendMessage(hScintilla, SCI_LINEFROMPOSITION, SendMessage(hScintilla, SCI_GETCURRENTPOS, 0, 0), 0); if (SendMessage(hScintilla, SCI_GETFOLDLEVEL, currentLine, 0) & SC_FOLDLEVELHEADERFLAG) headerLine = currentLine; else { headerLine = SendMessage(hScintilla, SCI_GETFOLDPARENT, currentLine, 0); if (headerLine == -1) return; } SendMessage(hScintilla, SCI_TOGGLEFOLD, headerLine, 0); renderCurrentPage(); } int VisualizerPanel::foldLevelFromPopup(bool bFold) { constexpr int itemCount{ 10 }; HMENU hPopupMenu = CreatePopupMenu(); AppendMenu(hPopupMenu, MF_STRING, MAXBYTE, L"All Levels"); AppendMenu(hPopupMenu, MF_SEPARATOR, NULL, NULL); for (int i{1}; i <= itemCount; ++i) { AppendMenu(hPopupMenu, MF_STRING, i, (L"Level " + to_wstring(i)).c_str()); } RECT rc; GetWindowRect(GetDlgItem(_hSelf, bFold ? IDC_VIZPANEL_FOLDING_FOLD_BTN : IDC_VIZPANEL_FOLDING_UNFOLD_BTN), &rc); int option = TrackPopupMenu(hPopupMenu, (bFold ? TPM_LEFTALIGN : TPM_RIGHTALIGN) | TPM_TOPALIGN | TPM_LEFTBUTTON | TPM_RETURNCMD | TPM_NONOTIFY, (bFold ? rc.left : rc.right), rc.bottom, 0, _hSelf, NULL); for (int i{}; i < itemCount; ++i) { RemoveMenu(hPopupMenu, 0, MF_BYPOSITION); } DestroyMenu(hPopupMenu); return (option == MAXBYTE ? MAXBYTE : option - 1); } void VisualizerPanel::expandFoldLevel(bool bExpand, int foldLevel) { if (foldLevel < 0) return; HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; SetCursor(LoadCursor(NULL, IDC_WAIT)); intptr_t lineCount{ SendMessage(hScintilla, SCI_GETLINECOUNT, 0, 0) }; for (intptr_t line{ 0 }; line < lineCount; ++line) { int level{ static_cast<int>(SendMessage(hScintilla, SCI_GETFOLDLEVEL, line, 0)) }; if (!(level & SC_FOLDLEVELHEADERFLAG)) continue; level -= SC_FOLDLEVELBASE; if (foldLevel < MAXBYTE && foldLevel != (level & SC_FOLDLEVELNUMBERMASK)) continue; if (static_cast<bool>(SendMessage(hScintilla, SCI_GETFOLDEXPANDED, line, 0)) != bExpand) SendMessage(hScintilla, SCI_TOGGLEFOLD, line, 0); } SetCursor(LoadCursor(NULL, IDC_ARROW)); renderCurrentPage(); } void VisualizerPanel::foldLevelMenu() { expandFoldLevel(FALSE, foldLevelFromPopup(TRUE)); } void VisualizerPanel::unfoldLevelMenu() { expandFoldLevel(TRUE, foldLevelFromPopup(FALSE)); } void VisualizerPanel::showFoldStructDialog() { _foldStructDlg.doDialog((HINSTANCE)_gModule); } DWORD __stdcall VisualizerPanel::threadPositionHighlighter(void*) { HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return FALSE; // Look for Idem Potency Hold if (idemPotentKey) // Idem Potency check failed. Another thread is processing this same function. Return immediately. return FALSE; else // OK to continue. Set Idem Potency Hold idemPotentKey = TRUE; // Modify caret styleInfo briefly to highlight the new position int currCaret = static_cast<int>(SendMessage(hScintilla, SCI_GETCARETSTYLE, 0, 0)); SendMessage(hScintilla, SCI_SETCARETSTYLE, CARETSTYLE_BLOCK, 0); Sleep(_configIO.getPreferenceInt(PREF_CARET_FLASH, 5) * 1000); SendMessage(hScintilla, SCI_SETCARETSTYLE, currCaret, 0); SendMessage(hScintilla, SCI_BRACEHIGHLIGHT, SendMessage(hScintilla, SCI_GETCURRENTPOS, 0, 0), -1); // Clear Idem Potency Hold idemPotentKey = FALSE; return TRUE; }
78,763
C++
.cpp
1,813
36.771098
145
0.670762
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,106
PreferencesDialog.cpp
shriprem_FWDataViz/src/Dialogs/PreferencesDialog.cpp
#include "PreferencesDialog.h" #include "VisualizerPanel.h" constexpr int PREF_TIP_LONG{ 30 }; extern VisualizerPanel _vizPanel; void PreferencesDialog::doDialog(HINSTANCE hInst) { if (!isCreated()) { Window::init(hInst, nppData._nppHandle); create(IDD_PREFERENCES_DIALOG); } initCheckbox(IDC_PREF_CLEARVIZ_AUTO, PREF_CLEARVIZ_AUTO, FALSE); initCheckbox(IDC_PREF_CLEARVIZ_PANEL, PREF_CLEARVIZ_PANEL, FALSE); initCheckbox(IDC_PREF_MBCHARS_STATE, PREF_MBCHARS_SHOW, FALSE); initCheckbox(IDC_PREF_HOP_FIELD_LEFT_EDGE, PREF_HOP_RT_LEFT_EDGE, FALSE); using Utils::addTooltip; addTooltip(_hSelf, IDC_PREF_CLEARVIZ_AUTO, L"", PREF_CLEARVIZ_AUTO_TIP, PREF_TIP_LONG, TRUE); addTooltip(_hSelf, IDC_PREF_CLEARVIZ_PANEL, L"", PREF_CLEARVIZ_PANEL_TIP, PREF_TIP_LONG, TRUE); addTooltip(_hSelf, IDC_PREF_MBCHARS_STATE, L"", PREF_MBCHARS_STATE_TIP, PREF_TIP_LONG, TRUE); addTooltip(_hSelf, IDC_PREF_HOP_FIELD_LEFT_EDGE, L"", PREF_HOP_RT_LEFT_EDGE_TIP, PREF_TIP_LONG, TRUE); displayFoldLineColor(); int foldLineAlpha{ _configIO.getPreferenceInt(PREF_FOLDLINE_ALPHA, MAXBYTE) }; SendMessage(GetDlgItem(_hSelf, IDC_PREF_FOLD_LINE_ALPHA_SLIDER), TBM_SETPOS, TRUE, foldLineAlpha); if constexpr(_gLanguage != LANG_ENGLISH) localize(); goToCenter(); SendMessage(_hParent, NPPM_DMMSHOW, 0, (LPARAM)_hSelf); } void PreferencesDialog::refreshDarkMode() { NPPDM_AutoThemeChildControls(_hSelf); redraw(); SendMessage(GetDlgItem(_hSelf, IDC_PREF_FOLD_LINE_ALPHA_SLIDER), TBM_SETRANGEMIN, FALSE, 0); } INT_PTR PreferencesDialog::run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: switch LOWORD(wParam) { case IDC_PREF_CLEARVIZ_AUTO: setCheckbox(IDC_PREF_CLEARVIZ_AUTO, PREF_CLEARVIZ_AUTO); break; case IDC_PREF_CLEARVIZ_PANEL: setCheckbox(IDC_PREF_CLEARVIZ_PANEL, PREF_CLEARVIZ_PANEL); break; case IDC_PREF_MBCHARS_STATE: setCheckbox(IDC_PREF_MBCHARS_STATE, PREF_MBCHARS_SHOW); _vizPanel.initMBCharsCheckbox(); break; case IDC_PREF_HOP_FIELD_LEFT_EDGE: setCheckbox(IDC_PREF_HOP_FIELD_LEFT_EDGE, PREF_HOP_RT_LEFT_EDGE); _vizPanel.updateHopRightTip(); break; case IDC_PREF_FOLD_LINE_COLOR: chooseColor(); break; case IDCANCEL: case IDCLOSE: display(FALSE); return TRUE; } break; case WM_HSCROLL: if (lParam == (LPARAM)GetDlgItem(_hSelf, IDC_PREF_FOLD_LINE_ALPHA_SLIDER)) setFoldLineAlpha(); break; case WM_INITDIALOG: NPPDM_AutoSubclassAndThemeChildControls(_hSelf); break; case WM_CTLCOLORDLG: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLORSTATIC: { INT_PTR ptr = colorStaticControl(wParam, lParam); if (ptr != NULL) return ptr; if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } break; } case WM_CTLCOLORLISTBOX: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorListbox(wParam, lParam); } break; case WM_PRINTCLIENT: if (NPPDM_IsEnabled()) return TRUE; break; } return FALSE; } void PreferencesDialog::localize() { SetWindowText(_hSelf, PREFERENCES_DIALOG_TITLE); SetDlgItemText(_hSelf, IDC_PREF_CLEARVIZ_AUTO, PREFERENCES_CLEARVIZ_AUTO); SetDlgItemText(_hSelf, IDC_PREF_CLEARVIZ_PANEL, PREFERENCES_CLEARVIZ_PANEL); SetDlgItemText(_hSelf, IDC_PREF_MBCHARS_STATE, PREFERENCES_MBCHARS_STATE); SetDlgItemText(_hSelf, IDC_PREF_HOP_FIELD_LEFT_EDGE, PREFERENCES_HOP_LEFT_EDGE); SetDlgItemText(_hSelf, IDCLOSE, PREFERENCES_CLOSE_BTN); } void PreferencesDialog::initCheckbox(int nIDButton, const string& preference, bool defaultVal) { CheckDlgButton(_hSelf, nIDButton, _configIO.getPreferenceBool(preference, defaultVal) ? BST_CHECKED : BST_UNCHECKED); } void PreferencesDialog::setCheckbox(int nIDButton, const string& preference) { bool checked{ IsDlgButtonChecked(_hSelf, nIDButton) == BST_CHECKED }; _configIO.setPreferenceBool(preference, checked); } void PreferencesDialog::chooseColor() { COLORREF customColors[16]{}; CHOOSECOLOR cc; ZeroMemory(&cc, sizeof(cc)); cc.lStructSize = sizeof(cc); cc.hwndOwner = _hSelf; cc.rgbResult = getPreferenceFoldLineColor(); cc.lpCustColors = (LPDWORD)customColors; cc.Flags = CC_FULLOPEN | CC_RGBINIT; if (!ChooseColor(&cc)) return; setPreferenceFoldLineColor(cc.rgbResult); displayFoldLineColor(); } COLORREF PreferencesDialog::getPreferenceFoldLineColor() { return Utils::intToRGB(Utils::StringtoInt(_configIO.getPreference(PREF_FOLDLINE_COLOR, "0"), 16)); } void PreferencesDialog::setPreferenceFoldLineColor(COLORREF rgbColor) { wchar_t hexColor[10]; swprintf(hexColor, 7, L"%06X", static_cast<int>(rgbColor)); _configIO.setPreference(PREF_FOLDLINE_COLOR, hexColor); } void PreferencesDialog::displayFoldLineColor() { Utils::setFontRegular(_hSelf, IDC_PREF_FOLD_LINE_COLOR); applyFoldLineColorAlpha(); } INT_PTR PreferencesDialog::colorStaticControl(WPARAM wParam, LPARAM lParam) { HDC hdc = (HDC)wParam; DWORD ctrlID = GetDlgCtrlID((HWND)lParam); COLORREF rgbColor{ getPreferenceFoldLineColor() }; if (hbr != NULL) DeleteObject(hbr); if (ctrlID == IDC_PREF_FOLD_LINE_COLOR) { SetBkColor(hdc, rgbColor); hbr = CreateSolidBrush(rgbColor); return (INT_PTR)hbr; } return NULL; } void PreferencesDialog::setFoldLineAlpha() { _configIO.setPreferenceInt(PREF_FOLDLINE_ALPHA, static_cast<int>(SendMessage(GetDlgItem(_hSelf, IDC_PREF_FOLD_LINE_ALPHA_SLIDER), TBM_GETPOS, 0, 0))); applyFoldLineColorAlpha(); } void PreferencesDialog::applyFoldLineColorAlpha() { HWND hScintilla{ getCurrentScintilla() }; if (!hScintilla) return; int foldColorAlpha{ static_cast<int>(getPreferenceFoldLineColor()) }; foldColorAlpha |= _configIO.getPreferenceInt(PREF_FOLDLINE_ALPHA, MAXBYTE) << 24; SendMessage(hScintilla, SCI_SETELEMENTCOLOUR, SC_ELEMENT_FOLD_LINE, foldColorAlpha); }
6,225
C++
.cpp
152
35.934211
120
0.723503
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,107
StyleDefComponent.cpp
shriprem_FWDataViz/src/Dialogs/StyleDefComponent.cpp
#include "StyleDefComponent.h" StyleDefComponent::~StyleDefComponent() { if (hbr != NULL) DeleteObject(hbr); } void StyleDefComponent::initComponent(HWND hDlg) { _hDialog = hDlg; SendDlgItemMessage(_hDialog, IDC_STYLE_DEF_BACK_EDIT, EM_LIMITTEXT, 6, NULL); SendDlgItemMessage(_hDialog, IDC_STYLE_DEF_FORE_EDIT, EM_LIMITTEXT, 6, NULL); SetWindowSubclass(GetDlgItem(_hDialog, IDC_STYLE_DEF_BACK_EDIT), procHexColorEditControl, NULL, NULL); SetWindowSubclass(GetDlgItem(_hDialog, IDC_STYLE_DEF_FORE_EDIT), procHexColorEditControl, NULL, NULL); bool recentOS = Utils::checkBaseOS(WV_VISTA); wstring fontName = recentOS ? L"Consolas" : L"Courier New"; int fontHeight = recentOS ? 8 : 7; Utils::setFont(_hDialog, IDC_STYLE_DEF_PREVIEW_BOX, fontName, fontHeight); setPangram(); } void StyleDefComponent::localize() const { SetDlgItemText(_hDialog, IDC_STYLE_DEF_GROUP_BOX, STYLE_DEF_GROUP_BOX); SetDlgItemText(_hDialog, IDC_STYLE_DEF_BACK_LABEL, STYLE_DEF_BACK_LABEL); SetDlgItemText(_hDialog, IDC_STYLE_DEF_FORE_LABEL, STYLE_DEF_FORE_LABEL); SetDlgItemText(_hDialog, IDC_STYLE_DEF_BOLD, STYLE_DEF_BOLD); SetDlgItemText(_hDialog, IDC_STYLE_DEF_ITALICS, STYLE_DEF_ITALICS); SetDlgItemText(_hDialog, IDC_STYLE_DEF_PREVIEW_LABEL, STYLE_DEF_PREVIEW_LABEL); } int StyleDefComponent::getStyleDefColor(bool back) const { TCHAR buf[10]; GetDlgItemText(_hDialog, back ? IDC_STYLE_DEF_BACK_EDIT : IDC_STYLE_DEF_FORE_EDIT, buf, 7); return Utils::StringtoInt(buf, 16); } void StyleDefComponent::setStyleDefColor(bool setEdit, int color, bool back) { if (setEdit) { TCHAR buf[10]; swprintf(buf, 7, L"%06X", color); SetDlgItemText(_hDialog, back ? IDC_STYLE_DEF_BACK_EDIT : IDC_STYLE_DEF_FORE_EDIT, buf); } // Set styleBack | styleFore here. Will be used in WM_CTLCOLORSTATIC, triggered by the setFontRegular() calls styleDefColor = TRUE; (back ? styleBack : styleFore) = Utils::intToRGB(color); Utils::setFontRegular(_hDialog, back ? IDC_STYLE_DEF_BACKCOLOR : IDC_STYLE_DEF_FORECOLOR); setOutputFontStyle(); } void StyleDefComponent::setOutputFontStyle() const { Utils::setFontRegular(_hDialog, IDC_STYLE_DEF_PREVIEW_BOX); if (IsDlgButtonChecked(_hDialog, IDC_STYLE_DEF_BOLD) == BST_CHECKED) Utils::setFontBold(_hDialog, IDC_STYLE_DEF_PREVIEW_BOX); if (IsDlgButtonChecked(_hDialog, IDC_STYLE_DEF_ITALICS) == BST_CHECKED) Utils::setFontItalic(_hDialog, IDC_STYLE_DEF_PREVIEW_BOX); } void StyleDefComponent::fillStyleDefs(StyleInfo& style) { CheckDlgButton(_hDialog, IDC_STYLE_DEF_BOLD, style.bold ? BST_CHECKED : BST_UNCHECKED); CheckDlgButton(_hDialog, IDC_STYLE_DEF_ITALICS, style.italics ? BST_CHECKED : BST_UNCHECKED); setStyleDefColor(TRUE, style.backColor, TRUE); setStyleDefColor(TRUE, style.foreColor, FALSE); cleanStyleDefs = TRUE; } void StyleDefComponent::setPangram() const { constexpr int count{ 10 }; wstring pangrams[count] = { L"SPHINX OF BLACK QUARTZ,\r\nJUDGE MY VOW.", L"A QUART JAR OF OIL\r\nMIXED WITH ZINC OXIDE\r\nMAKES A VERY BRIGHT PAINT.", L"A WIZARD'S JOB IS TO\r\nVEX CHUMPS QUICKLY IN FOG.", L"AMAZINGLY FEW DISCOTHEQUES\r\nPROVIDE JUKEBOXES.", L"PACK MY BOX WITH\r\nFIVE DOZEN LIQUOR JUGS.", L"THE LAZY MAJOR WAS FIXING\r\nCUPID'S BROKEN QUIVER.", L"MY FAXED JOKE WON A PAGER\r\nIN THE CABLE TV QUIZ SHOW.", L"THE FIVE BOXING WIZARDS\r\nJUMP QUICKLY.", L"FEW BLACK TAXIS\r\nDRIVE UP MAJOR ROADS\r\nON QUIET HAZY NIGHTS.", L"WE PROMPTLY JUDGED\r\nANTIQUE IVORY BUCKLES\r\nFOR THE NEXT PRIZE." }; SetDlgItemText(_hDialog, IDC_STYLE_DEF_PREVIEW_BOX, (pangrams[rand() % count]).c_str()); } INT_PTR StyleDefComponent::colorStaticControl(WPARAM wParam, LPARAM lParam) { HDC hdc = (HDC)wParam; DWORD ctrlID = GetDlgCtrlID((HWND)lParam); if (hbr != NULL) DeleteObject(hbr); switch (ctrlID) { case IDC_STYLE_DEF_BACKCOLOR: SetBkColor(hdc, styleBack); hbr = CreateSolidBrush(styleBack); return (INT_PTR)hbr; case IDC_STYLE_DEF_FORECOLOR: SetBkColor(hdc, styleFore); hbr = CreateSolidBrush(styleFore); return (INT_PTR)hbr; case IDC_STYLE_DEF_PREVIEW_BOX: SetBkColor(hdc, styleBack); SetTextColor(hdc, styleFore); hbr = CreateSolidBrush(styleBack); return (INT_PTR)hbr; default: return NULL; } } void StyleDefComponent::chooseStyleDefColor(bool back) { int color = getStyleDefColor(back); CHOOSECOLOR cc; ZeroMemory(&cc, sizeof(cc)); cc.lStructSize = sizeof(cc); cc.hwndOwner = _hDialog; cc.rgbResult = Utils::intToRGB(color); cc.lpCustColors = (LPDWORD)customColors; cc.Flags = CC_FULLOPEN | CC_RGBINIT; if (!ChooseColor(&cc)) return; color = static_cast<int>(cc.rgbResult); setStyleDefColor(TRUE, color, back); cleanStyleDefs = FALSE; } LRESULT CALLBACK procHexColorEditControl(HWND hwnd, UINT messageId, WPARAM wParam, LPARAM lParam, UINT_PTR, DWORD_PTR) { switch (messageId) { case WM_CHAR: { char ch{ static_cast<char>(wParam) }; if (!((ch == VK_BACK) || (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))) { Utils::showEditBalloonTip(hwnd, STYLE_DEF_HEX_TITLE, STYLE_DEF_HEX_CHARS_ONLY); return FALSE; } break; } case WM_PASTE: { wstring clipText; Utils::getClipboardText(GetParent(hwnd), clipText); if (!regex_match(clipText, std::wregex(L"^[0-9A-Fa-f]{0,6}$"))) { Utils::showEditBalloonTip(hwnd, STYLE_DEF_HEX_TITLE, STYLE_DEF_HEX_CHARS_ONLY); return FALSE; } break; } } return DefSubclassProc(hwnd, messageId, wParam, lParam); }
5,751
C++
.cpp
131
39.198473
120
0.70584
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,108
ConfigureDialog.cpp
shriprem_FWDataViz/src/Dialogs/ConfigureDialog.cpp
#include "ConfigureDialog.h" #include "EximFileTypeDialog.h" #include "FieldTypeDialog.h" #pragma comment(lib, "comctl32.lib") extern HINSTANCE _gModule; extern ConfigureDialog _configDlg; EximFileTypeDialog _eximDlg; FieldTypeDialog _fieldTypeDlg; void ConfigureDialog::doDialog(HINSTANCE hInst) { if (!isCreated()) { Window::init(hInst, nppData._nppHandle); create(IDD_FILE_TYPE_DEFINER_DIALOG); } hFilesLB = GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FILE_LIST_BOX); hFileEOL = GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FILE_EOL_EDIT); hFileThemes = GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FILE_THEME_LIST); hRecsLB = GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_LIST_BOX); hRecStart = GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_START_EDIT); hRecRegex = GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_REGEX_EDIT); hRecThemes = GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_THEME_LIST); hFieldLabels = GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FIELD_LABELS_EDIT); hFieldWidths = GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FIELD_WIDTHS_EDIT); for (int i{}, id{ IDC_FWVIZ_DEF_ADFT_LINE_EDIT_01 }; i < ADFT_MAX; ++i) { hADFTLine[i] = GetDlgItem(_hSelf, id++); hADFTRegex[i] = GetDlgItem(_hSelf, id++); } SendDlgItemMessage(_hSelf, IDC_FWVIZ_DEF_FILE_DESC_EDIT, EM_LIMITTEXT, MAX_PATH, NULL); SendDlgItemMessage(_hSelf, IDC_FWVIZ_DEF_REC_DESC_EDIT, EM_LIMITTEXT, MAX_PATH, NULL); SendMessage(hFileEOL, EM_LIMITTEXT, MAX_PATH, NULL); SendMessage(hADFTRegex[0], EM_LIMITTEXT, MAX_PATH, NULL); SendMessage(hADFTRegex[1], EM_LIMITTEXT, MAX_PATH, NULL); SendMessage(hADFTRegex[2], EM_LIMITTEXT, MAX_PATH, NULL); SendMessage(hRecStart, EM_LIMITTEXT, MAX_PATH, NULL); SendMessage(hRecRegex, EM_LIMITTEXT, MAX_PATH, NULL); SendMessage(hFieldLabels, EM_LIMITTEXT, FW_LINE_MAX_LENGTH, NULL); SendMessage(hFieldWidths, EM_LIMITTEXT, FW_LINE_MAX_LENGTH, NULL); SetWindowSubclass(hFieldLabels, procFieldEditMessages, NULL, NULL); SetWindowSubclass(hFieldWidths, procFieldEditMessages, NULL, NULL); SetWindowSubclass(hADFTLine[0], procNumberEditControl, NULL, NULL); SetWindowSubclass(hADFTLine[1], procNumberEditControl, NULL, NULL); SetWindowSubclass(hADFTLine[2], procNumberEditControl, NULL, NULL); HWND hToolTip{}; using Utils::addTooltip; using Utils::loadBitmap; loadBitmap(_hSelf, IDC_FWVIZ_DEF_FILE_DOWN_BUTTON, IDB_VIZ_MOVE_DOWN_BITMAP); addTooltip(_hSelf, IDC_FWVIZ_DEF_FILE_DOWN_BUTTON, L"", FWVIZ_DEF_FILE_MOVE_DOWN, FALSE); loadBitmap(_hSelf, IDC_FWVIZ_DEF_FILE_UP_BUTTON, IDB_VIZ_MOVE_UP_BITMAP); addTooltip(_hSelf, IDC_FWVIZ_DEF_FILE_UP_BUTTON, L"", FWVIZ_DEF_FILE_MOVE_UP, FALSE); loadBitmap(_hSelf, IDC_FWVIZ_DEF_MCBS_INFO_BUTTON, IDB_VIZ_INFO_BITMAP); hToolTip = addTooltip(_hSelf, IDC_FWVIZ_DEF_MCBS_INFO_BUTTON, FWVIZ_DEF_MCBS_HINT_TITLE, FWVIZ_DEF_MCBS_HINT_TEXT, TRUE); SendMessage(hToolTip, TTM_SETDELAYTIME, TTDT_AUTOPOP, (LPARAM)(30000)); loadBitmap(_hSelf, IDC_FWVIZ_DEF_ADFT_INFO_BUTTON, IDB_VIZ_INFO_BITMAP); hToolTip = addTooltip(_hSelf, IDC_FWVIZ_DEF_ADFT_INFO_BUTTON, FWVIZ_DEF_ADFT_HINT_TITLE, FWVIZ_DEF_ADFT_HINT_TEXT, TRUE); SendMessage(hToolTip, TTM_SETDELAYTIME, TTDT_AUTOPOP, (LPARAM)(30000)); loadBitmap(_hSelf, IDC_FWVIZ_DEF_REC_DOWN_BUTTON, IDB_VIZ_MOVE_DOWN_BITMAP); addTooltip(_hSelf, IDC_FWVIZ_DEF_REC_DOWN_BUTTON, L"", FWVIZ_DEF_REC_MOVE_DOWN, FALSE); loadBitmap(_hSelf, IDC_FWVIZ_DEF_REC_UP_BUTTON, IDB_VIZ_MOVE_UP_BITMAP); addTooltip(_hSelf, IDC_FWVIZ_DEF_REC_UP_BUTTON, L"", FWVIZ_DEF_REC_MOVE_UP, FALSE); loadBitmap(_hSelf, IDC_FWVIZ_DEF_REC_THEME_INFOBTN, IDB_VIZ_INFO_BITMAP); hToolTip = addTooltip(_hSelf, IDC_FWVIZ_DEF_REC_THEME_INFOBTN, FWVIZ_DEF_RECTHEME_HINT_HDR, FWVIZ_DEF_RECTHEME_HINT_TXT, TRUE); SendMessage(hToolTip, TTM_SETDELAYTIME, TTDT_AUTOPOP, (LPARAM)(30000)); loadBitmap(_hSelf, IDC_FWVIZ_DEF_INFO_BUTTON, IDB_VIZ_INFO_BITMAP); addTooltip(_hSelf, IDC_FWVIZ_DEF_INFO_BUTTON, L"", VIZ_PANEL_INFO_TIP, FALSE); Utils::setFontUnderline(_hSelf, IDC_FWVIZ_DEF_ADFT_GROUP_LABEL); if constexpr(_gLanguage != LANG_ENGLISH) localize(); goToCenter(); SendMessage(_hParent, NPPM_DMMSHOW, 0, (LPARAM)_hSelf); loadConfigInfo(); fillFileTypes(); } void ConfigureDialog::display(bool toShow) { StaticDialog::display(toShow); if (!toShow) { if (_eximDlg.isCreated() && _eximDlg.isVisible()) _eximDlg.display(FALSE); if (_fieldTypeDlg.isCreated() && _fieldTypeDlg.isVisible()) _fieldTypeDlg.display(FALSE); } } void ConfigureDialog::refreshDarkMode() { NPPDM_AutoThemeChildControls(_hSelf); redraw(); if (_eximDlg.isCreated()) _eximDlg.refreshDarkMode(); if (_fieldTypeDlg.isCreated()) _fieldTypeDlg.refreshDarkMode(); } INT_PTR CALLBACK ConfigureDialog::run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: switch LOWORD(wParam) { case IDC_FWVIZ_DEF_FILE_LIST_BOX: switch HIWORD(wParam) { case LBN_SELCHANGE: onFileTypeSelect(); break; } break; case IDC_FWVIZ_DEF_FILE_DOWN_BUTTON: moveFileType(MOVE_DOWN); break; case IDC_FWVIZ_DEF_FILE_UP_BUTTON: moveFileType(MOVE_UP); break; case IDC_FWVIZ_DEF_MCBS_INFO_BUTTON: ShellExecute(NULL, L"open", FWVIZ_DEF_MCBS_INFO_README, NULL, NULL, SW_SHOW); break; case IDC_FWVIZ_DEF_ADFT_INFO_BUTTON: ShellExecute(NULL, L"open", FWVIZ_DEF_ADFT_INFO_README, NULL, NULL, SW_SHOW); break; case IDC_FWVIZ_DEF_REC_THEME_INFOBTN: ShellExecute(NULL, L"open", FWVIZ_RT_THEME_INFO_README, NULL, NULL, SW_SHOW); break; case IDC_FWVIZ_DEF_FILE_DESC_EDIT: case IDC_FWVIZ_DEF_FILE_EOL_EDIT: case IDC_FWVIZ_DEF_MCBS_CHECKBOX: case IDC_FWVIZ_DEF_FILE_THEME_LIST: case IDC_FWVIZ_DEF_ADFT_LINE_EDIT_01: case IDC_FWVIZ_DEF_ADFT_REGEX_EDT_01: case IDC_FWVIZ_DEF_ADFT_LINE_EDIT_02: case IDC_FWVIZ_DEF_ADFT_REGEX_EDT_02: case IDC_FWVIZ_DEF_ADFT_LINE_EDIT_03: case IDC_FWVIZ_DEF_ADFT_REGEX_EDT_03: switch HIWORD(wParam) { case BN_CLICKED: case EN_CHANGE: case CBN_SELCHANGE: if (!loadingEdits) { cleanFileVals = FALSE; enableFileSelection(); } break; } break; case IDC_FWVIZ_DEF_FILE_ACCEPT_BTN: case IDC_FWVIZ_DEF_FILE_RESET_BTN: fileEditAccept(LOWORD(wParam) == IDC_FWVIZ_DEF_FILE_ACCEPT_BTN); break; case IDC_FWVIZ_DEF_FILE_NEW_BTN: fileEditNew(); break; case IDC_FWVIZ_DEF_FILE_CLONE_BTN: fileEditClone(); break; case IDC_FWVIZ_DEF_FILE_DEL_BTN: fileEditDelete(); break; case IDC_FWVIZ_DEF_REC_LIST_BOX: switch HIWORD(wParam) { case LBN_SELCHANGE: onRecTypeSelect(); break; } break; case IDC_FWVIZ_DEF_REC_DOWN_BUTTON: moveRecType(MOVE_DOWN); break; case IDC_FWVIZ_DEF_REC_UP_BUTTON: moveRecType(MOVE_UP); break; case IDC_FWVIZ_DEF_REC_DESC_EDIT: case IDC_FWVIZ_DEF_REC_THEME_LIST: switch HIWORD(wParam) { case EN_CHANGE: case CBN_SELCHANGE: if (!loadingEdits) { cleanRecVals = FALSE; enableRecSelection(); } break; } break; case IDC_FWVIZ_DEF_REC_START_EDIT: switch HIWORD(wParam) { case EN_CHANGE: if (!loadingEdits) { cleanRecVals = FALSE; enableRecSelection(); } if (GetFocus() == hRecStart) { onRecStartEditChange(); } break; } break; case IDC_FWVIZ_DEF_REC_REGEX_EDIT: switch HIWORD(wParam) { case EN_CHANGE: if (!loadingEdits) { cleanRecVals = FALSE; enableRecSelection(); } if (GetFocus() == hRecRegex) { onRecRegexEditChange(); } break; case EN_KILLFOCUS: if (GetWindowTextLength(hRecRegex) == 0) { SetWindowTextA(hRecRegex, "."); } break; } break; case IDC_FWVIZ_DEF_REC_ACCEPT_BTN: case IDC_FWVIZ_DEF_REC_RESET_BTN: recEditAccept(LOWORD(wParam) == IDC_FWVIZ_DEF_REC_ACCEPT_BTN); break; case IDC_FWVIZ_DEF_REC_NEW_BTN: recEditNew(FALSE); break; case IDC_FWVIZ_DEF_REC_CLONE_BTN: recEditNew(TRUE); break; case IDC_FWVIZ_DEF_REC_DEL_BTN: recEditDelete(); break; case IDC_FWVIZ_DEF_FIELD_LABELS_EDIT: switch HIWORD(wParam) { case EN_CHANGE: if (!loadingEdits) { cleanFieldVals = FALSE; enableRecSelection(); } break; case EN_SETFOCUS: setFieldEditCaretOnFocus(hFieldLabels); break; case EN_VSCROLL: syncFieldEditScrolling(hFieldLabels, hFieldWidths); break; } break; case IDC_FWVIZ_DEF_FIELD_WIDTHS_EDIT: switch HIWORD(wParam) { case EN_CHANGE: if (!loadingEdits) { cleanFieldVals = FALSE; enableRecSelection(); } break; case EN_SETFOCUS: setFieldEditCaretOnFocus(hFieldWidths); break; case EN_VSCROLL: syncFieldEditScrolling(hFieldWidths, hFieldLabels); break; } break; case IDC_FWVIZ_DEF_FIELD_ACCEPT_BTN: fieldEditsAccept(); break; case IDC_FWVIZ_DEF_FIELD_RESET_BTN: fillFieldTypes(); break; case IDC_FWVIZ_FIELD_TYPE_BUTTON: _fieldTypeDlg.doDialog((HINSTANCE)_gModule); break; case IDC_FWVIZ_DEF_INFO_BUTTON: ShellExecute(NULL, L"open", FWVIZ_DEF_INFO_README, NULL, NULL, SW_SHOW); break; case IDC_FWVIZ_DEF_SAVE_CONFIG_BTN: SetCursor(LoadCursor(NULL, IDC_WAIT)); saveConfigInfo(); SetCursor(LoadCursor(NULL, IDC_ARROW)); return TRUE; case IDC_FWVIZ_DEF_RESET_BTN: if (!promptDiscardChangesNo()) { configFile = L""; loadConfigInfo(); fillFileTypes(); } break; case IDC_FWVIZ_DEF_BACKUP_LOAD_BTN: if (!promptDiscardChangesNo()) { wstring backupConfigFile; if (_configIO.queryConfigFileName(_hSelf, TRUE, TRUE, backupConfigFile)) { if (_configIO.fixIfNotUTF8File(backupConfigFile)) { configFile = backupConfigFile; loadConfigInfo(); fillFileTypes(); cleanConfigFile = FALSE; enableFileSelection(); } } } break; case IDC_FWVIZ_DEF_BACKUP_VIEW_BTN: _configIO.viewBackupFolder(); break; case IDC_FWVIZ_DEF_EXTRACT_BTN: showEximDialog(TRUE); break; case IDC_FWVIZ_DEF_APPEND_BTN: showEximDialog(FALSE); break; case IDCANCEL: case IDCLOSE: if (promptDiscardChangesNo()) return TRUE; display(FALSE); return TRUE; } break; case WM_INITDIALOG: NPPDM_AutoSubclassAndThemeChildControls(_hSelf); break; case WM_CTLCOLORDLG: case WM_CTLCOLORSTATIC: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLOREDIT: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorSofter(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLORLISTBOX: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorListbox(wParam, lParam); } break; case WM_PRINTCLIENT: if (NPPDM_IsEnabled()) return TRUE; break; case FWVIZMSG_APPEND_EXIM_DATA: appendFileTypeConfigs(reinterpret_cast<LPCWSTR>(lParam)); break; } return FALSE; } void ConfigureDialog::localize() { SetWindowText(_hSelf, FWVIZ_DEF_DIALOG_TITLE); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_GROUP_BOX, FWVIZ_DEF_FILE_GROUP_BOX); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_DESC_LABEL, FWVIZ_DEF_FILE_DESC_LABEL); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_MCBS_CHECKBOX, FWVIZ_DEF_MCBS_CHECKBOX); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_EOL_LABEL, FWVIZ_DEF_FILE_EOL_LABEL); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_ADFT_GROUP_LABEL, FWVIZ_DEF_ADFT_GROUP_LABEL); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_ADFT_LINE_LABEL, FWVIZ_DEF_ADFT_LINE_LABEL); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_ADFT_REGEX_LABEL, FWVIZ_DEF_ADFT_REGEX_LABEL); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_THEME_LABEL, FWVIZ_DEF_FILE_THEME_LABEL); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_ACCEPT_BTN, FWVIZ_DEF_FILE_ACCEPT_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_RESET_BTN, FWVIZ_DEF_FILE_RESET_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_NEW_BTN, FWVIZ_DEF_FILE_NEW_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_CLONE_BTN, FWVIZ_DEF_FILE_CLONE_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_DEL_BTN, FWVIZ_DEF_FILE_DEL_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_GROUP_BOX, FWVIZ_DEF_REC_GROUP_BOX); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_DESC_LABEL, FWVIZ_DEF_REC_DESC_LABEL); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_START_LABEL, FWVIZ_DEF_REC_START_LABEL); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_REGEX_LABEL, FWVIZ_DEF_REC_REGEX_LABEL); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_THEME_LABEL, FWVIZ_DEF_REC_THEME_LABEL); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_ACCEPT_BTN, FWVIZ_DEF_REC_ACCEPT_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_RESET_BTN, FWVIZ_DEF_REC_RESET_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_NEW_BTN, FWVIZ_DEF_REC_NEW_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_CLONE_BTN, FWVIZ_DEF_REC_CLONE_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_DEL_BTN, FWVIZ_DEF_REC_DEL_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FIELD_GROUP_BOX, FWVIZ_DEF_FIELD_GROUP_BOX); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FIELD_WIDTHS_TEXT, FWVIZ_DEF_FIELD_WIDTHS_TEXT); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FIELD_LABELS_TEXT, FWVIZ_DEF_FIELD_LABELS_TEXT); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FIELD_ACCEPT_BTN, FWVIZ_DEF_FIELD_ACCEPT_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FIELD_RESET_BTN, FWVIZ_DEF_FIELD_RESET_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_FIELD_TYPE_BUTTON, FWVIZ_DEF_FIELD_TYPE_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_SAVE_CONFIG_BTN, FWVIZ_DIALOG_SAVE_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_RESET_BTN, FWVIZ_DIALOG_RESET_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_BACKUP_LOAD_BTN, FWVIZ_DIALOG_BKUP_LOAD_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_BACKUP_VIEW_BTN, FWVIZ_DIALOG_BKUP_VIEW_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_EXTRACT_BTN, FWVIZ_DIALOG_EXTRACT_BTN); SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_APPEND_BTN, FWVIZ_DIALOG_APPEND_BTN); SetDlgItemText(_hSelf, IDCLOSE, FWVIZ_DIALOG_CLOSE_BTN); } void ConfigureDialog::indicateCleanStatus() { if (cleanConfigFile) { SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_SAVE_CONFIG_BTN, FWVIZ_DIALOG_SAVE_BTN); Utils::setFontRegular(_hSelf, IDC_FWVIZ_DEF_SAVE_CONFIG_BTN); } else { SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_SAVE_CONFIG_BTN, (wstring(FWVIZ_DIALOG_SAVE_BTN) + L"*").c_str()); Utils::setFontBold(_hSelf, IDC_FWVIZ_DEF_SAVE_CONFIG_BTN); } if (cleanFileVals) { SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_ACCEPT_BTN, FWVIZ_DEF_FILE_ACCEPT_BTN); Utils::setFontRegular(_hSelf, IDC_FWVIZ_DEF_FILE_ACCEPT_BTN); } else { SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_ACCEPT_BTN, (wstring(FWVIZ_DEF_FILE_ACCEPT_BTN) + L"*").c_str()); Utils::setFontBold(_hSelf, IDC_FWVIZ_DEF_FILE_ACCEPT_BTN); } if (cleanRecVals) { SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_ACCEPT_BTN, FWVIZ_DEF_REC_ACCEPT_BTN); Utils::setFontRegular(_hSelf, IDC_FWVIZ_DEF_REC_ACCEPT_BTN); } else { SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_ACCEPT_BTN, (wstring(FWVIZ_DEF_REC_ACCEPT_BTN) + L"*").c_str()); Utils::setFontBold(_hSelf, IDC_FWVIZ_DEF_REC_ACCEPT_BTN); } if (cleanFieldVals) { SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FIELD_ACCEPT_BTN, FWVIZ_DEF_FIELD_ACCEPT_BTN); Utils::setFontRegular(_hSelf, IDC_FWVIZ_DEF_FIELD_ACCEPT_BTN); } else { SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FIELD_ACCEPT_BTN, (wstring(FWVIZ_DEF_FIELD_ACCEPT_BTN) + L"*").c_str()); Utils::setFontBold(_hSelf, IDC_FWVIZ_DEF_FIELD_ACCEPT_BTN); } } int ConfigureDialog::loadConfigInfo() { vector<string> fileTypeList; int fileTypeCount{ _configIO.getConfigValueList(fileTypeList, "Base", "FileTypes", "", Utils::WideToNarrow(configFile)) }; vFileTypes.clear(); vFileTypes.resize(fileTypeCount); for (int i{}; i < fileTypeCount; ++i) { loadFileTypeInfo(i, fileTypeList[i], configFile); } return static_cast<int>(vFileTypes.size()); } int ConfigureDialog::loadFileTypeInfo(int vIndex, const string& fileType, const wstring& wConfigFile) { string sConfigFile{ Utils::WideToNarrow(wConfigFile) }; FileType& FT{ vFileTypes[vIndex] }; FT.label = _configIO.getConfigWideChar(fileType, "FileLabel", "", sConfigFile); FT.theme = _configIO.getConfigWideChar(fileType, "FileTheme", "", sConfigFile); FT.eol = _configIO.getConfigWideChar(fileType, "RecordTerminator", "", sConfigFile); FT.multiByte = (_configIO.getConfigStringA(fileType, "MultiByteChars", "N") == "Y"); // Load ADFT data for (int i{}; i < ADFT_MAX; ++i) { char idx[5]; snprintf(idx, 5, "%02d", i + 1); FT.lineNums[i] = _configIO.getConfigInt(fileType, "ADFT_Line_" + string{ idx }, 0, sConfigFile); FT.regExprs[i] = _configIO.getConfigWideChar(fileType, "ADFT_Regex_" + string{ idx }, "", sConfigFile); } // Load Record Type data vector<string> recTypesList; int recTypeCount{ _configIO.getConfigValueList(recTypesList, fileType, "RecordTypes", "", sConfigFile) }; FT.vRecTypes.clear(); FT.vRecTypes.resize(recTypeCount); for (int j{}; j < recTypeCount; ++j) { string& recType{ recTypesList[j] }; RecordType& RT{ FT.vRecTypes[j] }; RT.label = _configIO.getConfigWideChar(fileType, (recType + "_Label"), "", sConfigFile); RT.marker = _configIO.getConfigWideChar(fileType, (recType + "_Marker"), "", sConfigFile); RT.theme = _configIO.getConfigWideChar(fileType, (recType + "_Theme"), "", sConfigFile); RT.fieldWidths = _configIO.getConfigWideChar(fileType, (recType + "_FieldWidths"), "", sConfigFile); RT.fieldLabels = _configIO.getConfigWideChar(fileType, (recType + "_FieldLabels"), "", sConfigFile); } return recTypeCount; } void ConfigureDialog::fillFileTypes() { // Fill File Types Listbox SendMessage(hFilesLB, LB_RESETCONTENT, NULL, NULL); for (const FileType FT : vFileTypes) { SendMessage(hFilesLB, LB_ADDSTRING, NULL, (LPARAM)FT.label.c_str()); } if (vFileTypes.size()) SendMessage(hFilesLB, LB_SETCURSEL, 0, NULL); // Fill Files & Records Themes Droplists SendMessage(hFileThemes, CB_RESETCONTENT, NULL, NULL); SendMessage(hRecThemes, CB_RESETCONTENT, NULL, NULL); SendMessage(hRecThemes, CB_ADDSTRING, NULL, (LPARAM)FWVIZ_DEF_REC_THEME_FROM_FT); vector<wstring> themesList; _configIO.getThemesList(themesList); for (const wstring theme : themesList) { SendMessage(hFileThemes, CB_ADDSTRING, NULL, (LPARAM)theme.c_str()); SendMessage(hRecThemes, CB_ADDSTRING, NULL, (LPARAM)theme.c_str()); } cleanConfigFile = TRUE; cleanFileVals = TRUE; onFileTypeSelect(); } int ConfigureDialog::getCurrentFileTypeIndex() const { int idxFT; idxFT = static_cast<int>(SendMessage(hFilesLB, LB_GETCURSEL, NULL, NULL)); if (idxFT == LB_ERR) return LB_ERR; return idxFT; } int ConfigureDialog::getCurrentRecIndex() const { int idxRec; idxRec = static_cast<int>(SendMessage(hRecsLB, LB_GETCURSEL, NULL, NULL)); if (idxRec == LB_ERR) return LB_ERR; return idxRec; } bool ConfigureDialog::getCurrentFileTypeInfo(FileType*& fileInfo) { int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return FALSE; fileInfo = &vFileTypes[idxFT]; return TRUE; } ConfigureDialog::FileType ConfigureDialog::getNewFileType() { FileType newFile; newFile.theme = L"Spectrum"; newFile.multiByte = FALSE; newFile.vRecTypes = vector<RecordType>{ getNewRec() }; return newFile; } int ConfigureDialog::getFileTypeConfig(size_t idxFT, bool cr_lf, wstring& ftCode, wstring& ftConfig) { size_t recTypeCount; wchar_t fileTypeCode[60], recTypeCode[10]; wstring new_line, rawCode, adft{}, recTypes{}, rtConfig{}, recTypePrefix; FileType& FT{ vFileTypes[idxFT] }; new_line = cr_lf ? L"\r\n" : L"\n"; string utf8Code{ Utils::WideToNarrow(FT.label) }; utf8Code = regex_replace(utf8Code, std::regex("[^\x20-\x7F]"), ""); rawCode = Utils::NarrowToWide(regex_replace(utf8Code, std::regex("(,|=|\\[|\\])"), " ")); rawCode = regex_replace(rawCode, wregex(L"(^( )+)|(( )+$)"), L""); rawCode = regex_replace(rawCode, wregex(L"( ){2,}"), L" "); rawCode = regex_replace(rawCode, wregex(L" "), L"_").substr(0, 50); swprintf(fileTypeCode, 60, L"FT%03d_%s", static_cast<int>(idxFT + 1), rawCode.c_str()); Utils::ToUpper(fileTypeCode); // ADFT Info for (int i{}; i < ADFT_MAX; ++i) { if (Utils::isInvalidRegex(FT.regExprs[i], _hSelf, wstring(FWVIZ_DEF_FILE_DESC_LABEL) + L" " + FT.label + new_line + FWVIZ_DEF_ADFT_GROUP_LABEL + L" - " + FWVIZ_DEF_ADFT_LINE_LABEL + L" " + to_wstring(i + 1))) return -2; wchar_t idx[5]; swprintf(idx, 5, L"%02d", i + 1); wstring lineNum{ (FT.lineNums[i] == 0) ? L"" : to_wstring(FT.lineNums[i]) }; adft += L"ADFT_Line_" + wstring{ idx } + L"=" + lineNum + new_line + L"ADFT_Regex_" + wstring{ idx } + L"=" + FT.regExprs[i] + new_line; } // Rec Info recTypeCount = (FT.vRecTypes.size() > 999) ? 999 : FT.vRecTypes.size(); for (size_t j{}; j < recTypeCount; ++j) { RecordType& RT{ FT.vRecTypes[j] }; if (Utils::isInvalidRegex(RT.marker, _hSelf, wstring(FWVIZ_DEF_FILE_DESC_LABEL) + L" " + FT.label + new_line + FWVIZ_DEF_REC_DESC_LABEL + L" " + RT.label + new_line + FWVIZ_DEF_REC_REGEX_LABEL)) return -2; swprintf(recTypeCode, 10, L"REC%03d", static_cast<int>(j + 1)); recTypePrefix = wstring{ recTypeCode }; recTypes += (j == 0 ? L"RecordTypes=" : L",") + recTypePrefix; rtConfig += recTypePrefix + L"_Label=" + RT.label + new_line + recTypePrefix + L"_Marker=" + RT.marker + new_line + recTypePrefix + L"_FieldLabels=" + RT.fieldLabels + new_line + recTypePrefix + L"_FieldWidths=" + RT.fieldWidths + new_line; if ((RT.theme != L"") && (RT.theme != FWVIZ_DEF_REC_THEME_FROM_FT) && (RT.theme != FT.theme)) rtConfig += recTypePrefix + L"_Theme=" + RT.theme + new_line; } // Output ftCode = wstring{ fileTypeCode }; ftConfig = L"[" + ftCode + L"]" + new_line + L"FileLabel=" + FT.label + new_line + L"FileTheme=" + FT.theme + new_line + L"RecordTerminator=" + FT.eol + new_line + L"MultiByteChars=" + (FT.multiByte ? L"Y" : L"N") + new_line + adft + recTypes + new_line + rtConfig; return 1; } bool ConfigureDialog::getCurrentRecInfo(RecordType*& recInfo) { int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return FALSE; int idxRec{ getCurrentRecIndex() }; if (idxRec == LB_ERR) return FALSE; recInfo = &vFileTypes[idxFT].vRecTypes[idxRec]; return TRUE; } ConfigureDialog::RecordType ConfigureDialog::getNewRec() { RecordType newRec; newRec.label = L""; newRec.marker = L""; newRec.fieldLabels = L""; newRec.fieldWidths = L""; newRec.theme = L""; return newRec; } void ConfigureDialog::onFileTypeSelect() { FileType* fileInfo; if (!getCurrentFileTypeInfo(fileInfo)) { FileType newFile{ getNewFileType() }; fileInfo = &newFile; } onFileTypeSelectFill(fileInfo); enableMoveFileButtons(); fillRecTypes(); } void ConfigureDialog::onFileTypeSelectFill(FileType* fileInfo) { loadingEdits = TRUE; SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_DESC_EDIT, fileInfo->label.c_str()); SetWindowText(hFileEOL, fileInfo->eol.c_str()); CheckDlgButton(_hSelf, IDC_FWVIZ_DEF_MCBS_CHECKBOX, fileInfo->multiByte ? BST_CHECKED : BST_UNCHECKED); for (int i{}; i < ADFT_MAX; ++i) { wstring lineNum{ (fileInfo->lineNums[i] == 0) ? L"" : to_wstring(fileInfo->lineNums[i]) }; SetWindowText(hADFTLine[i], lineNum.c_str()); SetWindowText(hADFTRegex[i], fileInfo->regExprs[i].c_str()); } Utils::setComboBoxSelection(hFileThemes, static_cast<int>( SendMessage(hFileThemes, CB_FINDSTRING, (WPARAM)-1, (LPARAM)fileInfo->theme.c_str()))); loadingEdits = FALSE; } void ConfigureDialog::enableMoveFileButtons() { int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return; EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FILE_DOWN_BUTTON), (idxFT < static_cast<int>(vFileTypes.size()) - 1)); EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FILE_UP_BUTTON), (idxFT > 0)); } void ConfigureDialog::enableFileSelection() { bool enable{ cleanFileVals && cleanRecVals && cleanFieldVals }; bool fileTypesExist{ SendMessage(hFilesLB, LB_GETCOUNT, 0, 0) > 0 }; ShowWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FILE_NEW_BTN), cleanFileVals ? SW_SHOW : SW_HIDE); ShowWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FILE_RESET_BTN), cleanFileVals ? SW_HIDE : SW_SHOW); EnableWindow(hFilesLB, enable); EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FILE_NEW_BTN), enable); EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FILE_CLONE_BTN), enable); EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FILE_DEL_BTN), fileTypesExist); EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_EXTRACT_BTN), enable); EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_APPEND_BTN), enable); if (enable) { enableMoveFileButtons(); } else { EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FILE_DOWN_BUTTON), FALSE); EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_FILE_UP_BUTTON), FALSE); } indicateCleanStatus(); } int ConfigureDialog::moveFileType(move_dir dir) { const int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return LB_ERR; switch (dir) { case MOVE_DOWN: if (idxFT >= static_cast<int>(vFileTypes.size()) - 1) return LB_ERR; break; case MOVE_UP: if (idxFT == 0) return LB_ERR; break; default: return LB_ERR; } FileType currType{ vFileTypes[idxFT] }; FileType& adjType{ vFileTypes[idxFT + dir] }; vFileTypes[idxFT] = adjType; vFileTypes[idxFT + dir] = currType; SendMessage(hFilesLB, LB_DELETESTRING, idxFT, NULL); SendMessage(hFilesLB, LB_INSERTSTRING, (idxFT + dir), (LPARAM)vFileTypes[idxFT + dir].label.c_str()); SendMessage(hFilesLB, LB_SETCURSEL, idxFT + dir, NULL); cleanConfigFile = FALSE; indicateCleanStatus(); enableMoveFileButtons(); return idxFT + dir; } void ConfigureDialog::fillRecTypes() { FileType* fileInfo; if (!getCurrentFileTypeInfo(fileInfo)) { FileType newFile{ getNewFileType() }; fileInfo = &newFile; } vector <RecordType>& recInfoList{ fileInfo->vRecTypes }; // Fill Rec Types Listbox SendMessage(hRecsLB, LB_RESETCONTENT, NULL, NULL); for (const RecordType RT : recInfoList) { SendMessage(hRecsLB, LB_ADDSTRING, NULL, (LPARAM)RT.label.c_str()); } if (recInfoList.size()) SendMessage(hRecsLB, LB_SETCURSEL, 0, NULL); cleanRecVals = TRUE; onRecTypeSelect(); } void ConfigureDialog::onRecTypeSelect() { RecordType* recInfo; if (!getCurrentRecInfo(recInfo)) { RecordType newRec{ getNewRec() }; recInfo = &newRec; } onRecTypeSelectFill(recInfo); enableMoveRecButtons(); fillFieldTypes(); } void ConfigureDialog::onRecTypeSelectFill(RecordType* recInfo) { loadingEdits = TRUE; SetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_DESC_EDIT, recInfo->label.c_str()); wstring regExpr = recInfo->marker; SetWindowText(hRecRegex, regExpr.c_str()); SetWindowText(hRecStart, getOnlyStartsWith(regExpr).c_str()); loadingEdits = FALSE; if (recInfo->theme == L"") recInfo->theme = FWVIZ_DEF_REC_THEME_FROM_FT; Utils::setComboBoxSelection(hRecThemes, static_cast<int>( SendMessage(hRecThemes, CB_FINDSTRING, (WPARAM)-1, (LPARAM)recInfo->theme.c_str()))); } void ConfigureDialog::enableMoveRecButtons() { int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return; int idxRec{ getCurrentRecIndex() }; if (idxRec == LB_ERR) return; EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_DOWN_BUTTON), (idxRec < static_cast<int>(vFileTypes[idxFT].vRecTypes.size()) - 1)); EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_UP_BUTTON), (idxRec > 0)); } void ConfigureDialog::enableRecSelection() { bool enable{ cleanRecVals && cleanFieldVals }; bool recTypesExist{ SendMessage(hRecsLB, LB_GETCOUNT, 0, 0) > 0 }; ShowWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_NEW_BTN), cleanRecVals ? SW_SHOW : SW_HIDE); ShowWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_RESET_BTN), cleanRecVals ? SW_HIDE : SW_SHOW); EnableWindow(hRecsLB, enable); EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_NEW_BTN), enable); EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_CLONE_BTN), enable); EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_DEL_BTN), recTypesExist); if (enable) { enableMoveRecButtons(); } else { EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_DOWN_BUTTON), FALSE); EnableWindow(GetDlgItem(_hSelf, IDC_FWVIZ_DEF_REC_UP_BUTTON), FALSE); } enableFileSelection(); } int ConfigureDialog::moveRecType(move_dir dir) { const int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return LB_ERR; const int idxRec{ getCurrentRecIndex() }; if (idxRec == LB_ERR) return LB_ERR; vector<RecordType>& recList{ vFileTypes[idxFT].vRecTypes }; switch (dir) { case MOVE_DOWN: if (idxRec >= static_cast<int>(recList.size()) - 1) return LB_ERR; break; case MOVE_UP: if (idxRec == 0) return LB_ERR; break; default: return LB_ERR; } RecordType currType{ recList[idxRec] }; RecordType& adjType{ recList[idxRec + dir] }; recList[idxRec] = adjType; recList[idxRec + dir] = currType; SendMessage(hRecsLB, LB_DELETESTRING, idxRec, NULL); SendMessage(hRecsLB, LB_INSERTSTRING, (idxRec + dir), (LPARAM)recList[idxRec + dir].label.c_str()); SendMessage(hRecsLB, LB_SETCURSEL, idxRec + dir, NULL); cleanConfigFile = FALSE; indicateCleanStatus(); enableMoveRecButtons(); return idxRec + dir; } void ConfigureDialog::fillFieldTypes() { RecordType* recInfo; if (!getCurrentRecInfo(recInfo)) { RecordType newRec{ getNewRec() }; recInfo = &newRec; } // Field Labels wstring fieldLabels{ regex_replace(recInfo->fieldLabels, wregex(L","), L"\r\n") }; SetWindowText(hFieldLabels, fieldLabels.c_str()); // Field Widths wstring fieldWidths{ regex_replace(recInfo->fieldWidths, wregex(L","), L"\r\n") }; SetWindowText(hFieldWidths, fieldWidths.c_str()); cleanFieldVals = TRUE; enableRecSelection(); } void ConfigureDialog::setFieldEditCaretOnFocus(HWND hEdit) { DWORD startPos{}, endPos{}; SendMessage(hEdit, EM_GETSEL, (WPARAM)&startPos, (LPARAM)&endPos); if (GetWindowTextLength(hEdit) == static_cast<int>(endPos) - static_cast<int>(startPos)) { int caretPos = (hEdit == hFieldLabels) ? editLabelsCaret : editWidthsCaret; SendMessage(hEdit, EM_SETSEL, caretPos, caretPos); SendMessage(hEdit, EM_SCROLLCARET, NULL, NULL); } hiliteFieldEditPairedItem(hEdit, (hEdit == hFieldLabels) ? hFieldWidths : hFieldLabels); } void ConfigureDialog::hiliteFieldEditPairedItem(HWND hThis, HWND hThat) { int thisLine = static_cast<int>(SendMessage(hThis, EM_LINEFROMCHAR, SendMessage(hThis, EM_LINEINDEX, (WPARAM)-1, NULL), NULL)); int thatLineCount = static_cast<int>(SendMessage(hThat, EM_GETLINECOUNT, NULL, NULL)); if (thisLine >= thatLineCount) return; int lineStart = static_cast<int>(SendMessage(hThat, EM_LINEINDEX, thisLine, NULL)); int lineLength = static_cast<int>(SendMessage(hThat, EM_LINELENGTH, lineStart, NULL)); ((hThis == hFieldLabels) ? editWidthsCaret : editLabelsCaret) = lineStart; SendMessage(hThat, EM_SETSEL, lineStart, (lineStart + lineLength)); SendMessage(hThat, EM_SCROLLCARET, NULL, NULL); } void ConfigureDialog::syncFieldEditScrolling(HWND hThis, HWND hThat) { int thisLine = static_cast<int>(SendMessage(hThis, EM_GETFIRSTVISIBLELINE, NULL, NULL)); int thatLineCount = static_cast<int>(SendMessage(hThat, EM_GETLINECOUNT, NULL, NULL)); if (thisLine >= thatLineCount) return; int thatLine = static_cast<int>(SendMessage(hThat, EM_GETFIRSTVISIBLELINE, NULL, NULL)); SendMessage(hThat, EM_LINESCROLL, NULL, thisLine - thatLine); } void ConfigureDialog::fieldEditsAccept() { if (cleanFieldVals) return; RecordType* recInfo; if (!getCurrentRecInfo(recInfo)) return; wstring fieldValues(FW_LINE_MAX_LENGTH + 1, '\0'); wstring vals{}; // Field Labels GetWindowText(hFieldLabels, fieldValues.data(), (FW_LINE_MAX_LENGTH + 1)); // Replace any trailing spaces + newlines with commas vals = regex_replace(wstring(fieldValues.c_str()), wregex(L" *\r\n"), L","); // Replace any commas + leading spaces with commas vals = regex_replace(vals, wregex(L", +([^,]*)"), L",$1"); // Trim any leading & trailing spaces for the entire string vals = regex_replace(vals, wregex(L"^ +(.*[^ ]) +$"), L"$1"); recInfo->fieldLabels = vals; SetWindowText(hFieldLabels, regex_replace(vals, wregex(L","), L"\r\n").c_str()); // Field Widths GetWindowText(hFieldWidths, fieldValues.data(), (FW_LINE_MAX_LENGTH + 1)); // Replace any newlines with commas. // No processing needed for leading & trailing spaces since this is a numeric edit control vals = regex_replace(wstring(fieldValues.c_str()), wregex(L"\r\n"), L","); recInfo->fieldWidths = vals.c_str(); cleanConfigFile = FALSE; cleanFieldVals = TRUE; enableRecSelection(); } void ConfigureDialog::onRecStartEditChange() const { wstring startText(MAX_PATH + 1, '\0'); GetWindowText(hRecStart, startText.data(), MAX_PATH); startText = startText.c_str(); wstring startReg{ L"." }; if (!startText.empty()) startReg = L"^" + regex_replace(startText, std::wregex(L"[" + REGEX_META_CHARS + L"]"), L"\\$&"); SetWindowText(hRecRegex, startReg.c_str()); } void ConfigureDialog::onRecRegexEditChange() { wstring regexText(MAX_PATH + 1, '\0'); GetWindowText(hRecRegex, regexText.data(), MAX_PATH); SetWindowText(hRecStart, getOnlyStartsWith(regexText.c_str()).c_str()); } int ConfigureDialog::recEditAccept(bool accept) { if (cleanRecVals) return 0; int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return -1; int idxRec{ getCurrentRecIndex() }; if (idxRec == LB_ERR) return -1; RecordType& recInfo{ vFileTypes[idxFT].vRecTypes[idxRec] }; if (accept) { wchar_t recDesc[MAX_PATH + 1]; GetDlgItemText(_hSelf, IDC_FWVIZ_DEF_REC_DESC_EDIT, recDesc, MAX_PATH); recInfo.label = recDesc; wchar_t regexVal[MAX_PATH + 1]; GetWindowText(hRecRegex, regexVal, MAX_PATH); if (Utils::isInvalidRegex(regexVal, _hSelf, FWVIZ_DEF_REC_REGEX_LABEL)) return -2; else recInfo.marker = regexVal; wchar_t themeVal[MAX_PATH + 1]; GetWindowText(hRecThemes, themeVal, MAX_PATH); recInfo.theme = (wstring{ themeVal } == FWVIZ_DEF_REC_THEME_FROM_FT) ? L"" : themeVal; } else if (recInfo.label.empty()) { recEditDelete(); return 0; } else { onRecTypeSelectFill(&recInfo); } SendMessage(hRecsLB, LB_DELETESTRING, idxRec, NULL); SendMessage(hRecsLB, LB_INSERTSTRING, idxRec, (LPARAM)recInfo.label.c_str()); SendMessage(hRecsLB, LB_SETCURSEL, idxRec, NULL); cleanConfigFile = FALSE; cleanRecVals = TRUE; enableRecSelection(); return 1; } void ConfigureDialog::recEditNew(bool clone) { int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return; int idxRT{ getCurrentRecIndex() }; if (clone && idxRT == LB_ERR) return; vector<RecordType>& records{ vFileTypes[idxFT].vRecTypes }; if (static_cast<int>(records.size()) >= REC_TYPE_LIMIT) { TCHAR buf[100]; swprintf(buf, 100, FWVIZ_RT_LIMIT_ERROR, REC_TYPE_LIMIT); MessageBox(_hSelf, buf, clone ? FWVIZ_RT_CLONE_ACTION : FWVIZ_RT_NEW_ACTION, MB_OK | MB_ICONSTOP); return; } RecordType newRec{ getNewRec() }; if (clone) { newRec.label = records[idxRT].label; newRec.marker = records[idxRT].marker; newRec.fieldLabels = records[idxRT].fieldLabels; newRec.fieldWidths = records[idxRT].fieldWidths; } records.push_back(newRec); size_t moveTo = records.size() - 1; SendMessage(hRecsLB, LB_ADDSTRING, NULL, (LPARAM)newRec.label.c_str()); SendMessage(hRecsLB, LB_SETCURSEL, moveTo, NULL); onRecTypeSelect(); cleanConfigFile = FALSE; cleanRecVals = clone; enableRecSelection(); } int ConfigureDialog::recEditDelete() { int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return LB_ERR; int idxRec{ getCurrentRecIndex() }; if (idxRec == LB_ERR) return LB_ERR; vector<RecordType>& records{ vFileTypes[idxFT].vRecTypes }; records.erase(records.begin() + idxRec); int lastRec = static_cast<int>(records.size()) - 1; int moveTo = (idxRec <= lastRec - 1) ? idxRec : lastRec; SendMessage(hRecsLB, LB_DELETESTRING, idxRec, NULL); SendMessage(hRecsLB, LB_SETCURSEL, moveTo, NULL); cleanConfigFile = FALSE; cleanRecVals = TRUE; onRecTypeSelect(); return moveTo; } int ConfigureDialog::fileEditAccept(bool accept) { if (cleanFileVals) return 0; int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return -1; FileType& fileInfo{ vFileTypes[idxFT] }; if (accept) { wchar_t fileVal[MAX_PATH + 1]; GetDlgItemText(_hSelf, IDC_FWVIZ_DEF_FILE_DESC_EDIT, fileVal, MAX_PATH); fileInfo.label = fileVal; GetWindowText(hFileThemes, fileVal, MAX_PATH); fileInfo.theme = fileVal; wchar_t eolVal[MAX_PATH + 1]; GetWindowText(hFileEOL, eolVal, MAX_PATH); fileInfo.eol = eolVal; fileInfo.multiByte = (IsDlgButtonChecked(_hSelf, IDC_FWVIZ_DEF_MCBS_CHECKBOX) == BST_CHECKED); // ADFT Info wchar_t lineNum[MAX_PATH + 1]; wchar_t regExpr[MAX_PATH + 1]; for (int i{}; i < ADFT_MAX; ++i) { GetWindowText(hADFTLine[i], lineNum, MAX_PATH); fileInfo.lineNums[i] = Utils::StringtoInt(lineNum); GetWindowText(hADFTRegex[i], regExpr, MAX_PATH); if (Utils::isInvalidRegex(regExpr, _hSelf, wstring(FWVIZ_DEF_ADFT_GROUP_LABEL) + L" - " + FWVIZ_DEF_ADFT_LINE_LABEL + L" " + to_wstring(i + 1))) return -2; else fileInfo.regExprs[i] = regExpr; } } else if (fileInfo.label.empty()) { fileEditDelete(); return 0; } else { onFileTypeSelectFill(&fileInfo); } // Update FT Listbox Entry SendMessage(hFilesLB, LB_DELETESTRING, idxFT, NULL); SendMessage(hFilesLB, LB_INSERTSTRING, idxFT, (LPARAM)fileInfo.label.c_str()); SendMessage(hFilesLB, LB_SETCURSEL, idxFT, NULL); cleanConfigFile = FALSE; cleanFileVals = TRUE; enableFileSelection(); return 1; } int ConfigureDialog::appendFileTypeConfigs(const wstring& sConfigFile) { vector<string> sectionList{}; wstring sectionLabel{}; int sectionCount{ _configIO.getConfigAllSectionsList(sectionList, Utils::WideToNarrow(sConfigFile)) }; int validCount{}; for (int i{}; i < sectionCount; ++i) { sectionLabel = _configIO.getConfigWideChar(sectionList[i], "FileLabel", "", Utils::WideToNarrow(sConfigFile)); if (sectionLabel.empty()) continue; if (!checkFTLimit(FALSE)) break; FileType newFile{ getNewFileType() }; vFileTypes.push_back(newFile); loadFileTypeInfo(static_cast<int>(vFileTypes.size() - 1), sectionList[i], sConfigFile); SendMessage(hFilesLB, LB_ADDSTRING, NULL, (LPARAM)sectionLabel.c_str()); ++validCount; } SendMessage(hFilesLB, LB_SETCURSEL, (vFileTypes.size() - 1), NULL); onFileTypeSelect(); cleanConfigFile = FALSE; enableFileSelection(); return validCount; } void ConfigureDialog::fileEditNew() { if (!checkFTLimit(FALSE)) return; FileType newFile{ getNewFileType() }; vFileTypes.push_back(newFile); size_t moveTo = vFileTypes.size() - 1; SendMessage(hFilesLB, LB_ADDSTRING, NULL, (LPARAM)newFile.label.c_str()); SendMessage(hFilesLB, LB_SETCURSEL, moveTo, NULL); onFileTypeSelect(); cleanConfigFile = FALSE; cleanFileVals = FALSE; enableFileSelection(); } void ConfigureDialog::fileEditClone() { if (!checkFTLimit(TRUE)) return; int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return; FileType& FT{ vFileTypes[idxFT] }; FileType NF{}; NF.label = FT.label + L"_clone"; NF.theme = FT.theme; NF.eol = FT.eol; NF.multiByte = FT.multiByte; // ADFT Info for (int i{}; i < ADFT_MAX; ++i) { NF.lineNums[i] = FT.lineNums[i]; NF.regExprs[i] = FT.regExprs[i]; } // Rec Info size_t recCount = FT.vRecTypes.size(); NF.vRecTypes.resize(recCount); for (size_t i{}; i < recCount; ++i) { NF.vRecTypes[i].label = FT.vRecTypes[i].label; NF.vRecTypes[i].marker = FT.vRecTypes[i].marker; NF.vRecTypes[i].fieldLabels = FT.vRecTypes[i].fieldLabels; NF.vRecTypes[i].fieldWidths = FT.vRecTypes[i].fieldWidths; } vFileTypes.push_back(NF); SendMessage(hFilesLB, LB_ADDSTRING, NULL, (LPARAM)NF.label.c_str()); SendMessage(hFilesLB, LB_SETCURSEL, (vFileTypes.size() - 1), NULL); onFileTypeSelect(); cleanConfigFile = FALSE; enableFileSelection(); } int ConfigureDialog::fileEditDelete() { int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return LB_ERR; vFileTypes.erase(vFileTypes.begin() + idxFT); int lastFile = static_cast<int>(vFileTypes.size()) - 1; int moveTo = (idxFT <= lastFile - 1) ? idxFT : lastFile; SendMessage(hFilesLB, LB_DELETESTRING, idxFT, NULL); SendMessage(hFilesLB, LB_SETCURSEL, moveTo, NULL); cleanConfigFile = FALSE; cleanFileVals = TRUE; onFileTypeSelect(); return moveTo; } bool ConfigureDialog::checkFTLimit(bool clone) { if (vFileTypes.size() < FILE_TYPE_LIMIT) return TRUE; TCHAR buf[100]; swprintf(buf, 100, FWVIZ_FT_LIMIT_ERROR, FILE_TYPE_LIMIT); MessageBox(_hSelf, buf, clone ? FWVIZ_FT_CLONE_ACTION : FWVIZ_FT_NEW_ACTION, MB_OK | MB_ICONSTOP); return FALSE; } bool ConfigureDialog::promptDiscardChangesNo() { if (!(cleanConfigFile && cleanFileVals && cleanRecVals && cleanFieldVals)) { if (MessageBox(_hSelf, FWVIZ_DISCARD_CHANGES, FWVIZ_DEF_DIALOG_TITLE, MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) == IDNO) return TRUE; } return false; } void ConfigureDialog::saveConfigInfo() { if (_configIO.isCurrentVizConfigDefault() && MessageBox(_hSelf, FWVIZ_DEFAULT_OVERWRITE, FWVIZ_DEF_DIALOG_TITLE, MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) == IDNO) return; if (!cleanFieldVals) fieldEditsAccept(); if (!cleanRecVals) if (recEditAccept() < 0) return; if (!cleanFileVals) if (fileEditAccept() < 0) return; size_t fileTypeCount; wstring fileData{}, fileTypes{}, ftCode{}, ftConfig{}; fileTypeCount = (vFileTypes.size() > 999) ? 999 : vFileTypes.size(); for (size_t i{}; i < fileTypeCount; ++i) { if (getFileTypeConfig(i, TRUE, ftCode, ftConfig) < 0) return; fileTypes += (i == 0 ? L"" : L",") + ftCode; fileData += ftConfig + L"\r\n"; } fileData = L"[Base]\r\nFileTypes=" + fileTypes + L"\r\n\r\n" + fileData; _configIO.backupConfigFile(_configIO.getConfigFile(_configIO.CONFIG_VIZ)); _configIO.saveConfigFile(fileData, _configIO.getConfigFile(_configIO.CONFIG_VIZ)); cleanConfigFile = TRUE; indicateCleanStatus(); RefreshVisualizerPanel(); } void ConfigureDialog::showEximDialog(bool bExtract) { _eximDlg.doDialog((HINSTANCE)_gModule); _eximDlg.initDialog(_hSelf, EximFileTypeDialog::FWTYPES_DLG, bExtract); if (bExtract) { int idxFT{ getCurrentFileTypeIndex() }; if (idxFT == LB_ERR) return; wstring ftCode{}, ftConfig{}; if (getFileTypeConfig(idxFT, TRUE, ftCode, ftConfig) < 0) { _eximDlg.display(false); return; } _eximDlg.setFileTypeData(ftConfig); } } wstring ConfigureDialog::getOnlyStartsWith(wstring expr) { return wstring{ (!expr.empty() && regex_match(expr, std::wregex(L"^\\^[^" + REGEX_META_CHARS + L"]+"))) ? expr.substr(1) : L"" }; } LRESULT CALLBACK procNumberEditControl(HWND hwnd, UINT messageId, WPARAM wParam, LPARAM lParam, UINT_PTR, DWORD_PTR) { switch (messageId) { case WM_CHAR: { wchar_t editChar{ static_cast<WCHAR>(wParam) }; bool valid{ editChar < ' ' || (editChar >= '0' && editChar <= '9') }; int editSel{ static_cast<int>(SendMessage(hwnd, EM_GETSEL, NULL, NULL)) }; if (LOWORD(editSel) == 0) { wchar_t editText[MAX_PATH + 1]; GetWindowText(hwnd, editText, MAX_PATH); if (HIWORD(editSel) == 0 && editText[0] == '-') valid = editChar < ' '; else valid |= editChar == '-'; } if (!valid) { showEditBalloonTip(hwnd, FWVIZ_DIALOG_NUMERIC_TITLE, FWVIZ_DIALOG_NUMERIC_MSG); return FALSE; } break; } case WM_PASTE: { wstring clipText; Utils::getClipboardText(GetParent(hwnd), clipText); int editSel{ static_cast<int>(SendMessage(hwnd, EM_GETSEL, NULL, NULL)) }; wchar_t editText[MAX_PATH + 1]; GetWindowText(hwnd, editText, MAX_PATH); wstring clipValid{ (editText[0] == '-' && (LOWORD(editSel) > 0 || HIWORD(editSel) == 0)) ? L"" : L"-?" }; clipValid += L"[0-9]*"; if (!regex_match(clipText, wregex(clipValid))) { showEditBalloonTip(hwnd, FWVIZ_DIALOG_NUMERIC_TITLE, FWVIZ_DIALOG_NUMERIC_MSG); return FALSE; } break; } } return DefSubclassProc(hwnd, messageId, wParam, lParam); } LRESULT CALLBACK procFieldEditMessages(HWND hwnd, UINT messageId, WPARAM wParam, LPARAM lParam, UINT_PTR, DWORD_PTR) { HWND hThis{ hwnd == _configDlg.hFieldLabels ? _configDlg.hFieldLabels : _configDlg.hFieldWidths }; HWND hThat{ hwnd == _configDlg.hFieldLabels ? _configDlg.hFieldWidths : _configDlg.hFieldLabels }; switch (messageId) { case WM_CHAR: if (wParam == ',' && hwnd == _configDlg.hFieldLabels) { showEditBalloonTip(hwnd, FWVIZ_DIALOG_COMMAS_TITLE, FWVIZ_DIALOG_COMMAS_MESSAGE); } break; case WM_KEYDOWN: case WM_KEYUP: case WM_LBUTTONUP: _configDlg.hiliteFieldEditPairedItem(hThis, hThat); break; case WM_VSCROLL: _configDlg.syncFieldEditScrolling(hThis, hThat); break; } return DefSubclassProc(hwnd, messageId, wParam, lParam); }
48,105
C++
.cpp
1,138
36.226714
132
0.673445
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,109
DataExtractDialog.cpp
shriprem_FWDataViz/src/Dialogs/DataExtractDialog.cpp
#include "DataExtractDialog.h" extern VisualizerPanel _vizPanel; extern DataExtractDialog _dataExtractDlg; LRESULT CALLBACK procKeyNavigation(HWND hwnd, UINT messageId, WPARAM wParam, LPARAM lParam, UINT_PTR, DWORD_PTR) { switch (messageId) { case WM_KEYDOWN: if (_dataExtractDlg.processKey(hwnd, wParam)) return FALSE; break; case WM_SYSKEYDOWN: if (_dataExtractDlg.processSysKey(hwnd, wParam)) return FALSE; break; } return DefSubclassProc(hwnd, messageId, wParam, lParam); } LRESULT CALLBACK procTemplateName(HWND hwnd, UINT messageId, WPARAM wParam, LPARAM lParam, UINT_PTR, DWORD_PTR) { switch (messageId) { case WM_CHAR: if (wParam == '[' || wParam == ']') { Utils::showEditBalloonTip(hwnd, DATA_EXTRACT_INVTEMPL_TITLE, DATA_EXTRACT_INVTEMPL_MSG); return FALSE; } break; case WM_PASTE: { wstring clipText; Utils::getClipboardText(GetParent(hwnd), clipText); if (!regex_match(clipText, std::wregex(L"[|]"))) { Utils::showEditBalloonTip(hwnd, DATA_EXTRACT_INVTEMPL_TITLE, DATA_EXTRACT_INVTEMPL_MSG); return FALSE; } break; } } return DefSubclassProc(hwnd, messageId, wParam, lParam); } void DataExtractDialog::doDialog(HINSTANCE hInst) { if (!isCreated()) { Window::init(hInst, nppData._nppHandle); create(IDD_DATA_EXTRACT_DIALOG); } using Utils::addTooltip; using Utils::loadBitmap; hIndicator = GetDlgItem(_hSelf, IDC_DAT_EXT_CURRENT_LINE); hTemplatesList = GetDlgItem(_hSelf, IDC_DAT_EXT_TEMPLATE_LIST); hTemplateName = GetDlgItem(_hSelf, IDC_DAT_EXT_TEMPLATE_NAME); SendMessage(hTemplateName, EM_LIMITTEXT, MAX_TEMPLATE_NAME, NULL); SetWindowSubclass(hTemplateName, procTemplateName, NULL, NULL); for (int i{}; i < LINES_PER_PAGE; ++i) { SetWindowSubclass(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_PREFIX_01 + i), procKeyNavigation, NULL, NULL); SendDlgItemMessage(_hSelf, IDC_DAT_EXT_ITEM_PREFIX_01 + i, EM_LIMITTEXT, MAX_PATH, NULL); SetWindowSubclass(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_SUFFIX_01 + i), procKeyNavigation, NULL, NULL); SendDlgItemMessage(_hSelf, IDC_DAT_EXT_ITEM_SUFFIX_01 + i, EM_LIMITTEXT, MAX_PATH, NULL); loadBitmap(_hSelf, IDC_DAT_EXT_ITEM_ADD_BTN_01 + i, IDB_DAT_EXT_PLUS_BITMAP); addTooltip(_hSelf, IDC_DAT_EXT_ITEM_ADD_BTN_01 + i, L"", DATA_EXTRACT_ADD_LINE_ITEM, FALSE); loadBitmap(_hSelf, IDC_DAT_EXT_ITEM_DEL_BTN_01 + i, IDB_DAT_EXT_MINUS_BITMAP); addTooltip(_hSelf, IDC_DAT_EXT_ITEM_DEL_BTN_01 + i, L"", DATA_EXTRACT_DEL_LINE_ITEM, FALSE); } loadBitmap(_hSelf, IDC_DAT_EXT_PAGE_PREV_BUTTON, IDB_DAT_EXT_PAGE_PREV_BITMAP); addTooltip(_hSelf, IDC_DAT_EXT_PAGE_PREV_BUTTON, L"", DATA_EXTRACT_PAGE_PREV, FALSE); loadBitmap(_hSelf, IDC_DAT_EXT_PAGE_NEXT_BUTTON, IDB_DAT_EXT_PAGE_NEXT_BITMAP); addTooltip(_hSelf, IDC_DAT_EXT_PAGE_NEXT_BUTTON, L"", DATA_EXTRACT_PAGE_NEXT, FALSE); loadBitmap(_hSelf, IDC_DAT_EXT_PAGE_ADD_BUTTON, IDB_DAT_EXT_PAGE_ADD_BITMAP); addTooltip(_hSelf, IDC_DAT_EXT_PAGE_ADD_BUTTON, L"", DATA_EXTRACT_PAGE_ADD, FALSE); loadBitmap(_hSelf, IDC_DAT_EXT_PAGE_DEL_BUTTON, IDB_DAT_EXT_PAGE_DEL_BITMAP); addTooltip(_hSelf, IDC_DAT_EXT_PAGE_DEL_BUTTON, L"", DATA_EXTRACT_PAGE_DEL, FALSE); loadBitmap(_hSelf, IDC_DAT_EXT_ITEM_DOWN_BUTTON, IDB_VIZ_MOVE_DOWN_BITMAP); addTooltip(_hSelf, IDC_DAT_EXT_ITEM_DOWN_BUTTON, L"", DATA_EXTRACT_MOVE_DOWN, FALSE); loadBitmap(_hSelf, IDC_DAT_EXT_ITEM_UP_BUTTON, IDB_VIZ_MOVE_UP_BITMAP); addTooltip(_hSelf, IDC_DAT_EXT_ITEM_UP_BUTTON, L"", DATA_EXTRACT_MOVE_UP, FALSE); CheckDlgButton(_hSelf, IDC_DAT_EXT_TEMPLATE_CURR_ONLY, BST_CHECKED); loadBitmap(_hSelf, IDC_DAT_EXT_INFO_BUTTON, IDB_VIZ_INFO_BITMAP); addTooltip(_hSelf, IDC_DAT_EXT_INFO_BUTTON, L"", VIZ_PANEL_INFO_TIP, FALSE); if constexpr(_gLanguage != LANG_ENGLISH) localize(); goToCenter(); SendMessage(_hParent, NPPM_DMMSHOW, 0, (LPARAM)_hSelf); SetFocus(_hSelf); } void DataExtractDialog::initDialog(const string fileType, const vector<RecordInfo>& recInfoList) { initFileType = fileType; pRecInfoList = &recInfoList; initFileTypeLabel = _configIO.getConfigWideChar(initFileType, "FileLabel"); extractsConfigFile = Utils::WideToNarrow(_configIO.getConfigFile(_configIO.CONFIG_EXTRACTS)); initRecTypeLists(); loadTemplatesList(); newTemplate(); moveIndicators(0, TRUE); } void DataExtractDialog::refreshDarkMode() { NPPDM_AutoSubclassAndThemeChildControls(_hSelf); redraw(); } INT_PTR CALLBACK DataExtractDialog::run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: switch LOWORD(wParam) { case IDC_DAT_EXT_ITEM_RECORD_01: case IDC_DAT_EXT_ITEM_RECORD_02: case IDC_DAT_EXT_ITEM_RECORD_03: case IDC_DAT_EXT_ITEM_RECORD_04: case IDC_DAT_EXT_ITEM_RECORD_05: case IDC_DAT_EXT_ITEM_RECORD_06: case IDC_DAT_EXT_ITEM_RECORD_07: case IDC_DAT_EXT_ITEM_RECORD_08: case IDC_DAT_EXT_ITEM_RECORD_09: case IDC_DAT_EXT_ITEM_RECORD_10: switch HIWORD(wParam) { case CBN_SELCHANGE: initLineItemFieldList(LOWORD(wParam) - IDC_DAT_EXT_ITEM_RECORD_01); break; case CBN_SETFOCUS: moveIndicators(LOWORD(wParam) - IDC_DAT_EXT_ITEM_RECORD_01, FALSE); break; } break; case IDC_DAT_EXT_ITEM_FIELD_01: case IDC_DAT_EXT_ITEM_FIELD_02: case IDC_DAT_EXT_ITEM_FIELD_03: case IDC_DAT_EXT_ITEM_FIELD_04: case IDC_DAT_EXT_ITEM_FIELD_05: case IDC_DAT_EXT_ITEM_FIELD_06: case IDC_DAT_EXT_ITEM_FIELD_07: case IDC_DAT_EXT_ITEM_FIELD_08: case IDC_DAT_EXT_ITEM_FIELD_09: case IDC_DAT_EXT_ITEM_FIELD_10: switch HIWORD(wParam) { case CBN_SETFOCUS: moveIndicators(LOWORD(wParam) - IDC_DAT_EXT_ITEM_FIELD_01, FALSE); break; } break; case IDC_DAT_EXT_ITEM_PREFIX_01: case IDC_DAT_EXT_ITEM_PREFIX_02: case IDC_DAT_EXT_ITEM_PREFIX_03: case IDC_DAT_EXT_ITEM_PREFIX_04: case IDC_DAT_EXT_ITEM_PREFIX_05: case IDC_DAT_EXT_ITEM_PREFIX_06: case IDC_DAT_EXT_ITEM_PREFIX_07: case IDC_DAT_EXT_ITEM_PREFIX_08: case IDC_DAT_EXT_ITEM_PREFIX_09: case IDC_DAT_EXT_ITEM_PREFIX_10: switch HIWORD(wParam) { case EN_SETFOCUS: moveIndicators(LOWORD(wParam) - IDC_DAT_EXT_ITEM_PREFIX_01, FALSE); break; } break; case IDC_DAT_EXT_ITEM_SUFFIX_01: case IDC_DAT_EXT_ITEM_SUFFIX_02: case IDC_DAT_EXT_ITEM_SUFFIX_03: case IDC_DAT_EXT_ITEM_SUFFIX_04: case IDC_DAT_EXT_ITEM_SUFFIX_05: case IDC_DAT_EXT_ITEM_SUFFIX_06: case IDC_DAT_EXT_ITEM_SUFFIX_07: case IDC_DAT_EXT_ITEM_SUFFIX_08: case IDC_DAT_EXT_ITEM_SUFFIX_09: case IDC_DAT_EXT_ITEM_SUFFIX_10: switch HIWORD(wParam) { case EN_SETFOCUS: moveIndicators(LOWORD(wParam) - IDC_DAT_EXT_ITEM_SUFFIX_01, FALSE); break; } break; case IDC_DAT_EXT_ITEM_ADD_BTN_01: case IDC_DAT_EXT_ITEM_ADD_BTN_02: case IDC_DAT_EXT_ITEM_ADD_BTN_03: case IDC_DAT_EXT_ITEM_ADD_BTN_04: case IDC_DAT_EXT_ITEM_ADD_BTN_05: case IDC_DAT_EXT_ITEM_ADD_BTN_06: case IDC_DAT_EXT_ITEM_ADD_BTN_07: case IDC_DAT_EXT_ITEM_ADD_BTN_08: case IDC_DAT_EXT_ITEM_ADD_BTN_09: case IDC_DAT_EXT_ITEM_ADD_BTN_10: addLineItem(LOWORD(wParam) - IDC_DAT_EXT_ITEM_ADD_BTN_01); break; case IDC_DAT_EXT_ITEM_DEL_BTN_01: case IDC_DAT_EXT_ITEM_DEL_BTN_02: case IDC_DAT_EXT_ITEM_DEL_BTN_03: case IDC_DAT_EXT_ITEM_DEL_BTN_04: case IDC_DAT_EXT_ITEM_DEL_BTN_05: case IDC_DAT_EXT_ITEM_DEL_BTN_06: case IDC_DAT_EXT_ITEM_DEL_BTN_07: case IDC_DAT_EXT_ITEM_DEL_BTN_08: case IDC_DAT_EXT_ITEM_DEL_BTN_09: case IDC_DAT_EXT_ITEM_DEL_BTN_10: delLineItem(LOWORD(wParam) - IDC_DAT_EXT_ITEM_DEL_BTN_01); break; case IDC_DAT_EXT_PAGE_PREV_BUTTON: previousPage(); break; case IDC_DAT_EXT_PAGE_NEXT_BUTTON: nextPage(); break; case IDC_DAT_EXT_PAGE_ADD_BUTTON: addPage(); break; case IDC_DAT_EXT_PAGE_DEL_BUTTON: deletePage(); break; case IDC_DAT_EXT_ITEM_DOWN_BUTTON: swapLineItems(currentLineItem, currentLineItem + 1); break; case IDC_DAT_EXT_ITEM_UP_BUTTON: swapLineItems(currentLineItem, currentLineItem - 1); break; case IDC_DAT_EXT_INFO_BUTTON: ShellExecute(NULL, L"open", DATA_EXTRACT_INFO_README, NULL, NULL, SW_SHOW); break; case IDC_DAT_EXT_EXTRACT_BTN: extractData(); break; case IDCANCEL: case IDCLOSE: display(FALSE); return TRUE; case IDC_DAT_EXT_TEMPLATE_CURR_ONLY: loadTemplatesList(); newTemplate(); break; case IDC_DAT_EXT_TEMPLATE_LIST: switch HIWORD(wParam) { case CBN_SELCHANGE: loadTemplate(); break; } break; case IDC_DAT_EXT_TEMPLATE_NAME: switch HIWORD(wParam) { case EN_CHANGE: enableSaveTemplate(); break; } break; case IDC_DAT_EXT_TEMPLATE_SAVE_BTN: saveTemplate(); break; case IDC_DAT_EXT_TEMPLATE_NEW_BTN: newTemplate(); break; case IDC_DAT_EXT_TEMPLATE_DEL_BTN: deleteTemplate(); break; } break; case WM_NOTIFY: switch (((LPNMHDR)lParam)->code) { case NM_CLICK: case NM_RETURN: ShellExecute(NULL, L"open", DATA_EXTRACT_KEYNAV_README, NULL, NULL, SW_SHOW); display(FALSE); return TRUE; } break; case WM_INITDIALOG: NPPDM_InitSysLink(GetDlgItem(_hSelf, IDC_DAT_EXT_NEW_KEYBOARD_TIP)); NPPDM_AutoSubclassAndThemeChildControls(_hSelf); break; case WM_CTLCOLORSTATIC: switch (GetDlgCtrlID((HWND)lParam)) { case IDC_DAT_EXT_CURRENT_LINE: case IDC_DAT_EXT_NEW_KEYBOARD_TIP: return NPPDM_OnCtlColorSysLink(reinterpret_cast<HDC>(wParam)); break; default: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } } break; case WM_CTLCOLORDLG: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLOREDIT: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorSofter(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLORLISTBOX: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorListbox(wParam, lParam); } break; case WM_PRINTCLIENT: if (NPPDM_IsEnabled()) return TRUE; break; } return FALSE; } void DataExtractDialog::localize() { SetWindowText(_hSelf, DATA_EXTRACT_DIALOG_TITLE); SetDlgItemText(_hSelf, IDC_DAT_EXT_PREFIX_LABEL, DATA_EXTRACT_PREFIX_LABEL); SetDlgItemText(_hSelf, IDC_DAT_EXT_RECORD_LABEL, DATA_EXTRACT_RECORD_LABEL); SetDlgItemText(_hSelf, IDC_DAT_EXT_FIELD_LABEL, DATA_EXTRACT_FIELD_LABEL); SetDlgItemText(_hSelf, IDC_DAT_EXT_FIELD_TRIM, DATA_EXTRACT_FIELD_TRIM); SetDlgItemText(_hSelf, IDC_DAT_EXT_SUFFIX_LABEL, DATA_EXTRACT_SUFFIX_LABEL); SetDlgItemText(_hSelf, IDC_DAT_EXT_NEW_KEYBOARD_TIP, DATA_EXTRACT_KEYBOARD_TIP); SetDlgItemText(_hSelf, IDC_DAT_EXT_NEW_LINE_TAB_TIP, DATA_EXTRACT_NEW_LINE_TAB); SetDlgItemText(_hSelf, IDC_DAT_EXT_EXTRACT_BTN, DATA_EXTRACT_EXTRACT_BTN); SetDlgItemText(_hSelf, IDCLOSE, DATA_EXTRACT_CLOSE_BTN); SetDlgItemText(_hSelf, IDC_DAT_EXT_TEMPLATE_GROUP, DATA_EXTRACT_TEMPLATE_GROUP); SetDlgItemText(_hSelf, IDC_DAT_EXT_TEMPLATE_CURR_ONLY, DATA_EXTRACT_TEMPLATE_CURR); SetDlgItemText(_hSelf, IDC_DAT_EXT_TEMPLATE_LIST_LABEL, DATA_EXTRACT_TEMPLATE_LOAD); SetDlgItemText(_hSelf, IDC_DAT_EXT_TEMPLATE_NAME_LABEL, DATA_EXTRACT_TEMPLATE_NAME); SetDlgItemText(_hSelf, IDC_DAT_EXT_TEMPLATE_SAVE_BTN, DATA_EXTRACT_TEMPLATE_SAVE); SetDlgItemText(_hSelf, IDC_DAT_EXT_TEMPLATE_NEW_BTN, DATA_EXTRACT_TEMPLATE_NEW); SetDlgItemText(_hSelf, IDC_DAT_EXT_TEMPLATE_DEL_BTN, DATA_EXTRACT_TEMPLATE_DEL); } void DataExtractDialog::initRecTypeLists() { for (int i{}; i < LINES_PER_PAGE; ++i) { // Load Record Type Dropdown lists HWND hRecList = GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_RECORD_01 + i); resetDropDown(hRecList); for (size_t j{}; j < pRecInfoList->size(); ++j) { SendMessage(hRecList, CB_ADDSTRING, NULL, (LPARAM)pRecInfoList->at(j).label.c_str()); } } } void DataExtractDialog::initLineItemFieldList(int line) { HWND hFTList = GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_FIELD_01 + line); resetDropDown(hFTList); string fileType{}; if (!_vizPanel.getDocFileType(fileType) || (initFileType != fileType)) return; size_t RTIndex = SendDlgItemMessage(_hSelf, IDC_DAT_EXT_ITEM_RECORD_01 + line, CB_GETCURSEL, NULL, NULL); if (RTIndex == 0) return; --RTIndex; const RecordInfo& RT{ pRecInfoList->at(RTIndex) }; size_t FTCount{ RT.fieldLabels.size() }; for (size_t i{}; i < FTCount; ++i) { SendMessage(hFTList, CB_ADDSTRING, NULL, (LPARAM)RT.fieldLabels[i].c_str()); } } void DataExtractDialog::moveIndicators(int line, bool focusPrefix) { currentLineItem = line; RECT rc; GetWindowRect(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_DEL_BTN_01 + line), &rc); POINT newPos{ rc.right + 1, rc.top + 2 }; ScreenToClient(_hSelf, &newPos); SetWindowPos(hIndicator, HWND_TOP, newPos.x, newPos.y, NULL, NULL, SWP_NOSIZE | SWP_NOOWNERZORDER); EnableWindow(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_DOWN_BUTTON), line < LINES_PER_PAGE - 1 || currentPage < getPageCount() - 1); EnableWindow(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_UP_BUTTON), line > 0 || currentPage > 0); if (focusPrefix) SetFocus(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_PREFIX_01 + line)); } void DataExtractDialog::resetDropDown(HWND hList) { SendMessage(hList, CB_RESETCONTENT, NULL, NULL); SendMessage(hList, CB_ADDSTRING, NULL, (LPARAM)L"-"); Utils::setComboBoxSelection(hList, 0); } bool DataExtractDialog::isBlankLineItem(const LineItemInfo& lineItem) { return (lineItem.prefix.length() + lineItem.suffix.length() + lineItem.recType + lineItem.fieldType == 0); } void DataExtractDialog::addLineItem(int line) { int idx{ (currentPage * 10) + line }; readPage(); if (isBlankLineItem(liBuffer.back())) liBuffer.erase(liBuffer.end() - 1); LineItemInfo liEmpty{}; liBuffer.insert(liBuffer.begin() + idx, liEmpty); if (liBuffer.size() > MAX_BUFFER_LINES) liBuffer.resize(MAX_BUFFER_LINES); loadPage(currentPage); moveIndicators(line, TRUE); } void DataExtractDialog::delLineItem(int line) { int idx{ (currentPage * 10) + line }; readPage(); liBuffer.erase(liBuffer.begin() + idx); loadPage(currentPage); moveIndicators(line, TRUE); } void DataExtractDialog::clearLineItem(int line) { SetDlgItemText(_hSelf, IDC_DAT_EXT_ITEM_PREFIX_01 + line, L""); SetDlgItemText(_hSelf, IDC_DAT_EXT_ITEM_SUFFIX_01 + line, L""); Utils::setComboBoxSelection(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_RECORD_01 + line), 0); resetDropDown(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_FIELD_01 + line)); } void DataExtractDialog::getLineItem(int line, LineItemInfo& lineItem) { TCHAR prefix[MAX_PATH + 1]; GetDlgItemText(_hSelf, IDC_DAT_EXT_ITEM_PREFIX_01 + line, prefix, MAX_PATH); lineItem.prefix = wstring{ prefix }; TCHAR suffix[MAX_PATH + 1]; GetDlgItemText(_hSelf, IDC_DAT_EXT_ITEM_SUFFIX_01 + line, suffix, MAX_PATH); lineItem.suffix = wstring{ suffix }; lineItem.recType = static_cast<int>( SendDlgItemMessage(_hSelf, IDC_DAT_EXT_ITEM_RECORD_01 + line, CB_GETCURSEL, NULL, NULL)); lineItem.fieldType = static_cast<int>( SendDlgItemMessage(_hSelf, IDC_DAT_EXT_ITEM_FIELD_01 + line, CB_GETCURSEL, NULL, NULL)); } void DataExtractDialog::setLineItem(int line, LineItemInfo& lineItem) { SetDlgItemText(_hSelf, IDC_DAT_EXT_ITEM_PREFIX_01 + line, lineItem.prefix.c_str()); SetDlgItemText(_hSelf, IDC_DAT_EXT_ITEM_SUFFIX_01 + line, lineItem.suffix.c_str()); Utils::setComboBoxSelection(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_RECORD_01 + line), lineItem.recType); initLineItemFieldList(line); Utils::setComboBoxSelection(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_FIELD_01 + line), lineItem.fieldType); } void DataExtractDialog::swapLineItems(int lineFrom, int lineTo) { int idxFrom{ (currentPage * 10) + lineFrom }; int idxTo{ (currentPage * 10) + lineTo }; int page{ currentPage }; int line{ lineTo }; int ctrlID{ GetDlgCtrlID(GetFocus()) }; int ctrlTop{ (ctrlID - currentLineItem == IDC_DAT_EXT_ITEM_SUFFIX_01) ? IDC_DAT_EXT_ITEM_SUFFIX_01 : IDC_DAT_EXT_ITEM_PREFIX_01 }; if (idxTo < 0 || idxTo >= static_cast<int>(liBuffer.size())) return; readPage(); if (lineTo >= 0 && lineTo < LINES_PER_PAGE) { getLineItem(lineFrom, liBuffer[idxTo]); getLineItem(lineTo, liBuffer[idxFrom]); } else { LineItemInfo& liFrom{ liBuffer[idxFrom] }; LineItemInfo liTo{ liBuffer[idxTo] }; getLineItem(lineFrom, liBuffer[idxTo]); liFrom.prefix = liTo.prefix; liFrom.recType = liTo.recType; liFrom.fieldType = liTo.fieldType; liFrom.suffix = liTo.suffix; if (lineTo < 0) { line = LINES_PER_PAGE - 1; --page; } else if (lineTo >= LINES_PER_PAGE) { line = 0; ++page; } } loadPage(page); SetFocus(GetDlgItem(_hSelf, ctrlTop + line)); } void DataExtractDialog::gotoLine(int ctrlID, int lineTo) { int idxTo{ (currentPage * 10) + lineTo }; int page{ currentPage }; int line{ lineTo }; int ctrlTop{ ctrlID - currentLineItem }; if (idxTo < 0 || idxTo >= static_cast<int>(liBuffer.size())) return; if (lineTo < 0 || lineTo >= LINES_PER_PAGE) { readPage(); if (lineTo < 0) { line = LINES_PER_PAGE - 1; --page; } else if (lineTo >= LINES_PER_PAGE) { line = 0; ++page; } loadPage(page); } SetFocus(GetDlgItem(_hSelf, ctrlTop + line)); } size_t DataExtractDialog::getValidLineItems(vector<LineItemInfo>& validLIs, bool validFieldType, bool activateNLT) { readPage(); validLIs.clear(); for (size_t i{}; i < liBuffer.size(); ++i) { LineItemInfo lineInfo{ liBuffer[i] }; if (isBlankLineItem(lineInfo)) continue; if (validFieldType && lineInfo.fieldType == 0) continue; // Decrement both recType & fieldType by one to account for the first "-" item in their dropdowns lineInfo.recType--; lineInfo.fieldType--; if (activateNLT) { _configIO.ActivateNewLineTabs(lineInfo.prefix); _configIO.ActivateNewLineTabs(lineInfo.suffix); } validLIs.emplace_back(lineInfo); } return validLIs.size(); } void DataExtractDialog::extractData() { vector<LineItemInfo> validLIs{}; PSCIFUNC_T sciFunc; void* sciPtr; if (getValidLineItems(validLIs, TRUE, TRUE) < 1) return; if (!getDirectScintillaFunc(sciFunc, sciPtr)) return; string fileType{}; if (!_vizPanel.getDocFileType(fileType) || (initFileType != fileType)) { MessageBox(_hSelf, DATA_EXTRACT_CHANGED_DOC, DATA_EXTRACT_DIALOG_TITLE, MB_OK | MB_ICONSTOP); return; } const intptr_t lineCount{ sciFunc(sciPtr, SCI_GETLINECOUNT, NULL, NULL) }; if (lineCount < 1) return; const size_t regexedCount{ pRecInfoList->size() }; string lineTextCStr(FW_LINE_MAX_LENGTH, '\0'); string recStartText{}, eolMarker{}; size_t eolMarkerLen; intptr_t eolMarkerPos, recStartLine{}, startPos, endPos, recStartPos{}; bool newRec{ TRUE }; bool recMatch{}; wstring extract{}; string fieldText(FW_LINE_MAX_LENGTH, '\0'); Sci_TextRangeFull sciTR{}; sciTR.lpstrText = fieldText.data(); eolMarker = _configIO.getConfigStringA(fileType, "RecordTerminator"); eolMarkerLen = eolMarker.length(); bool byteCols{ !_configIO.getMultiByteLexing(fileType) }; bool trimSpaces{ IsDlgButtonChecked(_hSelf, IDC_DAT_EXT_FIELD_TRIM) == BST_CHECKED }; const std::wregex regexTrimSpaces{ std::wregex(L"^\\s+|\\s+$") }; wstring fieldData{}; const intptr_t endLine{ lineCount }; for (intptr_t currentLine{}; currentLine < endLine; ++currentLine) { if (sciFunc(sciPtr, SCI_LINELENGTH, currentLine, NULL) > FW_LINE_MAX_LENGTH) { continue; } sciFunc(sciPtr, SCI_GETLINE, currentLine, (LPARAM)lineTextCStr.c_str()); startPos = sciFunc(sciPtr, SCI_POSITIONFROMLINE, currentLine, NULL); endPos = sciFunc(sciPtr, SCI_GETLINEENDPOSITION, currentLine, NULL); string_view lineText{ lineTextCStr.c_str(), static_cast<size_t>(endPos - startPos)}; if (newRec) { recStartLine = currentLine; recStartPos = startPos; recStartText = lineText; } if (newRec && lineText.empty()) { continue; } if (eolMarkerLen == 0) { newRec = TRUE; eolMarkerPos = endPos; } else if (lineText.length() > eolMarkerLen && (lineText.substr(lineText.length() - eolMarkerLen) == eolMarker)) { newRec = TRUE; eolMarkerPos = endPos - eolMarkerLen; } else if (currentLine < endLine) { newRec = FALSE; continue; } else { eolMarkerPos = endPos; } size_t regexIndex{}; while (regexIndex < regexedCount) { if (regex_match(recStartText, pRecInfoList->at(regexIndex).regExpr)) break; ++regexIndex; } if (regexIndex >= regexedCount) continue; recMatch = FALSE; for (size_t j{}; j < validLIs.size(); ++j) { const LineItemInfo& LI{ validLIs[j] }; const RecordInfo& RI{ pRecInfoList->at(LI.recType) }; if (static_cast<int>(regexIndex) != LI.recType) continue; if (byteCols) { sciTR.chrg.cpMin = recStartPos + RI.fieldStarts[LI.fieldType]; sciTR.chrg.cpMax = sciTR.chrg.cpMin + RI.fieldWidths[LI.fieldType]; } else { sciTR.chrg.cpMin = sciFunc(sciPtr, SCI_POSITIONRELATIVE, recStartPos, (LPARAM)RI.fieldStarts[LI.fieldType]); sciTR.chrg.cpMax = sciFunc(sciPtr, SCI_POSITIONRELATIVE, sciTR.chrg.cpMin, (LPARAM)RI.fieldWidths[LI.fieldType]); } if (sciTR.chrg.cpMax > eolMarkerPos || sciTR.chrg.cpMax == 0) sciTR.chrg.cpMax = eolMarkerPos; if (sciTR.chrg.cpMin < eolMarkerPos && (recStartPos + RI.fieldStarts[LI.fieldType] == 0 || sciTR.chrg.cpMin > 0)) { sciFunc(sciPtr, SCI_GETTEXTRANGE, NULL, (LPARAM)&sciTR); fieldData = Utils::NarrowToWide(fieldText.c_str()); if (trimSpaces) fieldData = std::regex_replace(fieldData, regexTrimSpaces, L""); extract += validLIs[j].prefix + fieldData + validLIs[j].suffix; recMatch = TRUE; } } if (recMatch) extract += L"\n"; } nppMessage(NPPM_MENUCOMMAND, 0, IDM_FILE_NEW); sciFunc(sciPtr, SCI_SETTEXT, NULL, (LPARAM)(Utils::WideToNarrow(extract)).c_str()); } int DataExtractDialog::loadTemplatesList() { resetDropDown(hTemplatesList); SetWindowText(hTemplateName, L""); bool currentOnly{ IsDlgButtonChecked(_hSelf, IDC_DAT_EXT_TEMPLATE_CURR_ONLY) == BST_CHECKED }; int sectionCount{}; vector<string> sectionList{}; sectionCount = _configIO.getConfigAllSectionsList(sectionList, extractsConfigFile); for (int i{}; i < sectionCount; ++i) { string templateName{}; bool matching{}; matching = (initFileType == _configIO.getConfigStringA(sectionList[i], "FileType", "", extractsConfigFile)); templateName = currentOnly ? (matching ? sectionList[i] : "") : (string{ matching ? "" : DATA_EXTRACT_TEMPLATE_OTHER } + sectionList[i]); if (!templateName.empty()) SendMessage(hTemplatesList, CB_ADDSTRING, NULL, (LPARAM)Utils::NarrowToWide(templateName).c_str()); } return sectionCount; } void DataExtractDialog::loadTemplate() { string templateName{ getSelectedTemplate() }; if (templateName.length() <= 1) { newTemplate(); return; } SetWindowText(hTemplateName, Utils::NarrowToWide(templateName).c_str()); CheckDlgButton(_hSelf, IDC_DAT_EXT_FIELD_TRIM, _configIO.getConfigStringA(templateName, "TrimSpaces", "N", extractsConfigFile) == "Y" ? BST_CHECKED : BST_UNCHECKED); EnableWindow(GetDlgItem(_hSelf, IDC_DAT_EXT_TEMPLATE_SAVE_BTN), TRUE); enableDeleteTemplate(); int liCount{ _configIO.getConfigInt(templateName, "LineItemCount", 0, extractsConfigFile) }; if (liCount < 1) { newTemplate(); return; } int loadCount{ liCount <= MAX_BUFFER_LINES ? liCount : MAX_BUFFER_LINES }; liBuffer.clear(); liBuffer.resize(static_cast<size_t>(getPageCount(loadCount)) * 10); for (int i{}; i < loadCount; ++i) { LineItemInfo& LI{ liBuffer[i] }; char tNum[4]; snprintf(tNum, 4, "%02d_", i); string numSuffix{ tNum }; LI.prefix = _configIO.getConfigWideChar(templateName, (numSuffix + "Prefix").c_str(), "", extractsConfigFile); LI.suffix = _configIO.getConfigWideChar(templateName, (numSuffix + "Suffix").c_str(), "", extractsConfigFile); LI.recType = _configIO.getConfigInt(templateName, (numSuffix + "Record").c_str(), 0, extractsConfigFile); if (LI.recType > static_cast<int>(pRecInfoList->size())) LI.recType = -1; if (LI.recType >= 0) { LI.fieldType = _configIO.getConfigInt(templateName, (numSuffix + "Field").c_str(), 0, extractsConfigFile); if (LI.fieldType > static_cast<int>(pRecInfoList->at(LI.recType).fieldLabels.size())) LI.fieldType = -1; } LI.recType++; LI.fieldType++; } loadPage(0); } string DataExtractDialog::getSelectedTemplate() const { bool validTemplate{ SendMessage(hTemplatesList, CB_GETCURSEL, NULL, NULL) > 0 }; string templateName{}; if (validTemplate) { wchar_t tName[MAX_TEMPLATE_NAME + 1]; GetWindowText(hTemplatesList, tName, MAX_TEMPLATE_NAME); templateName = Utils::WideToNarrow(tName); size_t otherLen = string{ DATA_EXTRACT_TEMPLATE_OTHER }.length(); if (templateName.substr(0, otherLen) == DATA_EXTRACT_TEMPLATE_OTHER) templateName = templateName.substr(otherLen); } return templateName; } string DataExtractDialog::getTemplateName() const { wchar_t tName[MAX_TEMPLATE_NAME + 1]; GetWindowText(hTemplateName, tName, MAX_TEMPLATE_NAME); return Utils::WideToNarrow(tName); } void DataExtractDialog::enableSaveTemplate() { EnableWindow(GetDlgItem(_hSelf, IDC_DAT_EXT_TEMPLATE_SAVE_BTN), getTemplateName().length() > 2); } void DataExtractDialog::enableDeleteTemplate() { int selected = static_cast<int>(SendMessage(hTemplatesList, CB_GETCURSEL, NULL, NULL)); EnableWindow(GetDlgItem(_hSelf, IDC_DAT_EXT_TEMPLATE_DEL_BTN), selected > 0); } void DataExtractDialog::saveTemplate() { vector<LineItemInfo> validLIs{}; getValidLineItems(validLIs, FALSE, FALSE); string templateName{ getTemplateName() }; if (templateName.length() < 3) return; // First, delete any existing section with the same name _configIO.deleteSection(templateName, extractsConfigFile); _configIO.setConfigStringA(templateName, "FileType", initFileType, extractsConfigFile); _configIO.setConfigMultiByte(templateName, "FileLabel", initFileTypeLabel, extractsConfigFile); _configIO.setConfigStringA(templateName, "LineItemCount", to_string(validLIs.size()), extractsConfigFile); _configIO.setConfigStringA(templateName, "TrimSpaces", (IsDlgButtonChecked(_hSelf, IDC_DAT_EXT_FIELD_TRIM) == BST_CHECKED) ? "Y" : "N", extractsConfigFile); for (size_t i{}; i < validLIs.size(); ++i) { LineItemInfo& LI = validLIs[i]; char tNum[4]; snprintf(tNum, 4, "%02d_", static_cast<int>(i)); string numSuffix{ tNum }; _configIO.setConfigMultiByte(templateName, numSuffix + "Prefix", LI.prefix, extractsConfigFile); _configIO.setConfigStringA(templateName, numSuffix + "Record", to_string(LI.recType), extractsConfigFile); _configIO.setConfigStringA(templateName, numSuffix + "Field", to_string(LI.fieldType), extractsConfigFile); _configIO.setConfigMultiByte(templateName, numSuffix + "Suffix", LI.suffix, extractsConfigFile); } wstring lbName{ Utils::NarrowToWide(templateName) }; if (SendMessage(hTemplatesList, CB_FINDSTRING, (WPARAM)-1, (LPARAM)lbName.c_str()) == CB_ERR) { Utils::setComboBoxSelection(hTemplatesList, static_cast<int>(SendMessage(hTemplatesList, CB_ADDSTRING, NULL, (LPARAM)lbName.c_str()))); } loadTemplate(); } void DataExtractDialog::newTemplate() { liBuffer.clear(); liBuffer.resize(LINES_PER_PAGE); loadPage(0); Utils::setComboBoxSelection(hTemplatesList, 0); SetWindowText(hTemplateName, L""); CheckDlgButton(_hSelf, IDC_DAT_EXT_FIELD_TRIM, BST_UNCHECKED); EnableWindow(GetDlgItem(_hSelf, IDC_DAT_EXT_TEMPLATE_SAVE_BTN), FALSE); enableDeleteTemplate(); } void DataExtractDialog::deleteTemplate() { if (MessageBox(_hSelf, DATA_EXTRACT_DELETE_PROMPT, DATA_EXTRACT_DIALOG_TITLE, MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) == IDNO) return; _configIO.deleteSection(getTemplateName(), extractsConfigFile); SendMessage(hTemplatesList, CB_DELETESTRING, SendMessage(hTemplatesList, CB_GETCURSEL, 0, NULL), NULL); newTemplate(); } int DataExtractDialog::getPageCount(int items) { if (items == 0) items = static_cast<int>(liBuffer.size()); return ((items - 1) / 10) + 1; } void DataExtractDialog::loadPage(int pageNum) { size_t seq{ static_cast<size_t>(pageNum) * LINES_PER_PAGE }; if (liBuffer.size() <= seq) return; if (liBuffer.size() < (seq + LINES_PER_PAGE)) liBuffer.resize(seq + LINES_PER_PAGE); currentPage = pageNum; enablePageButtons(); for (int i{}; i < LINES_PER_PAGE; ++i) { setLineItem(i, liBuffer[seq]); SetDlgItemText(_hSelf, IDC_DAT_EXT_ITEM_SEQ_01 + i, to_wstring(++seq).c_str()); } moveIndicators(0, TRUE); } void DataExtractDialog::readPage() { size_t seq{ static_cast<size_t>(currentPage) * LINES_PER_PAGE }; if (liBuffer.size() < (seq + LINES_PER_PAGE)) liBuffer.resize(seq + LINES_PER_PAGE); for (int i{}; i < LINES_PER_PAGE; ++i) { getLineItem(i, liBuffer[seq + i]); } } void DataExtractDialog::previousPage() { if (currentPage > 0) readPage(); loadPage(currentPage - 1); } void DataExtractDialog::nextPage() { if (currentPage < getPageCount() - 1) { readPage(); loadPage(currentPage + 1); } } void DataExtractDialog::addPage() { const int pageCount{ getPageCount() }; if (pageCount < MAX_PAGES) { readPage(); liBuffer.resize(liBuffer.size() + LINES_PER_PAGE); loadPage(pageCount); } } void DataExtractDialog::deletePage() { if (currentPage > 0) { int start{ currentPage * 10 }; liBuffer.erase(liBuffer.begin() + start, liBuffer.begin() + start + LINES_PER_PAGE); loadPage(currentPage - 1); } } void DataExtractDialog::enablePageButtons() { const int pageCount{ getPageCount() }; EnableWindow(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_ADD_BTN_10), pageCount < MAX_PAGES); EnableWindow(GetDlgItem(_hSelf, IDC_DAT_EXT_PAGE_PREV_BUTTON), currentPage > 0); EnableWindow(GetDlgItem(_hSelf, IDC_DAT_EXT_PAGE_NEXT_BUTTON), currentPage < pageCount - 1); EnableWindow(GetDlgItem(_hSelf, IDC_DAT_EXT_PAGE_ADD_BUTTON), pageCount < MAX_PAGES); EnableWindow(GetDlgItem(_hSelf, IDC_DAT_EXT_PAGE_DEL_BUTTON), currentPage > 0); } bool DataExtractDialog::processKey(HWND hCtrl, WPARAM wParam) { int ctrlID{ GetDlgCtrlID(hCtrl) }; switch (wParam) { case VK_DOWN: if (Utils::checkKeyHeldDown(VK_CONTROL)) { swapLineItems(currentLineItem, currentLineItem + 1); return TRUE; } else { gotoLine(ctrlID, currentLineItem + 1); return TRUE; } break; case VK_UP: if (Utils::checkKeyHeldDown(VK_CONTROL)) { swapLineItems(currentLineItem, currentLineItem - 1); return TRUE; } else { gotoLine(ctrlID, currentLineItem - 1); return TRUE; } break; case VK_HOME: if (Utils::checkKeyHeldDown(VK_CONTROL)) { SetFocus(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_PREFIX_01)); return TRUE; } break; case VK_END: if (Utils::checkKeyHeldDown(VK_CONTROL)) { SetFocus(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_SUFFIX_01 + LINES_PER_PAGE - 1)); return TRUE; } return TRUE; break; case VK_PRIOR: if (Utils::checkKeyHeldDown(VK_CONTROL)) { previousPage(); } else { SetFocus(GetDlgItem(_hSelf, ctrlID - currentLineItem)); } return TRUE; break; case VK_NEXT: if (Utils::checkKeyHeldDown(VK_CONTROL)) { nextPage(); } else { SetFocus(GetDlgItem(_hSelf, ctrlID - currentLineItem + LINES_PER_PAGE - 1)); } return TRUE; break; case VK_ADD: case VK_OEM_PLUS: case VK_INSERT: if (Utils::checkKeyHeldDown(VK_CONTROL) && Utils::checkKeyHeldDown(VK_SHIFT)) { addPage(); return TRUE; } else if (Utils::checkKeyHeldDown(VK_CONTROL)) { addLineItem(currentLineItem); return TRUE; } break; case VK_SUBTRACT: case VK_OEM_MINUS: case VK_DELETE: if (Utils::checkKeyHeldDown(VK_CONTROL) && Utils::checkKeyHeldDown(VK_SHIFT)) { deletePage(); return TRUE; } else if (Utils::checkKeyHeldDown(VK_CONTROL)) { delLineItem(currentLineItem); return TRUE; } break; } return FALSE; } bool DataExtractDialog::processSysKey(HWND, WPARAM wParam) { switch (wParam) { case VK_HOME: if (Utils::checkKeyHeldDown(VK_MENU)) { SetFocus(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_PREFIX_01 + currentLineItem)); return TRUE; } break; case VK_END: if (Utils::checkKeyHeldDown(VK_MENU)) { SetFocus(GetDlgItem(_hSelf, IDC_DAT_EXT_ITEM_SUFFIX_01 + currentLineItem)); return TRUE; } break; } return FALSE; }
34,832
C++
.cpp
855
34.45614
125
0.67037
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,110
ThemeDialog.cpp
shriprem_FWDataViz/src/Dialogs/ThemeDialog.cpp
#include "ThemeDialog.h" #include "EximFileTypeDialog.h" extern HINSTANCE _gModule; extern ThemeDialog _themeDlg; extern EximFileTypeDialog _eximDlg; void ThemeDialog::doDialog(HINSTANCE hInst) { if (!isCreated()) { Window::init(hInst, nppData._nppHandle); create(IDD_THEME_DEFINER_DIALOG); } initComponent(_hSelf); using Utils::addTooltip; using Utils::loadBitmap; hThemesLB = GetDlgItem(_hSelf, IDC_THEME_DEF_LIST_BOX); hStylesLB = GetDlgItem(_hSelf, IDC_THEME_STYLE_LIST_BOX); SendDlgItemMessage(_hSelf, IDC_THEME_DEF_DESC_EDIT, EM_LIMITTEXT, MAX_PATH, NULL); SetWindowSubclass(GetDlgItem(_hSelf, IDC_THEME_STYLE_LIST_BOX), procStylesListBox, NULL, NULL); loadBitmap(_hSelf, IDC_THEME_DEF_DOWN_BUTTON, IDB_VIZ_MOVE_DOWN_BITMAP); addTooltip(_hSelf, IDC_THEME_DEF_DOWN_BUTTON, L"", THEME_DEF_MOVE_DOWN, FALSE); loadBitmap(_hSelf, IDC_THEME_DEF_UP_BUTTON, IDB_VIZ_MOVE_UP_BITMAP); addTooltip(_hSelf, IDC_THEME_DEF_UP_BUTTON, L"", THEME_DEF_MOVE_UP, FALSE); loadBitmap(_hSelf, IDC_THEME_STYLE_DOWN_BUTTON, IDB_VIZ_MOVE_DOWN_BITMAP); addTooltip(_hSelf, IDC_THEME_STYLE_DOWN_BUTTON, L"", THEME_STYLE_MOVE_DOWN, FALSE); loadBitmap(_hSelf, IDC_THEME_STYLE_UP_BUTTON, IDB_VIZ_MOVE_UP_BITMAP); addTooltip(_hSelf, IDC_THEME_STYLE_UP_BUTTON, L"", THEME_STYLE_MOVE_UP, FALSE); loadBitmap(_hSelf, IDC_THEME_DEF_INFO_BUTTON, IDB_VIZ_INFO_BITMAP); addTooltip(_hSelf, IDC_THEME_DEF_INFO_BUTTON, L"", VIZ_PANEL_INFO_TIP, FALSE); if constexpr(_gLanguage != LANG_ENGLISH) localize(); goToCenter(); SendMessage(_hParent, NPPM_DMMSHOW, 0, (LPARAM)_hSelf); SetFocus(_hSelf); loadConfigInfo(); fillThemes(); } void ThemeDialog::display(bool toShow) { StaticDialog::display(toShow); if (!toShow) { if (_eximDlg.isCreated() && _eximDlg.isVisible()) _eximDlg.display(FALSE); } } void ThemeDialog::refreshDarkMode() { NPPDM_AutoThemeChildControls(_hSelf); redraw(); if (_eximDlg.isCreated()) _eximDlg.refreshDarkMode(); } INT_PTR CALLBACK ThemeDialog::run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: switch LOWORD(wParam) { case IDC_THEME_DEF_LIST_BOX: switch HIWORD(wParam) { case LBN_SELCHANGE: onThemeSelect(); break; } break; case IDC_THEME_DEF_DOWN_BUTTON: moveThemeType(MOVE_DOWN); break; case IDC_THEME_DEF_UP_BUTTON: moveThemeType(MOVE_UP); break; case IDC_THEME_DEF_DESC_EDIT: switch HIWORD(wParam) { case EN_CHANGE: if (!loadingEdits) { cleanThemeVals = FALSE; enableThemeSelection(); } break; } break; case IDC_THEME_DEF_ACCEPT_BTN: case IDC_THEME_DEF_RESET_BTN: themeEditAccept(LOWORD(wParam) == IDC_THEME_DEF_ACCEPT_BTN); break; case IDC_THEME_DEF_NEW_BTN: themeEditNew(); break; case IDC_THEME_DEF_CLONE_BTN: themeEditClone(); break; case IDC_THEME_DEF_DEL_BTN: themeEditDelete(); break; case IDC_THEME_STYLE_LIST_BOX: switch HIWORD(wParam) { case LBN_SELCHANGE: onStyleSelect(); if (swatchTopIndex != static_cast<int>(SendDlgItemMessage(_hSelf, IDC_THEME_STYLE_LIST_BOX, LB_GETTOPINDEX, NULL, NULL))) initPreviewSwatch(); break; } break; case IDC_THEME_STYLE_DOWN_BUTTON: moveStyleType(MOVE_DOWN); break; case IDC_THEME_STYLE_UP_BUTTON: moveStyleType(MOVE_UP); break; case IDC_THEME_STYLE_NEW_BTN: styleEditNew(FALSE); break; case IDC_THEME_STYLE_CLONE_BTN: styleEditNew(TRUE); break; case IDC_THEME_STYLE_DEL_BTN: styleEditDelete(); break; case IDC_STYLE_DEF_BACK_EDIT: case IDC_STYLE_DEF_FORE_EDIT: switch (HIWORD(wParam)) { case EN_CHANGE: bool back = (LOWORD(wParam) == IDC_STYLE_DEF_BACK_EDIT); setStyleDefColor(FALSE, getStyleDefColor(back), back); if (!loadingEdits) { cleanStyleDefs = FALSE; enableStyleSelection(); } break; } break; case IDC_STYLE_DEF_BACKCOLOR: chooseStyleDefColor(TRUE); break; case IDC_STYLE_DEF_FORECOLOR: chooseStyleDefColor(FALSE); break; case IDC_STYLE_DEF_BOLD: case IDC_STYLE_DEF_ITALICS: setOutputFontStyle(); cleanStyleDefs = FALSE; enableStyleSelection(); break; case IDC_STYLE_DEF_PREVIEW_BOX: setPangram(); break; case IDC_THEME_STYLE_DEF_ACCEPT_BTN: styleDefsAccept(); break; case IDC_THEME_STYLE_DEF_RESET_BTN: fillStyleDefs(); break; case IDC_THEME_DEF_INFO_BUTTON: ShellExecute(NULL, L"open", THEME_DEF_INFO_README, NULL, NULL, SW_SHOW); break; case IDC_THEME_DEF_SAVE_CONFIG_BTN: SetCursor(LoadCursor(NULL, IDC_WAIT)); saveConfigInfo(); SetCursor(LoadCursor(NULL, IDC_ARROW)); return TRUE; case IDC_THEME_DEF_RESET_CONFIG_BTN: if (!promptDiscardChangesNo()) { themeFile = L""; loadConfigInfo(); fillThemes(); } break; case IDC_THEME_DEF_BACKUP_LOAD_BTN: if (!promptDiscardChangesNo()) { wstring backupThemeFile; if (_configIO.queryConfigFileName(_hSelf, TRUE, TRUE, backupThemeFile)) { if (_configIO.fixIfNotUTF8File(backupThemeFile)) { themeFile = backupThemeFile; loadConfigInfo(); fillThemes(); cleanConfigFile = FALSE; enableThemeSelection(); } } } break; case IDC_THEME_DEF_BACKUP_VIEW_BTN: _configIO.viewBackupFolder(); break; case IDC_THEME_DEF_EXTRACT_BTN: showEximDialog(TRUE); break; case IDC_THEME_DEF_APPEND_BTN: showEximDialog(FALSE); break; case IDCANCEL: case IDCLOSE: if (promptDiscardChangesNo()) return TRUE; display(FALSE); return TRUE; default: if (cleanStyleDefs) processSwatchClick(LOWORD(wParam)); } break; case WM_CTLCOLORSTATIC: if (styleDefColor) { INT_PTR ptr = colorStaticControl(wParam, lParam); if (ptr != NULL) return ptr; ptr = colorPreviewSwatch(wParam, lParam); if (ptr != NULL) return ptr; } if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLORDLG: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLOREDIT: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorSofter(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLORLISTBOX: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorListbox(wParam, lParam); } break; case WM_PRINTCLIENT: if (NPPDM_IsEnabled()) return TRUE; break; case WM_INITDIALOG: NPPDM_AutoSubclassAndThemeChildControls(_hSelf); break; case FWVIZMSG_APPEND_EXIM_DATA: appendThemeConfigs(reinterpret_cast<LPCWSTR>(lParam)); break; } return FALSE; } void ThemeDialog::localize() { SetWindowText(_hSelf, THEME_DIALOG_TITLE); SetDlgItemText(_hSelf, IDC_THEME_DEF_GROUP_BOX, THEME_DEF_GROUP_BOX); SetDlgItemText(_hSelf, IDC_THEME_DEF_DESC_LABEL, THEME_DEF_DESC_LABEL); SetDlgItemText(_hSelf, IDC_THEME_DEF_ACCEPT_BTN, THEME_DEF_ACCEPT_BTN); SetDlgItemText(_hSelf, IDC_THEME_DEF_RESET_BTN, THEME_DEF_RESET_BTN); SetDlgItemText(_hSelf, IDC_THEME_DEF_NEW_BTN, THEME_DEF_NEW_BTN); SetDlgItemText(_hSelf, IDC_THEME_DEF_CLONE_BTN, THEME_DEF_CLONE_BTN); SetDlgItemText(_hSelf, IDC_THEME_DEF_DEL_BTN, THEME_DEF_DEL_BTN); SetDlgItemText(_hSelf, IDC_THEME_STYLE_GROUP_BOX, THEME_STYLE_GROUP_BOX); SetDlgItemText(_hSelf, IDC_THEME_STYLE_NEW_BTN, THEME_STYLE_NEW_BTN); SetDlgItemText(_hSelf, IDC_THEME_STYLE_CLONE_BTN, THEME_STYLE_CLONE_BTN); SetDlgItemText(_hSelf, IDC_THEME_STYLE_DEL_BTN, THEME_STYLE_DEL_BTN); SetDlgItemText(_hSelf, IDC_THEME_STYLE_DEF_ACCEPT_BTN, THEME_STYLE_DEF_ACCEPT_BTN); SetDlgItemText(_hSelf, IDC_THEME_STYLE_DEF_RESET_BTN, THEME_STYLE_DEF_RESET_BTN); SetDlgItemText(_hSelf, IDC_THEME_DEF_SAVE_CONFIG_BTN, THEME_DIALOG_SAVE_BTN); SetDlgItemText(_hSelf, IDC_THEME_DEF_RESET_CONFIG_BTN, THEME_DIALOG_RESET_BTN); SetDlgItemText(_hSelf, IDC_THEME_DEF_BACKUP_LOAD_BTN, THEME_DIALOG_BKUP_LOAD_BTN); SetDlgItemText(_hSelf, IDC_THEME_DEF_BACKUP_VIEW_BTN, THEME_DIALOG_BKUP_VIEW_BTN); SetDlgItemText(_hSelf, IDC_THEME_DEF_EXTRACT_BTN, THEME_DIALOG_EXTRACT_BTN); SetDlgItemText(_hSelf, IDC_THEME_DEF_APPEND_BTN, THEME_DIALOG_APPEND_BTN); SetDlgItemText(_hSelf, IDCLOSE, THEME_DIALOG_CLOSE_BTN); StyleDefComponent::localize(); } void ThemeDialog::indicateCleanStatus() { if (cleanConfigFile) { SetDlgItemText(_hSelf, IDC_THEME_DEF_SAVE_CONFIG_BTN, THEME_DIALOG_SAVE_BTN); Utils::setFontRegular(_hSelf, IDC_THEME_DEF_SAVE_CONFIG_BTN); } else { SetDlgItemText(_hSelf, IDC_THEME_DEF_SAVE_CONFIG_BTN, (wstring(THEME_DIALOG_SAVE_BTN) + L"*").c_str()); Utils::setFontBold(_hSelf, IDC_THEME_DEF_SAVE_CONFIG_BTN); } if (cleanThemeVals) { SetDlgItemText(_hSelf, IDC_THEME_DEF_ACCEPT_BTN, THEME_DEF_ACCEPT_BTN); Utils::setFontRegular(_hSelf, IDC_THEME_DEF_ACCEPT_BTN); } else { SetDlgItemText(_hSelf, IDC_THEME_DEF_ACCEPT_BTN, (wstring(THEME_DEF_ACCEPT_BTN) + L"*").c_str()); Utils::setFontBold(_hSelf, IDC_THEME_DEF_ACCEPT_BTN); } if (cleanStyleDefs) { SetDlgItemText(_hSelf, IDC_THEME_STYLE_DEF_ACCEPT_BTN, THEME_STYLE_DEF_ACCEPT_BTN); Utils::setFontRegular(_hSelf, IDC_THEME_STYLE_DEF_ACCEPT_BTN); } else { SetDlgItemText(_hSelf, IDC_THEME_STYLE_DEF_ACCEPT_BTN, (wstring(THEME_STYLE_DEF_ACCEPT_BTN) + L"*").c_str()); Utils::setFontBold(_hSelf, IDC_THEME_STYLE_DEF_ACCEPT_BTN); } } int ThemeDialog::loadConfigInfo() { vector<wstring> themesList; int themesCount{ _configIO.getThemesList(themesList, themeFile) }; vThemeTypes.clear(); vThemeTypes.resize(themesCount); for (int i{}; i < themesCount; ++i) { wstring& themeType = themesList[i]; loadThemeInfo(i, themeType, themeFile); } return static_cast<int>(vThemeTypes.size()); } int ThemeDialog::loadThemeInfo(int vIndex, const wstring& themeType, const wstring& sThemeFile) { ThemeType& TT = vThemeTypes[vIndex]; TT.label = themeType; _configIO.getFullStyle(themeType, "EOL", TT.eolStyle, sThemeFile); char buf[10]; int styleCount{ Utils::StringtoInt(_configIO.getStyleValue(themeType, "Count", sThemeFile)) }; TT.vStyleInfo.clear(); TT.vStyleInfo.resize(styleCount); for (int i{}; i < styleCount; ++i) { snprintf(buf, 8, "BFBI_%02i", i); _configIO.getFullStyle(themeType, buf, TT.vStyleInfo[i], sThemeFile); } return styleCount; } void ThemeDialog::fillThemes() { SendMessage(hThemesLB, LB_RESETCONTENT, NULL, NULL); for (const ThemeType TT : vThemeTypes) { SendMessage(hThemesLB, LB_ADDSTRING, NULL, (LPARAM)TT.label.c_str()); } if (vThemeTypes.size() > 0) SendMessage(hThemesLB, LB_SETCURSEL, 0, NULL); cleanConfigFile = TRUE; cleanThemeVals = TRUE; onThemeSelect(); } int ThemeDialog::getCurrentThemeIndex() const { int idxTT; idxTT = static_cast<int>(SendMessage(hThemesLB, LB_GETCURSEL, NULL, NULL)); if (idxTT == LB_ERR) return LB_ERR; return idxTT; } int ThemeDialog::getCurrentStyleIndex() const { int idxStyle; idxStyle = static_cast<int>(SendMessage(hStylesLB, LB_GETCURSEL, NULL, NULL)); if (idxStyle == LB_ERR) return LB_ERR; return idxStyle; } bool ThemeDialog::getCurrentThemeInfo(ThemeType*& themeInfo) { int idxTT{ getCurrentThemeIndex() }; if (idxTT == LB_ERR) return FALSE; themeInfo = &vThemeTypes[idxTT]; return TRUE; } ThemeDialog::ThemeType ThemeDialog::getNewTheme() { ThemeType newTheme; newTheme.label = L""; newTheme.vStyleInfo = vector<StyleInfo>{ getNewStyle() }; return newTheme; } wstring ThemeDialog::getStyleConfig(int idx, StyleInfo& style) { wchar_t styleDef[25]; swprintf(styleDef, 25, L"BFBI_%02i=%06X %06X ", idx, style.backColor, style.foreColor); return wstring{ styleDef } + (style.bold ? L"1" : L"0") + (style.italics ? L"1" : L"0"); } void ThemeDialog::getThemeConfig(size_t idxTh, bool cr_lf, wstring& themeLabel, wstring& ttConfig) { wstring new_line = cr_lf ? L"\r\n" : L"\n"; ThemeType& TT = vThemeTypes[idxTh]; size_t styleCount = (TT.vStyleInfo.size() > 99) ? 99 : TT.vStyleInfo.size(); themeLabel = regex_replace(themeLabel, wregex(L"(|,|=|\\[|\\])"), L" "); themeLabel = regex_replace(TT.label, wregex(L"(^( )+)|(( )+$)"), L""); themeLabel = regex_replace(themeLabel, wregex(L"( ){2,}"), L" ").substr(0, 50); ttConfig = L"[" + themeLabel + L"]" + new_line + L"Count=" + to_wstring(styleCount) + new_line + L"EOL=" + getStyleConfig(0, TT.eolStyle).substr(8) + new_line; for (size_t j{}; j < styleCount; ++j) { ttConfig += getStyleConfig(static_cast<int>(j), TT.vStyleInfo[j]) + new_line; } } bool ThemeDialog::getCurrentStyleInfo(StyleInfo*& recInfo) { int idxTT{ getCurrentThemeIndex() }; if (idxTT == LB_ERR) return FALSE; int idxStyle{ getCurrentStyleIndex() }; if (idxStyle == LB_ERR) return FALSE; recInfo = (idxStyle < static_cast<int>(vThemeTypes[idxTT].vStyleInfo.size())) ? &vThemeTypes[idxTT].vStyleInfo[idxStyle] : &vThemeTypes[idxTT].eolStyle; return TRUE; } StyleInfo ThemeDialog::getNewStyle() { StyleInfo newStyle{}; newStyle.backColor = static_cast<int>(nppMessage(NPPM_GETEDITORDEFAULTBACKGROUNDCOLOR)); newStyle.foreColor = static_cast<int>(nppMessage(NPPM_GETEDITORDEFAULTFOREGROUNDCOLOR)); newStyle.bold = 0; newStyle.italics = 0; return newStyle; } void ThemeDialog::onThemeSelect() { ThemeType* themeInfo; if (!getCurrentThemeInfo(themeInfo)) { ThemeType newTheme{ getNewTheme() }; themeInfo = &newTheme; } onThemeSelectFill(themeInfo); enableMoveThemeButtons(); fillStyles(); } void ThemeDialog::onThemeSelectFill(ThemeType* themeInfo) { loadingEdits = TRUE; SetDlgItemText(_hSelf, IDC_THEME_DEF_DESC_EDIT, themeInfo->label.c_str()); loadingEdits = FALSE; } void ThemeDialog::enableMoveThemeButtons() { int idxFT{ getCurrentThemeIndex() }; if (idxFT == LB_ERR) return; EnableWindow(GetDlgItem(_hSelf, IDC_THEME_DEF_DOWN_BUTTON), (idxFT < static_cast<int>(vThemeTypes.size()) - 1)); EnableWindow(GetDlgItem(_hSelf, IDC_THEME_DEF_UP_BUTTON), (idxFT > 0)); } void ThemeDialog::enableThemeSelection() { bool enable{ cleanThemeVals && cleanStyleDefs }; bool themesExist{ SendMessage(hThemesLB, LB_GETCOUNT, 0, 0) > 0 }; ShowWindow(GetDlgItem(_hSelf, IDC_THEME_DEF_NEW_BTN), cleanThemeVals ? SW_SHOW : SW_HIDE); ShowWindow(GetDlgItem(_hSelf, IDC_THEME_DEF_RESET_BTN), cleanThemeVals ? SW_HIDE : SW_SHOW); EnableWindow(hThemesLB, enable); EnableWindow(GetDlgItem(_hSelf, IDC_THEME_DEF_NEW_BTN), enable); EnableWindow(GetDlgItem(_hSelf, IDC_THEME_DEF_CLONE_BTN), enable); EnableWindow(GetDlgItem(_hSelf, IDC_THEME_DEF_DEL_BTN), themesExist); EnableWindow(GetDlgItem(_hSelf, IDC_THEME_DEF_EXTRACT_BTN), enable); EnableWindow(GetDlgItem(_hSelf, IDC_THEME_DEF_APPEND_BTN), enable); if (enable) { enableMoveThemeButtons(); } else { EnableWindow(GetDlgItem(_hSelf, IDC_THEME_DEF_DOWN_BUTTON), FALSE); EnableWindow(GetDlgItem(_hSelf, IDC_THEME_DEF_UP_BUTTON), FALSE); } indicateCleanStatus(); } int ThemeDialog::moveThemeType(move_dir dir) { const int idxTheme{ getCurrentThemeIndex() }; if (idxTheme == LB_ERR) return LB_ERR; switch (dir) { case MOVE_DOWN: if (idxTheme >= static_cast<int>(vThemeTypes.size()) - 1) return LB_ERR; break; case MOVE_UP: if (idxTheme == 0) return LB_ERR; break; default: return LB_ERR; } ThemeType currType = vThemeTypes[idxTheme]; ThemeType& adjType = vThemeTypes[idxTheme + dir]; vThemeTypes[idxTheme] = adjType; vThemeTypes[idxTheme + dir] = currType; SendMessage(hThemesLB, LB_DELETESTRING, idxTheme, NULL); SendMessage(hThemesLB, LB_INSERTSTRING, (idxTheme + dir), (LPARAM)vThemeTypes[idxTheme + dir].label.c_str()); SendMessage(hThemesLB, LB_SETCURSEL, idxTheme + dir, NULL); cleanConfigFile = FALSE; indicateCleanStatus(); enableMoveThemeButtons(); return idxTheme + dir; } void ThemeDialog::fillStyles() { ThemeType* themeInfo; if (!getCurrentThemeInfo(themeInfo)) { ThemeType newTheme{ getNewTheme() }; themeInfo = &newTheme; } wchar_t styleLabel[10]; vector <StyleInfo>& styleList{ themeInfo->vStyleInfo }; int styleCount{ static_cast<int>(styleList.size()) }; SendMessage(hStylesLB, LB_RESETCONTENT, NULL, NULL); for (int i{}; i < styleCount; ++i) { swprintf(styleLabel, 10, L"Style #%02i", i); SendMessage(hStylesLB, LB_ADDSTRING, NULL, (LPARAM)styleLabel); } SendMessage(hStylesLB, LB_ADDSTRING, NULL, (LPARAM)L"EOL Marker Style"); SendMessage(hStylesLB, LB_SETCURSEL, 0, NULL); onStyleSelect(); initPreviewSwatch(); } void ThemeDialog::onStyleSelect() { int idxTheme{ getCurrentThemeIndex() }; if (idxTheme == LB_ERR) return; int idxStyle{ getCurrentStyleIndex() }; if (idxStyle == LB_ERR) return; EnableWindow(GetDlgItem(_hSelf, IDC_THEME_STYLE_DEL_BTN), (idxStyle < static_cast<int>(vThemeTypes[idxTheme].vStyleInfo.size()))); enableMoveStyleButtons(); fillStyleDefs(); } void ThemeDialog::enableMoveStyleButtons() { int idxTheme{ getCurrentThemeIndex() }; if (idxTheme == LB_ERR) return; int idxStyle{ getCurrentStyleIndex() }; if (idxStyle == LB_ERR) return; int styleCount{ static_cast<int>(vThemeTypes[idxTheme].vStyleInfo.size()) }; EnableWindow(GetDlgItem(_hSelf, IDC_THEME_STYLE_DOWN_BUTTON), (idxStyle < styleCount - 1)); EnableWindow(GetDlgItem(_hSelf, IDC_THEME_STYLE_UP_BUTTON), (idxStyle > 0 && idxStyle < styleCount)); } void ThemeDialog::enableStyleSelection() { EnableWindow(GetDlgItem(_hSelf, IDC_THEME_STYLE_LIST_BOX), cleanStyleDefs); EnableWindow(GetDlgItem(_hSelf, IDC_THEME_STYLE_CLONE_BTN), cleanStyleDefs); EnableWindow(GetDlgItem(_hSelf, IDC_THEME_STYLE_NEW_BTN), cleanStyleDefs); if (cleanStyleDefs) { enableMoveStyleButtons(); } else { EnableWindow(GetDlgItem(_hSelf, IDC_THEME_STYLE_DOWN_BUTTON), cleanStyleDefs); EnableWindow(GetDlgItem(_hSelf, IDC_THEME_STYLE_UP_BUTTON), cleanStyleDefs); } enableThemeSelection(); } int ThemeDialog::moveStyleType(move_dir dir) { const int idxTheme{ getCurrentThemeIndex() }; if (idxTheme == LB_ERR) return LB_ERR; const int idxStyle{ getCurrentStyleIndex() }; if (idxStyle == LB_ERR) return LB_ERR; vector<StyleInfo>& styleList = vThemeTypes[idxTheme].vStyleInfo; switch (dir) { case MOVE_DOWN: if (idxStyle >= static_cast<int>(styleList.size()) - 1) return LB_ERR; break; case MOVE_UP: if (idxStyle == 0) return LB_ERR; break; default: return LB_ERR; } StyleInfo currType = styleList[idxStyle]; StyleInfo& adjType = styleList[idxStyle + dir]; styleList[idxStyle] = adjType; styleList[idxStyle + dir] = currType; TCHAR itemText[100]{}; SendMessage(hStylesLB, LB_GETTEXT, idxStyle, (LPARAM)itemText); SendMessage(hStylesLB, LB_DELETESTRING, idxStyle, NULL); SendMessage(hStylesLB, LB_INSERTSTRING, (idxStyle + dir), (LPARAM)itemText); SendMessage(hStylesLB, LB_SETCURSEL, idxStyle + dir, NULL); cleanConfigFile = FALSE; indicateCleanStatus(); enableMoveStyleButtons(); initPreviewSwatch(); return idxStyle + dir; } void ThemeDialog::setStyleDefColor(bool setEdit, int color, bool back) { loadingEdits = TRUE; StyleDefComponent::setStyleDefColor(setEdit, color, back); loadingEdits = FALSE; } void ThemeDialog::fillStyleDefs() { StyleInfo* style; if (!getCurrentStyleInfo(style)) { StyleInfo newStyle{ getNewStyle() }; style = &newStyle; } StyleDefComponent::fillStyleDefs(*style); enableStyleSelection(); } void ThemeDialog::styleDefsAccept() { if (cleanStyleDefs) return; StyleInfo* style; if (!getCurrentStyleInfo(style)) return; int idxStyle = getCurrentStyleIndex(); style->backColor = getStyleDefColor(TRUE); style->foreColor = getStyleDefColor(FALSE); style->bold = (IsDlgButtonChecked(_hSelf, IDC_STYLE_DEF_BOLD) == BST_CHECKED); style->italics = (IsDlgButtonChecked(_hSelf, IDC_STYLE_DEF_ITALICS) == BST_CHECKED); initPreviewSwatch(idxStyle, idxStyle); cleanConfigFile = FALSE; cleanStyleDefs = TRUE; enableStyleSelection(); } INT_PTR ThemeDialog::colorPreviewSwatch(WPARAM wParam, LPARAM lParam) { const int idxTheme{ getCurrentThemeIndex() }; if (idxTheme == LB_ERR) return NULL; ThemeType& TT = vThemeTypes[idxTheme]; int topIdx = static_cast<int>(SendDlgItemMessage(_hSelf, IDC_THEME_STYLE_LIST_BOX, LB_GETTOPINDEX, NULL, NULL)); int styleCount = static_cast<int>(TT.vStyleInfo.size()); int ctrlIDOffset, brushColor; HDC hdc = (HDC)wParam; DWORD ctrlID = GetDlgCtrlID((HWND)lParam); if (hbr != NULL) DeleteObject(hbr); // Back color swatches ctrlIDOffset = static_cast<int>(ctrlID) - IDC_THEME_SWATCH_BACK_00; if (ctrlIDOffset >= 0 && ctrlIDOffset < SWATCH_ITEM_COUNT) { if (ctrlIDOffset + topIdx < styleCount) brushColor = Utils::intToRGB(TT.vStyleInfo[ctrlIDOffset + topIdx].backColor); else if (ctrlIDOffset + topIdx == styleCount) brushColor = Utils::intToRGB(TT.eolStyle.backColor); else return NULL; SetBkColor(hdc, brushColor); hbr = CreateSolidBrush(brushColor); return (INT_PTR)hbr; } // Fore color swatches ctrlIDOffset = static_cast<int>(ctrlID) - IDC_THEME_SWATCH_FORE_00; if (ctrlIDOffset >= 0 && ctrlIDOffset < SWATCH_ITEM_COUNT) { if (ctrlIDOffset + topIdx < styleCount) brushColor = Utils::intToRGB(TT.vStyleInfo[ctrlIDOffset + topIdx].foreColor); else if (ctrlIDOffset + topIdx == styleCount) brushColor = Utils::intToRGB(TT.eolStyle.foreColor); else return NULL; SetBkColor(hdc, brushColor); hbr = CreateSolidBrush(brushColor); return (INT_PTR)hbr; } return NULL; } void ThemeDialog::initPreviewSwatch(int idxStart, int idxEnd) { const int idxTheme{ getCurrentThemeIndex() }; if (idxTheme == LB_ERR) return; ThemeType& TT = vThemeTypes[idxTheme]; swatchTopIndex = static_cast<int>(SendDlgItemMessage(_hSelf, IDC_THEME_STYLE_LIST_BOX, LB_GETTOPINDEX, NULL, NULL)); int styleCount = static_cast<int>(TT.vStyleInfo.size()); for (int i{ idxStart }; i <= idxEnd; ++i) { ShowWindow(GetDlgItem(_hSelf, IDC_THEME_SWATCH_BACK_00 + i), (i + swatchTopIndex <= styleCount)); Utils::setFontRegular(_hSelf, IDC_THEME_SWATCH_BACK_00 + i); ShowWindow(GetDlgItem(_hSelf, IDC_THEME_SWATCH_FORE_00 + i), (i + swatchTopIndex <= styleCount)); Utils::setFontRegular(_hSelf, IDC_THEME_SWATCH_FORE_00 + i); } } void ThemeDialog::processSwatchClick(int ctrlID) { int topIdx = static_cast<int>(SendDlgItemMessage(_hSelf, IDC_THEME_STYLE_LIST_BOX, LB_GETTOPINDEX, NULL, NULL)); if (ctrlID >= IDC_THEME_SWATCH_BACK_00 && ctrlID <= IDC_THEME_SWATCH_BACK_00 + SWATCH_ITEM_COUNT) { SendDlgItemMessage(_hSelf, IDC_THEME_STYLE_LIST_BOX, LB_SETCURSEL, ctrlID - IDC_THEME_SWATCH_BACK_00 + topIdx, NULL); onStyleSelect(); } if (ctrlID >= IDC_THEME_SWATCH_FORE_00 && ctrlID <= IDC_THEME_SWATCH_FORE_00 + SWATCH_ITEM_COUNT) { SendDlgItemMessage(_hSelf, IDC_THEME_STYLE_LIST_BOX, LB_SETCURSEL, ctrlID - IDC_THEME_SWATCH_FORE_00 + topIdx, NULL); onStyleSelect(); } } void ThemeDialog::chooseStyleDefColor(bool back) { StyleInfo* style; if (!getCurrentStyleInfo(style)) return; StyleDefComponent::chooseStyleDefColor(back); cleanConfigFile = FALSE; enableStyleSelection(); } void ThemeDialog::styleEditNew(bool clone) { int idxFT{ getCurrentThemeIndex() }; if (idxFT == LB_ERR) return; int idxST{ getCurrentStyleIndex() }; if (clone && idxST == LB_ERR) return; StyleInfo newStyle{ getNewStyle() }; vector<StyleInfo>& styles = vThemeTypes[idxFT].vStyleInfo; int newIdx{ static_cast<int>(styles.size()) }; if (newIdx >= STYLE_ITEM_LIMIT) { TCHAR buf[100]; swprintf(buf, 100, THEME_STYLE_LIMIT_ERROR, STYLE_ITEM_LIMIT); MessageBox(_hSelf, buf, clone ? THEME_STYLE_CLONE_ACTION : THEME_STYLE_NEW_ACTION, MB_OK | MB_ICONSTOP); return; } wchar_t styleLabel[10]; swprintf(styleLabel, 10, L"Style #%02i", newIdx); if (clone) { newStyle.backColor = styles[idxST].backColor; newStyle.foreColor = styles[idxST].foreColor; newStyle.bold = styles[idxST].bold; newStyle.italics = styles[idxST].italics; } styles.push_back(newStyle); SendMessage(hStylesLB, LB_INSERTSTRING, newIdx, (LPARAM)styleLabel); SendMessage(hStylesLB, LB_SETCURSEL, newIdx, NULL); onStyleSelect(); initPreviewSwatch(); cleanConfigFile = FALSE; enableStyleSelection(); } int ThemeDialog::styleEditDelete() { int idxFT{ getCurrentThemeIndex() }; if (idxFT == LB_ERR) return LB_ERR; int idxRec{ getCurrentStyleIndex() }; if (idxRec == LB_ERR) return LB_ERR; vector<StyleInfo>& records = vThemeTypes[idxFT].vStyleInfo; records.erase(records.begin() + idxRec); int lastRec = static_cast<int>(records.size()) - 1; int moveTo = (idxRec <= lastRec - 1) ? idxRec : lastRec; SendMessage(hStylesLB, LB_DELETESTRING, idxRec, NULL); SendMessage(hStylesLB, LB_SETCURSEL, moveTo, NULL); cleanConfigFile = FALSE; onStyleSelect(); initPreviewSwatch(); return moveTo; } void ThemeDialog::themeEditAccept(bool accept) { if (cleanThemeVals) return; int idxFT{ getCurrentThemeIndex() }; if (idxFT == LB_ERR) return; ThemeType& fileInfo = vThemeTypes[idxFT]; if (accept) { wchar_t fileVal[MAX_PATH + 1]; GetDlgItemText(_hSelf, IDC_THEME_DEF_DESC_EDIT, fileVal, MAX_PATH + 1); fileInfo.label = fileVal; } else if (fileInfo.label.empty()) { themeEditDelete(); return; } else { onThemeSelectFill(&fileInfo); } SendMessage(hThemesLB, LB_DELETESTRING, idxFT, NULL); SendMessage(hThemesLB, LB_INSERTSTRING, idxFT, (LPARAM)fileInfo.label.c_str()); SendMessage(hThemesLB, LB_SETCURSEL, idxFT, NULL); cleanConfigFile = FALSE; cleanThemeVals = TRUE; enableThemeSelection(); } int ThemeDialog::appendThemeConfigs(const wstring& sThemeFile) { int sectionCount{}, validCount{}; vector<wstring> sectionList{}; sectionCount = _configIO.getConfigAllSectionsList(sectionList, sThemeFile); for (int i{}; i < sectionCount; ++i) { if (_configIO.getConfigInt(sectionList[i], "Count", 0, sThemeFile) > 0) { if (!checkThemeLimit(FALSE)) break; ThemeType newTheme{ getNewTheme() }; vThemeTypes.push_back(newTheme); loadThemeInfo(static_cast<int>(vThemeTypes.size() - 1), sectionList[i], sThemeFile); SendMessage(hThemesLB, LB_ADDSTRING, NULL, (LPARAM)sectionList[i].c_str()); ++validCount; } } SendMessage(hThemesLB, LB_SETCURSEL, (vThemeTypes.size() - 1), NULL); onThemeSelect(); cleanConfigFile = FALSE; enableThemeSelection(); return validCount; } void ThemeDialog::themeEditNew() { if (!checkThemeLimit(FALSE)) return; ThemeType newFile{ getNewTheme() }; vThemeTypes.push_back(newFile); size_t moveTo = vThemeTypes.size() - 1; SendMessage(hThemesLB, LB_ADDSTRING, NULL, (LPARAM)newFile.label.c_str()); SendMessage(hThemesLB, LB_SETCURSEL, moveTo, NULL); onThemeSelect(); cleanConfigFile = FALSE; cleanThemeVals = FALSE; enableThemeSelection(); } void ThemeDialog::themeEditClone() { if (!checkThemeLimit(TRUE)) return; int idxTT{ getCurrentThemeIndex() }; if (idxTT == LB_ERR) return; ThemeType& TT = vThemeTypes[idxTT]; ThemeType NT{}; NT.label = TT.label + L"_clone"; size_t recCount = TT.vStyleInfo.size(); NT.vStyleInfo.resize(recCount); for (size_t i{}; i < recCount; ++i) { NT.vStyleInfo[i].backColor = TT.vStyleInfo[i].backColor; NT.vStyleInfo[i].foreColor = TT.vStyleInfo[i].foreColor; NT.vStyleInfo[i].bold = TT.vStyleInfo[i].bold; NT.vStyleInfo[i].italics = TT.vStyleInfo[i].italics; } vThemeTypes.push_back(NT); SendMessage(hThemesLB, LB_ADDSTRING, NULL, (LPARAM)NT.label.c_str()); SendMessage(hThemesLB, LB_SETCURSEL, (vThemeTypes.size() - 1), NULL); onThemeSelect(); cleanConfigFile = FALSE; enableThemeSelection(); } int ThemeDialog::themeEditDelete() { int idxFT{ getCurrentThemeIndex() }; if (idxFT == LB_ERR) return LB_ERR; vThemeTypes.erase(vThemeTypes.begin() + idxFT); int lastFile = static_cast<int>(vThemeTypes.size()) - 1; int moveTo = (idxFT <= lastFile - 1) ? idxFT : lastFile; SendMessage(hThemesLB, LB_DELETESTRING, idxFT, NULL); SendMessage(hThemesLB, LB_SETCURSEL, moveTo, NULL); cleanConfigFile = FALSE; cleanThemeVals = TRUE; onThemeSelect(); return moveTo; } bool ThemeDialog::checkThemeLimit(bool clone) { if (vThemeTypes.size() < THEME_ITEM_LIMIT) return TRUE; TCHAR buf[100]; swprintf(buf, 100, THEME_DEF_LIMIT_ERROR, THEME_ITEM_LIMIT); MessageBox(_hSelf, buf, clone ? THEME_DEF_CLONE_ACTION : THEME_DEF_NEW_ACTION, MB_OK | MB_ICONSTOP); return FALSE; } bool ThemeDialog::promptDiscardChangesNo() { if (!(cleanConfigFile && cleanThemeVals && cleanStyleDefs)) { if (MessageBox(_hSelf, THEME_DISCARD_CHANGES, THEME_DIALOG_TITLE, MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) == IDNO) return TRUE; } return FALSE; } void ThemeDialog::saveConfigInfo() { if (!cleanStyleDefs) styleDefsAccept(); if (!cleanThemeVals) themeEditAccept(); size_t themeCount; wstring fileData{}, themes{}, ttCode{}, ttConfig{}; themeCount = (vThemeTypes.size() > 999) ? 999 : vThemeTypes.size(); for (size_t i{}; i < themeCount; ++i) { getThemeConfig(i, TRUE, ttCode, ttConfig); themes += (i == 0 ? L"" : L",") + ttCode; fileData += ttConfig + L"\r\n"; } fileData = L"[Base]\r\nThemes=" + themes + L"\r\n\r\n" + fileData; _configIO.backupConfigFile(_configIO.getConfigFile(_configIO.CONFIG_THEMES)); _configIO.saveConfigFile(fileData, _configIO.getConfigFile(_configIO.CONFIG_THEMES)); cleanConfigFile = TRUE; indicateCleanStatus(); RefreshVisualizerPanel(); } void ThemeDialog::showEximDialog(bool bExtract) { _eximDlg.doDialog((HINSTANCE)_gModule); _eximDlg.initDialog(_hSelf, EximFileTypeDialog::THEMES_DLG, bExtract); if (bExtract) { int idxTT{ getCurrentThemeIndex() }; if (idxTT == LB_ERR) return; wstring ttCode{}, ttConfig{}; getThemeConfig(idxTT, TRUE, ttCode, ttConfig); _eximDlg.setFileTypeData(ttConfig); } } LRESULT CALLBACK procStylesListBox(HWND hwnd, UINT messageId, WPARAM wParam, LPARAM lParam, UINT_PTR, DWORD_PTR) { switch (messageId) { case WM_VSCROLL: _themeDlg.initPreviewSwatch(); break; } return DefSubclassProc(hwnd, messageId, wParam, lParam); }
32,175
C++
.cpp
815
33.781595
119
0.683938
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,111
FoldStructDialog.cpp
shriprem_FWDataViz/src/Dialogs/FoldStructDialog.cpp
#include "FoldStructDialog.h" #include "EximFileTypeDialog.h" #pragma comment(lib, "comctl32.lib") extern HINSTANCE _gModule; extern EximFileTypeDialog _eximDlg; void FoldStructDialog::doDialog(HINSTANCE hInst) { if (!isCreated()) { Window::init(hInst, nppData._nppHandle); create(IDD_FOLD_STRUCT_DEFINER_DIALOG); } hFoldStructs = GetDlgItem(_hSelf, IDC_FOLD_DEF_FILE_LIST_BOX); hFTList = GetDlgItem(_hSelf, IDC_FOLD_DEF_FILE_TYPE_LIST); hFoldBlocks = GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_LIST_BOX); hHdrRTList = GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_TYPE_LIST); hImplRecs = GetDlgItem(_hSelf, IDC_FOLD_IMPLICIT_TRMNTRS_LIST); hExplRecs = GetDlgItem(_hSelf, IDC_FOLD_EXPLICIT_TRMNTRS_LIST); hExplRTList = GetDlgItem(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_LIST); using Utils::addTooltip; using Utils::loadBitmap; loadBitmap(_hSelf, IDC_FOLD_DEF_FILE_DOWN_BUTTON, IDB_VIZ_MOVE_DOWN_BITMAP); addTooltip(_hSelf, IDC_FOLD_DEF_FILE_DOWN_BUTTON, L"", FOLD_DEF_FILE_MOVE_DOWN, FALSE); loadBitmap(_hSelf, IDC_FOLD_DEF_FILE_UP_BUTTON, IDB_VIZ_MOVE_UP_BITMAP); addTooltip(_hSelf, IDC_FOLD_DEF_FILE_UP_BUTTON, L"", FOLD_DEF_FILE_MOVE_UP, FALSE); loadBitmap(_hSelf, IDC_FOLD_DEF_HDR_REC_DOWN_BTN, IDB_VIZ_MOVE_DOWN_BITMAP); addTooltip(_hSelf, IDC_FOLD_DEF_HDR_REC_DOWN_BTN, L"", FOLD_DEF_HDR_REC_MOVE_DOWN, FALSE); loadBitmap(_hSelf, IDC_FOLD_DEF_HDR_REC_UP_BTN, IDB_VIZ_MOVE_UP_BITMAP); addTooltip(_hSelf, IDC_FOLD_DEF_HDR_REC_UP_BTN, L"", FOLD_DEF_HDR_REC_MOVE_UP, FALSE); loadBitmap(_hSelf, IDC_FOLD_DEF_INFO_BUTTON, IDB_VIZ_INFO_BITMAP); addTooltip(_hSelf, IDC_FOLD_DEF_INFO_BUTTON, L"", VIZ_PANEL_INFO_TIP, FALSE); if constexpr(_gLanguage != LANG_ENGLISH) localize(); goToCenter(); SendMessage(_hParent, NPPM_DMMSHOW, 0, (LPARAM)_hSelf); loadFileTypesList(); loadStructsInfo(); fillFoldStructs(); } void FoldStructDialog::refreshDarkMode() { NPPDM_AutoThemeChildControls(_hSelf); redraw(); if (_eximDlg.isCreated()) _eximDlg.refreshDarkMode(); } INT_PTR CALLBACK FoldStructDialog::run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: switch LOWORD(wParam) { case IDC_FOLD_DEF_FILE_LIST_BOX: switch HIWORD(wParam) { case LBN_SELCHANGE: onFoldStructSelect(); break; } break; case IDC_FOLD_DEF_FILE_DOWN_BUTTON: moveStructType(MOVE_DOWN); break; case IDC_FOLD_DEF_FILE_UP_BUTTON: moveStructType(MOVE_UP); break; case IDC_FOLD_DEF_FILE_TYPE_LIST: case IDC_FOLD_DEF_AUTO_FOLD_APPLY: switch HIWORD(wParam) { case BN_CLICKED: case CBN_SELCHANGE: if (!loadingEdits) { cleanStructVals = FALSE; enableStructSelection(); } break; } break; case IDC_FOLD_DEF_FILE_ACCEPT_BTN: case IDC_FOLD_DEF_FILE_RESET_BTN: structEditAccept(LOWORD(wParam) == IDC_FOLD_DEF_FILE_ACCEPT_BTN); break; case IDC_FOLD_DEF_FILE_NEW_BTN: structEditNew(); break; case IDC_FOLD_DEF_FILE_CLONE_BTN: structEditClone(); break; case IDC_FOLD_DEF_FILE_DEL_BTN: structEditDelete(); break; case IDC_FOLD_DEF_HDR_REC_LIST_BOX: switch HIWORD(wParam) { case LBN_SELCHANGE: onFoldBlockSelect(); break; } break; case IDC_FOLD_DEF_HDR_REC_DOWN_BTN: moveBlockType(MOVE_DOWN); break; case IDC_FOLD_DEF_HDR_REC_UP_BTN: moveBlockType(MOVE_UP); break; case IDC_FOLD_DEF_HDR_REC_TYPE_LIST: switch HIWORD(wParam) { case CBN_SELCHANGE: if (!loadingEdits) { cleanBlockVals = FALSE; enableBlockSelection(); } break; } break; case IDC_FOLD_DEF_HDR_PRIORITY_EDIT: case IDC_FOLD_DEF_HDR_REC_RECURSIVE: switch HIWORD(wParam) { case BN_CLICKED: case EN_CHANGE: if (!loadingEdits) { cleanBlockVals = FALSE; fillImplicitEndRecs(); enableBlockSelection(); } break; } break; case IDC_FOLD_DEF_HDR_REC_ACCEPT_BTN: case IDC_FOLD_DEF_HDR_REC_RESET_BTN: blockEditAccept(LOWORD(wParam) == IDC_FOLD_DEF_HDR_REC_ACCEPT_BTN); fillImplicitEndRecs(); break; case IDC_FOLD_DEF_HDR_REC_NEW_BTN: blockEditNew(FALSE); break; case IDC_FOLD_DEF_HDR_REC_CLONE_BTN: blockEditNew(TRUE); break; case IDC_FOLD_DEF_HDR_REC_DEL_BTN: blockEditDelete(); break; case IDC_FOLD_EXPLICIT_TRMNTRS_LIST: switch HIWORD(wParam) { case LBN_SELCHANGE: onEndRecSelect(); break; } break; case IDC_FOLD_EXPLICIT_ENDREC_LIST: switch HIWORD(wParam) { case CBN_SELCHANGE: if (!loadingEdits) { cleanEndRecVals = FALSE; enableEndRecSelection(); } break; } break; case IDC_FOLD_EXPLICIT_ENDREC_ACCEPT: case IDC_FOLD_EXPLICIT_ENDREC_RESET: endRecEditAccept(LOWORD(wParam) == IDC_FOLD_EXPLICIT_ENDREC_ACCEPT); break; case IDC_FOLD_EXPLICIT_ENDREC_NEW: endRecEditNew(); break; case IDC_FOLD_EXPLICIT_ENDREC_DEL: endRecEditDelete(); break; case IDC_FOLD_DEF_INFO_BUTTON: ShellExecute(NULL, L"open", FOLD_DEF_INFO_README, NULL, NULL, SW_SHOW); break; case IDC_FOLD_DEF_SAVE_BTN: SetCursor(LoadCursor(NULL, IDC_WAIT)); saveFoldStructInfo(); SetCursor(LoadCursor(NULL, IDC_ARROW)); return TRUE; case IDC_FOLD_DEF_RESET_BTN: if (!promptDiscardChangesNo()) { structsFile = L""; loadStructsInfo(); fillFoldStructs(); } break; case IDC_FOLD_DEF_BACKUP_LOAD_BTN: if (!promptDiscardChangesNo()) { wstring backupStructsFile; if (_configIO.queryConfigFileName(_hSelf, TRUE, TRUE, backupStructsFile)) { if (_configIO.fixIfNotUTF8File(backupStructsFile)) { structsFile = backupStructsFile; loadStructsInfo(); fillFoldStructs(); cleanStructsFile = FALSE; enableStructSelection(); } } } break; case IDC_FOLD_DEF_BACKUP_VIEW_BTN: _configIO.viewBackupFolder(); break; case IDC_FOLD_DEF_EXTRACT_BTN: showEximDialog(TRUE); break; case IDC_FOLD_DEF_APPEND_BTN: showEximDialog(FALSE); break; case IDCANCEL: case IDCLOSE: if (promptDiscardChangesNo()) return TRUE; display(FALSE); return TRUE; } break; case WM_INITDIALOG: NPPDM_AutoSubclassAndThemeChildControls(_hSelf); break; case WM_CTLCOLORDLG: case WM_CTLCOLORSTATIC: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLOREDIT: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorSofter(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLORLISTBOX: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorListbox(wParam, lParam); } break; case WM_PRINTCLIENT: if (NPPDM_IsEnabled()) return TRUE; break; case FWVIZMSG_APPEND_EXIM_DATA: appendFoldStructInfo(reinterpret_cast<LPCWSTR>(lParam)); break; } return FALSE; } void FoldStructDialog::localize() { SetWindowText(_hSelf, FOLD_STRUCT_DIALOG_TITLE); SetDlgItemText(_hSelf, IDC_FOLD_DEF_FILE_GROUP_BOX, FOLD_DEF_FILE_GROUP_BOX); SetDlgItemText(_hSelf, IDC_FOLD_DEF_FILE_TYPE_LABEL, FOLD_DEF_FILE_TYPE_LABEL); SetDlgItemText(_hSelf, IDC_FOLD_DEF_AUTO_FOLD_APPLY, FOLD_DEF_AUTO_FOLD_APPLY); SetDlgItemText(_hSelf, IDC_FOLD_DEF_FILE_ACCEPT_BTN, FOLD_DEF_FILE_ACCEPT_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_FILE_RESET_BTN, FOLD_DEF_FILE_RESET_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_FILE_NEW_BTN, FOLD_DEF_FILE_NEW_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_FILE_RESET_BTN, FOLD_DEF_FILE_RESET_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_FILE_CLONE_BTN, FOLD_DEF_FILE_CLONE_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_FILE_DEL_BTN, FOLD_DEF_FILE_DEL_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_REC_GROUP_BOX, FOLD_DEF_HDR_REC_GROUP_BOX); SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_REC_TYPE_LABEL, FOLD_DEF_HDR_REC_TYPE_LABEL); SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_PRIORITY_LABEL, FOLD_DEF_HDR_PRIORITY_LABEL); SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_REC_RECURSIVE, FOLD_DEF_HDR_REC_RECURSIVE); SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_REC_ACCEPT_BTN, FOLD_DEF_HDR_REC_ACCEPT_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_REC_RESET_BTN, FOLD_DEF_HDR_REC_RESET_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_REC_NEW_BTN, FOLD_DEF_HDR_REC_NEW_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_REC_RESET_BTN, FOLD_DEF_HDR_REC_RESET_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_REC_CLONE_BTN, FOLD_DEF_HDR_REC_CLONE_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_REC_DEL_BTN, FOLD_DEF_HDR_REC_DEL_BTN); SetDlgItemText(_hSelf, IDC_FOLD_IMPLICIT_TRMNTRS_GROUP, FOLD_IMPLICIT_TRMNTRS_GROUP); SetDlgItemText(_hSelf, IDC_FOLD_EXPLICIT_TRMNTRS_GROUP, FOLD_EXPLICIT_TRMNTRS_GROUP); SetDlgItemText(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_LABEL, FOLD_EXPLICIT_ENDREC_LABEL); SetDlgItemText(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_ACCEPT, FOLD_EXPLICIT_ENDREC_ACCEPT); SetDlgItemText(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_RESET, FOLD_EXPLICIT_ENDREC_RESET); SetDlgItemText(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_NEW, FOLD_EXPLICIT_ENDREC_NEW); SetDlgItemText(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_RESET, FOLD_EXPLICIT_ENDREC_RESET); SetDlgItemText(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_DEL, FOLD_EXPLICIT_ENDREC_DEL); SetDlgItemText(_hSelf, IDC_FOLD_DEF_SAVE_BTN, FOLD_DEF_SAVE_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_RESET_BTN, FOLD_DEF_RESET_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_BACKUP_LOAD_BTN, FOLD_DEF_BACKUP_LOAD_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_BACKUP_VIEW_BTN, FOLD_DEF_BACKUP_VIEW_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_EXTRACT_BTN, FOLD_DEF_EXTRACT_BTN); SetDlgItemText(_hSelf, IDC_FOLD_DEF_APPEND_BTN, FOLD_DEF_APPEND_BTN); } void FoldStructDialog::indicateCleanStatus() { if (cleanStructsFile) { SetDlgItemText(_hSelf, IDC_FOLD_DEF_SAVE_BTN, FOLD_DEF_SAVE_BTN); Utils::setFontRegular(_hSelf, IDC_FOLD_DEF_SAVE_BTN); } else { SetDlgItemText(_hSelf, IDC_FOLD_DEF_SAVE_BTN, (wstring(FOLD_DEF_SAVE_BTN) + L"*").c_str()); Utils::setFontBold(_hSelf, IDC_FOLD_DEF_SAVE_BTN); } if (cleanStructVals) { SetDlgItemText(_hSelf, IDC_FOLD_DEF_FILE_ACCEPT_BTN, FOLD_DEF_FILE_ACCEPT_BTN); Utils::setFontRegular(_hSelf, IDC_FOLD_DEF_FILE_ACCEPT_BTN); } else { SetDlgItemText(_hSelf, IDC_FOLD_DEF_FILE_ACCEPT_BTN, (wstring(FOLD_DEF_FILE_ACCEPT_BTN) + L"*").c_str()); Utils::setFontBold(_hSelf, IDC_FOLD_DEF_FILE_ACCEPT_BTN); } if (cleanBlockVals) { SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_REC_ACCEPT_BTN, FOLD_DEF_HDR_REC_ACCEPT_BTN); Utils::setFontRegular(_hSelf, IDC_FOLD_DEF_HDR_REC_ACCEPT_BTN); } else { SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_REC_ACCEPT_BTN, (wstring(FOLD_DEF_HDR_REC_ACCEPT_BTN) + L"*").c_str()); Utils::setFontBold(_hSelf, IDC_FOLD_DEF_HDR_REC_ACCEPT_BTN); } if (cleanEndRecVals) { SetDlgItemText(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_ACCEPT, FOLD_EXPLICIT_ENDREC_ACCEPT); Utils::setFontRegular(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_ACCEPT); } else { SetDlgItemText(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_ACCEPT, (wstring(FOLD_EXPLICIT_ENDREC_ACCEPT) + L"*").c_str()); Utils::setFontBold(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_ACCEPT); } } void FoldStructDialog::fillFoldStructs() { SendMessage(hFoldStructs, LB_RESETCONTENT, NULL, NULL); for (size_t i{}; i < vFoldStructs.size(); ++i) { SendMessage(hFoldStructs, LB_ADDSTRING, NULL, (LPARAM)vFoldStructs[i].fileType.label.c_str()); } if (vFoldStructs.size()) SendMessage(hFoldStructs, LB_SETCURSEL, 0, 0); cleanStructsFile = TRUE; cleanStructVals = TRUE; onFoldStructSelect(); } int FoldStructDialog::loadFileTypesList() { vector<string> fileTypes; int ftCount{ _configIO.getConfigValueList(fileTypes, "Base", "FileTypes") }; vFileTypes.clear(); vFileTypes.resize(ftCount); SendMessage(hFTList, CB_RESETCONTENT, NULL, NULL); for (int i{}; i < ftCount; ++i) { wstring fileLabel{ _configIO.getConfigWideChar(fileTypes[i], "FileLabel") }; vFileTypes[i].type = fileTypes[i]; vFileTypes[i].label = fileLabel; SendMessage(hFTList, CB_ADDSTRING, NULL, (LPARAM)fileLabel.c_str()); } return ftCount; } int FoldStructDialog::loadRecTypesList(string fileType) { vector<string> recTypesList; int recTypeCount{ _configIO.getConfigValueList(recTypesList, fileType, "RecordTypes") }; vRecTypes.clear(); vRecTypes.resize(recTypeCount); for (int i{}; i < recTypeCount; ++i) { vRecTypes[i].type = recTypesList[i]; vRecTypes[i].label = _configIO.getConfigWideChar(fileType, (recTypesList[i] + "_Label")); } return recTypeCount; } int FoldStructDialog::loadStructsInfo() { int foldStructCount{ _configIO.getFoldStructCount() }; vFoldStructs.clear(); vFoldStructs.resize(foldStructCount); for (int i{}; i < foldStructCount; ++i) { loadFoldStructInfo(i, "", structsFile); } return static_cast<int>(vFoldStructs.size()); } int FoldStructDialog::loadFoldStructInfo(int vIndex, string fsType, const wstring& sStructsFile) { if (fsType.empty()) { char buf[10]; snprintf(buf, 6, "FS%03d", vIndex + 1); fsType = buf; } FoldStructInfo& FS{ vFoldStructs[vIndex] }; TypeInfo& FT{ FS.fileType }; FT.type = _configIO.getFoldStructValueA(fsType, "FileType", sStructsFile); FT.label = _configIO.getConfigWideChar(FT.type, "FileLabel"); if (FT.label.empty()) FT.label = Utils::NarrowToWide(FT.type); FS.autoFold = (_configIO.getFoldStructValueA(fsType, "FoldLevelAuto", sStructsFile) == "Y"); loadRecTypesList(FT.type); string headerRecs{ _configIO.getFoldStructValueA(fsType, "HeaderRecords", sStructsFile) }; vector<string> headerRecList{}; int headerCount{ _configIO.Tokenize(headerRecs, headerRecList) }; int recTypeCount{ static_cast<int>(vRecTypes.size()) }; vector<BlockInfo>& BI{ FS.vBlocks }; BI.clear(); BI.resize(headerCount); for (int i{}; i < headerCount; ++i) { int hdrIndex{ Utils::StringtoInt(headerRecList[i].substr(3)) - 1 }; BI[i].hdrRec.type = headerRecList[i]; BI[i].hdrRec.label = (hdrIndex >= recTypeCount) ? Utils::NarrowToWide(headerRecList[i]) : vRecTypes[hdrIndex].label; BI[i].priority = Utils::StringtoInt(_configIO.getFoldStructValueA(fsType, headerRecList[i] + "_Priority", sStructsFile)); BI[i].recursive = (_configIO.getFoldStructValueA(fsType, headerRecList[i] + "_Recursive", sStructsFile) == "Y"); string endRecs{ _configIO.getFoldStructValueA(fsType, headerRecList[i] + "_EndRecords", sStructsFile) }; vector<string> endRecList{}; int endRecsCount{ _configIO.Tokenize(endRecs, endRecList) }; vector<TypeInfo>& ER{ BI[i].vEndRecs }; ER.clear(); ER.resize(endRecsCount); for (int j{}; j < endRecsCount; ++j) { int endRecIndex{ Utils::StringtoInt(endRecList[j].substr(3)) - 1 }; ER[j].type = endRecList[j]; ER[j].label = (endRecIndex >= recTypeCount) ? Utils::NarrowToWide(endRecList[j]) : vRecTypes[endRecIndex].label; } } return headerCount; } void FoldStructDialog::onFoldStructSelect() { FoldStructInfo* fsInfo; if (!getCurrentFoldStructInfo(fsInfo)) { FoldStructInfo newFile{}; fsInfo = &newFile; } onFoldStructSelectFill(fsInfo); enableMoveStructButtons(); fillFoldBlocks(); } void FoldStructDialog::onFoldStructSelectFill(FoldStructInfo* fsInfo) { loadingEdits = TRUE; Utils::setComboBoxSelection(hFTList, static_cast<int>( SendMessage(hFTList, CB_FINDSTRING, (WPARAM)-1, (LPARAM)fsInfo->fileType.label.c_str()))); CheckDlgButton(_hSelf, IDC_FOLD_DEF_AUTO_FOLD_APPLY, fsInfo->autoFold ? BST_CHECKED : BST_UNCHECKED); loadingEdits = FALSE; } void FoldStructDialog::enableMoveStructButtons() { int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return; EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_FILE_DOWN_BUTTON), (idxFS < static_cast<int>(vFoldStructs.size()) - 1)); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_FILE_UP_BUTTON), (idxFS > 0)); } void FoldStructDialog::enableStructSelection() { bool enable{ cleanStructVals && cleanBlockVals && cleanEndRecVals }; bool structRecsExist{ SendMessage(hFoldStructs, LB_GETCOUNT, 0, 0) > 0 }; bool fileTypesExist{ vFileTypes.size() > 0 }; ShowWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_FILE_NEW_BTN), cleanStructVals ? SW_SHOW : SW_HIDE); ShowWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_FILE_RESET_BTN), cleanStructVals ? SW_HIDE : SW_SHOW); EnableWindow(hFoldStructs, enable); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_AUTO_FOLD_APPLY), fileTypesExist); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_FILE_ACCEPT_BTN), fileTypesExist); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_FILE_NEW_BTN), fileTypesExist && enable); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_FILE_CLONE_BTN), fileTypesExist && enable); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_FILE_DEL_BTN), structRecsExist); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_EXTRACT_BTN), enable); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_APPEND_BTN), enable); if (enable) { enableMoveStructButtons(); } else { EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_FILE_DOWN_BUTTON), FALSE); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_FILE_UP_BUTTON), FALSE); } indicateCleanStatus(); } int FoldStructDialog::moveStructType(move_dir dir) { const int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return LB_ERR; switch (dir) { case MOVE_DOWN: if (idxFS >= static_cast<int>(vFoldStructs.size()) - 1) return LB_ERR; break; case MOVE_UP: if (idxFS == 0) return LB_ERR; break; default: return LB_ERR; } FoldStructInfo currStruct{ vFoldStructs[idxFS] }; FoldStructInfo& adjStruct{ vFoldStructs[idxFS + dir] }; vFoldStructs[idxFS] = adjStruct; vFoldStructs[idxFS + dir] = currStruct; SendMessage(hFoldStructs, LB_DELETESTRING, idxFS, NULL); SendMessage(hFoldStructs, LB_INSERTSTRING, (idxFS + dir), (LPARAM)vFoldStructs[idxFS + dir].fileType.label.c_str()); SendMessage(hFoldStructs, LB_SETCURSEL, idxFS + dir, NULL); cleanStructsFile = FALSE; indicateCleanStatus(); enableMoveStructButtons(); return idxFS + dir; } int FoldStructDialog::structEditAccept(bool accept) { if (cleanStructVals) return 0; int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return -1; FoldStructInfo& fsInfo{ vFoldStructs[idxFS] }; if (accept) { int index{ static_cast<int>(SendMessage(hFTList, CB_GETCURSEL, 0, 0)) }; if (index >= static_cast<int>(vFileTypes.size())) return -1; fsInfo.fileType.type = vFileTypes[index].type; fsInfo.fileType.label = vFileTypes[index].label; fsInfo.autoFold = (IsDlgButtonChecked(_hSelf, IDC_FOLD_DEF_AUTO_FOLD_APPLY) == BST_CHECKED); } else if (fsInfo.fileType.label.empty()) { structEditDelete(); return 0; } else { onFoldStructSelectFill(&fsInfo); } // Update FT Listbox Entry SendMessage(hFoldStructs, LB_DELETESTRING, idxFS, NULL); SendMessage(hFoldStructs, LB_INSERTSTRING, idxFS, (LPARAM)fsInfo.fileType.label.c_str()); SendMessage(hFoldStructs, LB_SETCURSEL, idxFS, NULL); cleanStructsFile = FALSE; cleanStructVals = TRUE; enableStructSelection(); return 1; } void FoldStructDialog::structEditNew() { FoldStructInfo newFS{}; vFoldStructs.push_back(newFS); size_t moveTo = vFoldStructs.size() - 1; SendMessage(hFoldStructs, LB_ADDSTRING, NULL, (LPARAM)newFS.fileType.label.c_str()); SendMessage(hFoldStructs, LB_SETCURSEL, moveTo, NULL); onFoldStructSelect(); cleanStructsFile = FALSE; cleanStructVals = FALSE; enableStructSelection(); } void FoldStructDialog::structEditClone() { int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return; FoldStructInfo& FS{ vFoldStructs[idxFS] }; FoldStructInfo NF{}; NF.fileType = FS.fileType; NF.autoFold = FS.autoFold; // Block Info size_t blockCount = FS.vBlocks.size(); NF.vBlocks.resize(blockCount); for (size_t i{}; i < blockCount; ++i) { BlockInfo& NFBI{ NF.vBlocks[i] }; BlockInfo& FSBI{ FS.vBlocks[i] }; NFBI.hdrRec = FSBI.hdrRec; NFBI.priority = FSBI.priority; NFBI.recursive = FSBI.recursive; // End Recs Info size_t endRecsCount = FSBI.vEndRecs.size(); NFBI.vEndRecs.resize(endRecsCount); for (size_t j{}; j < endRecsCount; ++j) { NFBI.vEndRecs[j] = FSBI.vEndRecs[j]; } } vFoldStructs.push_back(NF); SendMessage(hFoldStructs, LB_ADDSTRING, NULL, (LPARAM)NF.fileType.label.c_str()); SendMessage(hFoldStructs, LB_SETCURSEL, (vFoldStructs.size() - 1), NULL); onFoldStructSelect(); cleanStructsFile = FALSE; cleanStructVals = FALSE; enableStructSelection(); } int FoldStructDialog::structEditDelete() { int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return LB_ERR; vFoldStructs[idxFS].vBlocks.clear(); vFoldStructs.erase(vFoldStructs.begin() + idxFS); int lastFile = static_cast<int>(vFoldStructs.size()) - 1; int moveTo = (idxFS <= lastFile) ? idxFS : lastFile; SendMessage(hFoldStructs, LB_DELETESTRING, idxFS, NULL); SendMessage(hFoldStructs, LB_SETCURSEL, moveTo, NULL); cleanStructsFile = FALSE; cleanStructVals = TRUE; onFoldStructSelect(); return moveTo; } void FoldStructDialog::fillFoldBlocks() { FoldStructInfo* fsInfo; if (!getCurrentFoldStructInfo(fsInfo)) { FoldStructInfo newFs{}; fsInfo = &newFs; } vector <BlockInfo>& blockInfoList{ fsInfo->vBlocks }; // Fill Fold Blocks Listbox SendMessage(hFoldBlocks, LB_RESETCONTENT, NULL, NULL); for (const auto& BI : blockInfoList) { SendMessage(hFoldBlocks, LB_ADDSTRING, NULL, (LPARAM)BI.hdrRec.label.c_str()); } if (blockInfoList.size()) SendMessage(hFoldBlocks, LB_SETCURSEL, 0, NULL); // Fill Header Rec Types Listbox loadRecTypesList(fsInfo->fileType.type); SendMessage(hHdrRTList, CB_RESETCONTENT, NULL, NULL); SendMessage(hExplRTList, CB_RESETCONTENT, NULL, NULL); for (const auto& RT : vRecTypes) { SendMessage(hHdrRTList, CB_ADDSTRING, NULL, (LPARAM)RT.label.c_str()); SendMessage(hExplRTList, CB_ADDSTRING, NULL, (LPARAM)RT.label.c_str()); } cleanBlockVals = TRUE; onFoldBlockSelect(); } void FoldStructDialog::onFoldBlockSelect() { BlockInfo* blockInfo; if (!getCurrentBlockInfo(blockInfo)) { BlockInfo newBlock{}; blockInfo = &newBlock; } onFoldBlockSelectFill(blockInfo); enableMoveBlockButtons(); fillImplicitEndRecs(); fillExplicitEndRecs(blockInfo); } void FoldStructDialog::onFoldBlockSelectFill(BlockInfo* blockInfo) { loadingEdits = TRUE; Utils::setComboBoxSelection(hHdrRTList, static_cast<int>( SendMessage(hHdrRTList, CB_FINDSTRING, (WPARAM)-1, (LPARAM)blockInfo->hdrRec.label.c_str()))); SetDlgItemText(_hSelf, IDC_FOLD_DEF_HDR_PRIORITY_EDIT, to_wstring(blockInfo->priority).c_str()); CheckDlgButton(_hSelf, IDC_FOLD_DEF_HDR_REC_RECURSIVE, blockInfo->recursive ? BST_CHECKED : BST_UNCHECKED); loadingEdits = FALSE; } void FoldStructDialog::enableMoveBlockButtons() { int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return; int idxBlock{ getCurrentBlockIndex() }; if (idxBlock == LB_ERR) return; EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_DOWN_BTN), (idxBlock < static_cast<int>(vFoldStructs[idxFS].vBlocks.size()) - 1)); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_UP_BTN), (idxBlock > 0)); } void FoldStructDialog::enableBlockSelection() { bool enable{ cleanBlockVals && cleanEndRecVals }; bool blockRecsExist{ SendMessage(hFoldBlocks, LB_GETCOUNT, 0, 0) > 0 }; bool recTypesExist{ vRecTypes.size() > 0 }; ShowWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_NEW_BTN), cleanBlockVals ? SW_SHOW : SW_HIDE); ShowWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_RESET_BTN), cleanBlockVals ? SW_HIDE : SW_SHOW); EnableWindow(hFoldBlocks, enable); EnableWindow(hHdrRTList, blockRecsExist && recTypesExist); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_PRIORITY_EDIT), blockRecsExist && recTypesExist); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_RECURSIVE), blockRecsExist && recTypesExist); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_ACCEPT_BTN), blockRecsExist && recTypesExist); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_NEW_BTN), recTypesExist && enable); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_CLONE_BTN), blockRecsExist && recTypesExist && enable); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_DEL_BTN), blockRecsExist); if (enable) { enableMoveBlockButtons(); } else { EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_DOWN_BTN), FALSE); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_DEF_HDR_REC_UP_BTN), FALSE); } enableStructSelection(); } int FoldStructDialog::moveBlockType(move_dir dir) { const int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return LB_ERR; const int idxBlock{ getCurrentBlockIndex() }; if (idxBlock == LB_ERR) return LB_ERR; vector<BlockInfo>& blockList{ vFoldStructs[idxFS].vBlocks }; switch (dir) { case MOVE_DOWN: if (idxBlock >= static_cast<int>(blockList.size()) - 1) return LB_ERR; break; case MOVE_UP: if (idxBlock == 0) return LB_ERR; break; default: return LB_ERR; } BlockInfo currType{ blockList[idxBlock] }; BlockInfo& adjType{ blockList[idxBlock + dir] }; blockList[idxBlock] = adjType; blockList[idxBlock + dir] = currType; SendMessage(hFoldBlocks, LB_DELETESTRING, idxBlock, NULL); SendMessage(hFoldBlocks, LB_INSERTSTRING, (idxBlock + dir), (LPARAM)blockList[idxBlock + dir].hdrRec.label.c_str()); SendMessage(hFoldBlocks, LB_SETCURSEL, idxBlock + dir, NULL); cleanStructsFile = FALSE; indicateCleanStatus(); enableMoveBlockButtons(); return idxBlock + dir; } int FoldStructDialog::blockEditAccept(bool accept) { if (cleanBlockVals) return 0; int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return LB_ERR; int idxBlock{ getCurrentBlockIndex() }; if (idxBlock == LB_ERR) return LB_ERR; BlockInfo& BI{ vFoldStructs[idxFS].vBlocks[idxBlock] }; if (accept) { int index{ static_cast<int>(SendMessage(hHdrRTList, CB_GETCURSEL, 0, 0)) }; if (index >= static_cast<int>(vRecTypes.size())) return -1; BI.hdrRec.type = vRecTypes[index].type; BI.hdrRec.label = vRecTypes[index].label; BI.priority = static_cast<int>(GetDlgItemInt(_hSelf, IDC_FOLD_DEF_HDR_PRIORITY_EDIT, NULL, FALSE)); BI.recursive = (IsDlgButtonChecked(_hSelf, IDC_FOLD_DEF_HDR_REC_RECURSIVE) == BST_CHECKED); } else if (BI.hdrRec.label.empty()) { blockEditDelete(); return 0; } else { onFoldBlockSelectFill(&BI); } SendMessage(hFoldBlocks, LB_DELETESTRING, idxBlock, NULL); SendMessage(hFoldBlocks, LB_INSERTSTRING, idxBlock, (LPARAM)BI.hdrRec.label.c_str()); SendMessage(hFoldBlocks, LB_SETCURSEL, idxBlock, NULL); cleanStructsFile = FALSE; cleanBlockVals = TRUE; enableBlockSelection(); return 1; } void FoldStructDialog::blockEditNew(bool clone) { int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return; int idxBlock{ getCurrentBlockIndex() }; if (clone && idxBlock == LB_ERR) return; vector<BlockInfo>& blocks{ vFoldStructs[idxFS].vBlocks }; BlockInfo NB{}; if (clone) { BlockInfo& BI{ blocks[idxBlock] }; NB.hdrRec = BI.hdrRec; NB.priority = BI.priority; NB.recursive = BI.recursive; size_t endRecCount{ BI.vEndRecs.size() }; NB.vEndRecs.resize(endRecCount); for (size_t i{}; i < endRecCount; ++i) { NB.vEndRecs[i] = BI.vEndRecs[i]; } } blocks.push_back(NB); size_t moveTo = blocks.size() - 1; SendMessage(hFoldBlocks, LB_ADDSTRING, NULL, (LPARAM)NB.hdrRec.label.c_str()); SendMessage(hFoldBlocks, LB_SETCURSEL, moveTo, NULL); onFoldBlockSelect(); cleanStructsFile = FALSE; cleanBlockVals = clone; enableBlockSelection(); } int FoldStructDialog::blockEditDelete() { int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return LB_ERR; int idxBlock{ getCurrentBlockIndex() }; if (idxBlock == LB_ERR) return LB_ERR; vector<BlockInfo>& blocks{ vFoldStructs[idxFS].vBlocks }; blocks.erase(blocks.begin() + idxBlock); int lastRec = static_cast<int>(blocks.size()) - 1; int moveTo = (idxBlock <= lastRec - 1) ? idxBlock : lastRec; SendMessage(hFoldBlocks, LB_DELETESTRING, idxBlock, NULL); SendMessage(hFoldBlocks, LB_SETCURSEL, moveTo, NULL); cleanStructsFile = FALSE; cleanBlockVals = TRUE; onFoldBlockSelect(); return moveTo; } void FoldStructDialog::fillImplicitEndRecs() { FoldStructInfo* fsInfo; if (!getCurrentFoldStructInfo(fsInfo)) { FoldStructInfo newFs{}; fsInfo = &newFs; } int recTypeIndex{ static_cast<int>(SendMessage(hHdrRTList, CB_GETCURSEL, 0, 0)) }; int priority{ static_cast<int>(GetDlgItemInt(_hSelf, IDC_FOLD_DEF_HDR_PRIORITY_EDIT, NULL, FALSE)) }; bool recursive{ IsDlgButtonChecked(_hSelf, IDC_FOLD_DEF_HDR_REC_RECURSIVE) == BST_CHECKED }; int threshold{ priority - (recursive ? 1 : 0) }; vector <BlockInfo>& blockInfoList{ fsInfo->vBlocks }; SendMessage(hImplRecs, LB_RESETCONTENT, NULL, NULL); for (const auto& BI : blockInfoList) { if (BI.hdrRec.label.empty()) continue; if (recursive && (BI.hdrRec.type == vRecTypes[recTypeIndex].type)) continue; if (BI.priority > threshold) continue; SendMessage(hImplRecs, LB_ADDSTRING, NULL, (LPARAM)BI.hdrRec.label.c_str()); } SendMessage(hImplRecs, LB_ADDSTRING, NULL, (LPARAM)FOLD_IMPLICIT_END_OF_FILE); } void FoldStructDialog::fillExplicitEndRecs(BlockInfo* blockInfo) { SendMessage(hExplRecs, LB_RESETCONTENT, NULL, NULL); for (const auto& ER : blockInfo->vEndRecs) { SendMessage(hExplRecs, LB_ADDSTRING, NULL, (LPARAM)ER.label.c_str()); } if (blockInfo->vEndRecs.size()) SendMessage(hExplRecs, LB_SETCURSEL, 0, NULL); onEndRecSelect(); cleanEndRecVals = TRUE; enableBlockSelection(); } void FoldStructDialog::onEndRecSelect() { onEndRecSelectFill(); enableEndRecSelection(); } void FoldStructDialog::onEndRecSelectFill() { loadingEdits = TRUE; Utils::setComboBoxSelection(hExplRTList, static_cast<int>( SendMessage(hExplRTList, CB_FINDSTRING, (WPARAM)-1, (LPARAM)Utils::getListBoxItem(hExplRecs).c_str()))); loadingEdits = FALSE; } void FoldStructDialog::enableEndRecSelection() { bool enable{ cleanEndRecVals }; bool blockRecsExist{ SendMessage(hFoldBlocks, LB_GETCOUNT, 0, 0) > 0 }; bool endRecsExist{ SendMessage(hExplRecs, LB_GETCOUNT, 0, 0) > 0 }; bool recTypesExist{ vRecTypes.size() > 0 }; ShowWindow(GetDlgItem(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_NEW), cleanEndRecVals ? SW_SHOW : SW_HIDE); ShowWindow(GetDlgItem(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_RESET), cleanEndRecVals ? SW_HIDE : SW_SHOW); EnableWindow(hExplRecs, enable); EnableWindow(hExplRTList, endRecsExist && recTypesExist); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_ACCEPT), endRecsExist && recTypesExist); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_NEW), blockRecsExist && recTypesExist && enable); EnableWindow(GetDlgItem(_hSelf, IDC_FOLD_EXPLICIT_ENDREC_DEL), endRecsExist); enableBlockSelection(); } int FoldStructDialog::endRecEditAccept(bool accept) { if (cleanEndRecVals) return 0; int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return LB_ERR; int idxBlock{ getCurrentBlockIndex() }; if (idxBlock == LB_ERR) return LB_ERR; int idxEndRec{ static_cast<int>(SendMessage(hExplRecs, LB_GETCURSEL, 0, 0)) }; if (idxEndRec == LB_ERR) return LB_ERR; TypeInfo& TI{ vFoldStructs[idxFS].vBlocks[idxBlock].vEndRecs[idxEndRec] }; if (accept) { int index{ static_cast<int>(SendMessage(hExplRTList, CB_GETCURSEL, 0, 0)) }; if (index >= static_cast<int>(vRecTypes.size())) return -1; TI.type = vRecTypes[index].type; TI.label = vRecTypes[index].label; } else if (TI.label.empty()) { endRecEditDelete(); return 0; } else { onEndRecSelectFill(); } SendMessage(hExplRecs, LB_DELETESTRING, idxEndRec, NULL); SendMessage(hExplRecs, LB_INSERTSTRING, idxEndRec, (LPARAM)TI.label.c_str()); SendMessage(hExplRecs, LB_SETCURSEL, idxEndRec, NULL); cleanStructsFile = FALSE; cleanEndRecVals = TRUE; enableEndRecSelection(); return 1; } void FoldStructDialog::endRecEditNew() { if (!vRecTypes.size()) return; int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return; int idxBlock{ getCurrentBlockIndex() }; if (idxBlock == LB_ERR) return; vector<TypeInfo>& endRecs{ vFoldStructs[idxFS].vBlocks[idxBlock].vEndRecs }; endRecs.push_back(TypeInfo{}); size_t moveTo = endRecs.size() - 1; SendMessage(hExplRecs, LB_ADDSTRING, NULL, (LPARAM)L""); SendMessage(hExplRecs, LB_SETCURSEL, moveTo, NULL); onEndRecSelect(); cleanStructsFile = FALSE; cleanEndRecVals = FALSE; enableEndRecSelection(); } int FoldStructDialog::endRecEditDelete() { int endRecCount{ static_cast<int>(SendMessage(hExplRecs, LB_GETCOUNT, 0, 0)) }; if (endRecCount == LB_ERR) return LB_ERR; if (!endRecCount) return 0; int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return LB_ERR; int idxBlock{ getCurrentBlockIndex() }; if (idxBlock == LB_ERR) return LB_ERR; int idxEndRec{ static_cast<int>(SendMessage(hExplRecs, LB_GETCURSEL, 0, 0)) }; if (idxEndRec == LB_ERR) return LB_ERR; vector<TypeInfo>& endRecs{ vFoldStructs[idxFS].vBlocks[idxBlock].vEndRecs }; endRecs.erase(endRecs.begin() + idxEndRec); int lastRec = static_cast<int>(endRecs.size()) - 1; int moveTo = (idxEndRec <= lastRec - 1) ? idxEndRec : lastRec; SendMessage(hExplRecs, LB_DELETESTRING, idxEndRec, NULL); SendMessage(hExplRecs, LB_SETCURSEL, moveTo, NULL); cleanStructsFile = FALSE; cleanEndRecVals = TRUE; onEndRecSelect(); return moveTo; } bool FoldStructDialog::promptDiscardChangesNo() { if (!(cleanStructsFile && cleanStructVals && cleanBlockVals && cleanEndRecVals)) { if (MessageBox(_hSelf, FOLD_DEF_DISCARD_CHANGES, FOLD_STRUCT_DIALOG_TITLE, MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) == IDNO) return TRUE; } return false; } void FoldStructDialog::saveFoldStructInfo() { if (_configIO.isCurrentVizConfigDefault() && MessageBox(_hSelf, FWVIZ_DEFAULT_OVERWRITE, FWVIZ_DEF_DIALOG_TITLE, MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) == IDNO) return; if (!cleanEndRecVals) endRecEditAccept(); if (!cleanBlockVals) if (blockEditAccept() < 0) return; if (!cleanStructVals) if (structEditAccept() < 0) return; size_t fsCount; wstring fileData{}, fsConfig{}; fsCount = vFoldStructs.size(); fileData = L"[Base]\r\nFoldStructCount=" + to_wstring(fsCount) + L"\r\n\r\n"; for (size_t i{}; i < fsCount; ++i) { if (getFoldStructInfo(i, TRUE, fsConfig) < 0) return; fileData += fsConfig + L"\r\n"; } _configIO.backupConfigFile(_configIO.getConfigFile(_configIO.CONFIG_FOLDSTRUCTS)); _configIO.saveConfigFile(fileData, _configIO.getConfigFile(_configIO.CONFIG_FOLDSTRUCTS)); cleanStructsFile = TRUE; indicateCleanStatus(); } void FoldStructDialog::showEximDialog(bool bExtract) { _eximDlg.doDialog((HINSTANCE)_gModule); _eximDlg.initDialog(_hSelf, EximFileTypeDialog::FOLDS_DLG, bExtract); if (bExtract) { int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return; wstring fsConfig{}; if (getFoldStructInfo(idxFS, TRUE, fsConfig) < 0) { _eximDlg.display(false); return; } _eximDlg.setFileTypeData(fsConfig); } } int FoldStructDialog::appendFoldStructInfo(const wstring& sConfigFile) { vector<string> sectionList{}; string sectionFT{}; wstring sectionLabel{}; int sectionCount{ _configIO.getConfigAllSectionsList(sectionList, Utils::WideToNarrow(sConfigFile)) }; int validCount{}; for (int i{}; i < sectionCount; ++i) { sectionFT = _configIO.getConfigStringA(sectionList[i], "FileType", "", Utils::WideToNarrow(sConfigFile)); if (sectionFT.empty()) continue; sectionLabel = _configIO.getConfigWideChar(sectionList[i], "FileLabel", "", Utils::WideToNarrow(sConfigFile)); if (sectionLabel.empty()) continue; FoldStructInfo newFS{}; vFoldStructs.push_back(newFS); loadFoldStructInfo(static_cast<int>(vFoldStructs.size() - 1), sectionList[i], sConfigFile); SendMessage(hFoldStructs, LB_ADDSTRING, NULL, (LPARAM)sectionLabel.c_str()); ++validCount; } SendMessage(hFoldStructs, LB_SETCURSEL, (vFoldStructs.size() - 1), NULL); onFoldStructSelect(); cleanStructsFile = FALSE; enableStructSelection(); return validCount; } int FoldStructDialog::getCurrentFoldStructIndex() const { int idxFS; idxFS = static_cast<int>(SendMessage(hFoldStructs, LB_GETCURSEL, NULL, NULL)); if (idxFS == LB_ERR) return LB_ERR; return idxFS; } bool FoldStructDialog::getCurrentFoldStructInfo(FoldStructInfo*& structInfo) { int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return FALSE; structInfo = &vFoldStructs[idxFS]; return TRUE; } int FoldStructDialog::getFoldStructInfo(size_t idxFS, bool cr_lf, wstring& fsConfig) { FoldStructInfo& FS{ vFoldStructs[idxFS] }; wstring new_line{ cr_lf ? L"\r\n" : L"\n" }; wstring hdrRecs{}, blockConfig{}; for (size_t i{}; i < FS.vBlocks.size(); ++i) { BlockInfo& BI{FS.vBlocks[i]}; wstring hdrFileType{ Utils::NarrowToWide(BI.hdrRec.type) }; wstring endRecs{}; for (size_t j{}; j < BI.vEndRecs.size(); ++j) { endRecs += (j == 0 ? L"" : L",") + Utils::NarrowToWide(BI.vEndRecs[j].type); } hdrRecs += (i == 0 ? L"" : L",") + hdrFileType; blockConfig += hdrFileType + L"_Priority=" + to_wstring(BI.priority) + new_line + hdrFileType + L"_Recursive=" + (BI.recursive ? L"Y" : L"N") + new_line + hdrFileType + L"_EndRecords=" + endRecs + new_line; } wchar_t foldStructCode[10]; swprintf(foldStructCode, 10, L"FS%03d", static_cast<int>(idxFS + 1)); fsConfig = L"[" + wstring{ foldStructCode } + L"]" + new_line + L"FileType=" + Utils::NarrowToWide(FS.fileType.type) + new_line + L"FileLabel=" + FS.fileType.label + new_line + L"FoldLevelAuto=" + (FS.autoFold ? L"Y" : L"N") + new_line + L"HeaderRecords=" + hdrRecs + new_line + blockConfig; return 0; } int FoldStructDialog::getCurrentBlockIndex() const { int idxBlock; idxBlock = static_cast<int>(SendMessage(hFoldBlocks, LB_GETCURSEL, NULL, NULL)); if (idxBlock == LB_ERR) return LB_ERR; return idxBlock; } bool FoldStructDialog::getCurrentBlockInfo(BlockInfo*& blockInfo) { int idxFS{ getCurrentFoldStructIndex() }; if (idxFS == LB_ERR) return FALSE; int idxBlock{ getCurrentBlockIndex() }; if (idxBlock == LB_ERR) return FALSE; blockInfo = &vFoldStructs[idxFS].vBlocks[idxBlock]; return TRUE; }
40,728
C++
.cpp
964
36.53112
127
0.691156
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,112
EximFileTypeDialog.cpp
shriprem_FWDataViz/src/Dialogs/EximFileTypeDialog.cpp
#include "EximFileTypeDialog.h" void EximFileTypeDialog::doDialog(HINSTANCE hInst) { if (!isCreated()) { Window::init(hInst, nppData._nppHandle); create(IDD_FILE_TYPE_EXIM_DIALOG); } goToCenter(); Utils::loadBitmap(_hSelf, IDC_FTEXIM_INFO_BUTTON, IDB_VIZ_INFO_BITMAP); Utils::addTooltip(_hSelf, IDC_FTEXIM_INFO_BUTTON, L"", VIZ_PANEL_INFO_TIP, FALSE); SendMessage(_hParent, NPPM_DMMSHOW, 0, (LPARAM)_hSelf); } void EximFileTypeDialog::initDialog(HWND hWnd, exim_clients mode, bool bExtract) { hClientDlg = hWnd; exim_mode = mode; extractMode = bExtract; localize(); ShowWindow(GetDlgItem(_hSelf, IDC_FTEXIM_SAVE_FILE), extractMode ? SW_SHOW : SW_HIDE); ShowWindow(GetDlgItem(_hSelf, IDC_FTEXIM_LOAD_FILE), extractMode ? SW_HIDE : SW_SHOW); ShowWindow(GetDlgItem(_hSelf, IDC_FTEXIM_APPEND), extractMode ? SW_HIDE : SW_SHOW); bool recentOS = Utils::checkBaseOS(WV_VISTA); wstring fontName = recentOS ? L"Consolas" : L"Courier New"; int fontHeight = recentOS ? 10 : 8; Utils::setFont(_hSelf, IDC_FTEXIM_EDIT_CNTRL, fontName, fontHeight); SetFocus(GetDlgItem(_hSelf, IDC_FTEXIM_EDIT_CNTRL)); } void EximFileTypeDialog::refreshDarkMode() { NPPDM_AutoThemeChildControls(_hSelf); redraw(); } void EximFileTypeDialog::setFileTypeData(const wstring& ftConfig) { SetDlgItemText(_hSelf, IDC_FTEXIM_EDIT_CNTRL, ftConfig.c_str()); } void EximFileTypeDialog::localize() { SetWindowText(_hSelf, extractMode ? EXTRACT_TITLE[exim_mode] : APPEND_TITLE[exim_mode]); SetDlgItemText(_hSelf, IDC_FTEXIM_EDIT_LABEL, EDIT_LABEL[exim_mode]); SetDlgItemText(_hSelf, IDC_FTEXIM_EDIT_CNTRL, L""); SetDlgItemText(_hSelf, IDCLOSE, EXIM_CLOSE_BTN); if (extractMode) { SetDlgItemText(_hSelf, IDC_FTEXIM_SAVE_FILE, EXIM_SAVE_FILE_BTN); SetDlgItemText(_hSelf, IDCLOSE, EXIM_CLOSE_BTN); } else { SetDlgItemText(_hSelf, IDC_FTEXIM_LOAD_FILE, EXIM_LOAD_FILE_BTN); SetDlgItemText(_hSelf, IDC_FTEXIM_APPEND, APPEND_BTN[exim_mode]); SetDlgItemText(_hSelf, IDCLOSE, EXIM_CANCEL_BTN); } } INT_PTR CALLBACK EximFileTypeDialog::run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: switch LOWORD(wParam) { case IDC_FTEXIM_INFO_BUTTON: ShellExecute(NULL, L"open", extractMode ? CONFIG_EXTRACT_INFO_README : CONFIG_APPEND_INFO_README, NULL, NULL, SW_SHOW); break; case IDCANCEL: case IDCLOSE: display(FALSE); return TRUE; case IDC_FTEXIM_LOAD_FILE: loadExtractFile(); break; case IDC_FTEXIM_SAVE_FILE: saveExtractFile(); break; case IDC_FTEXIM_APPEND: appendExtractFile(); break; } break; case WM_INITDIALOG: NPPDM_AutoSubclassAndThemeChildControls(_hSelf); break; case WM_CTLCOLORDLG: case WM_CTLCOLORSTATIC: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLOREDIT: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorSofter(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLORLISTBOX: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorListbox(wParam, lParam); } break; case WM_PRINTCLIENT: if (NPPDM_IsEnabled()) return TRUE; break; } return FALSE; } void EximFileTypeDialog::appendExtractFile() { wstring tmpFile{}; _configIO.getBackupTempFileName(tmpFile); _configIO.saveConfigFile(getEditControlText(), tmpFile); display(FALSE); SendMessage(hClientDlg, FWVIZMSG_APPEND_EXIM_DATA, 0, (LPARAM)tmpFile.c_str()); DeleteFile(tmpFile.c_str()); } void EximFileTypeDialog::loadExtractFile() { wstring sExtractFile{}; if (_configIO.queryConfigFileName(_hSelf, TRUE, FALSE, sExtractFile)) { if (_configIO.fixIfNotUTF8File(sExtractFile)) { string sExtractData{ _configIO.readConfigFile(sExtractFile) }; SetDlgItemText(_hSelf, IDC_FTEXIM_EDIT_CNTRL, Utils::NarrowToWide(sExtractData).c_str()); } } } void EximFileTypeDialog::saveExtractFile() { wstring sExtractFile{}; if (_configIO.queryConfigFileName(_hSelf, FALSE, FALSE, sExtractFile)) { _configIO.saveConfigFile(getEditControlText(), sExtractFile); } } wstring EximFileTypeDialog::getEditControlText() { wstring sExtractData(FW_LINE_MAX_LENGTH, '\0'); GetDlgItemText(_hSelf, IDC_FTEXIM_EDIT_CNTRL, sExtractData.data(), FW_LINE_MAX_LENGTH); return wstring{ sExtractData.c_str()}; }
4,603
C++
.cpp
122
32.467213
128
0.702697
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,113
JumpToField.cpp
shriprem_FWDataViz/src/Dialogs/JumpToField.cpp
#include "JumpToField.h" #include "VisualizerPanel.h" extern VisualizerPanel _vizPanel; void JumpToField::doDialog(HINSTANCE hInst) { if (!isCreated()) { Window::init(hInst, nppData._nppHandle); create(IDD_JUMP_FIELD_DIALOG); } CheckDlgButton(_hSelf, IDC_JUMP_FIELD_PREF_SEQ_NUM, _configIO.getPreferenceBool(PREF_JUMP_FIELD_SEQ, FALSE) ? BST_CHECKED : BST_UNCHECKED); hCaretFlash = GetDlgItem(_hSelf, IDC_JUMP_CARET_FLASH_SLIDER); SendMessage(hCaretFlash, TBM_SETRANGEMIN, FALSE, 1); SendMessage(hCaretFlash, TBM_SETRANGEMAX, FALSE, 10); using Utils::addTooltip; addTooltip(_hSelf, IDC_JUMP_CARET_FLASH_LABEL, L"", JUMP_TIP_CARET_FLASH, TRUE); addTooltip(_hSelf, IDC_JUMP_CARET_FLASH_SLIDER, L"", JUMP_TIP_CARET_FLASH, TRUE); addTooltip(_hSelf, IDC_JUMP_CARET_FLASH_VALUE, L"", JUMP_TIP_CARET_FLASH, TRUE); if constexpr(_gLanguage != LANG_ENGLISH) localize(); goToCenter(); SendMessage(_hParent, NPPM_DMMSHOW, 0, (LPARAM)_hSelf); } void JumpToField::refreshDarkMode() { NPPDM_AutoThemeChildControls(_hSelf); redraw(); SendMessage(hCaretFlash, TBM_SETRANGEMIN, FALSE, 1); } void JumpToField::initDialog(const string fileType, int recordIndex, int fieldIndex, const vector<wstring>& fieldLabels) { initFileType = fileType; initRecordRegIndex = recordIndex; pFieldLabels = &fieldLabels; hFieldList = GetDlgItem(_hSelf, IDC_JUMP_FIELD_LIST); loadJumpList(fieldIndex); int flashSecs{ _configIO.getPreferenceInt(PREF_CARET_FLASH, 5) }; SendMessage(hCaretFlash, TBM_SETPOS, TRUE, flashSecs); setTbarPosition(flashSecs, FALSE); SetFocus(hFieldList); } void JumpToField::setFileTypeData(const wstring& ftConfig) { SetDlgItemText(_hSelf, IDC_JUMP_FIELD_LIST, ftConfig.c_str()); } INT_PTR CALLBACK JumpToField::run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: switch LOWORD(wParam) { case IDCANCEL: case IDCLOSE: display(FALSE); return TRUE; case IDC_JUMP_FIELD_LIST: switch HIWORD(wParam) { case CBN_SELCHANGE: break; } break; case IDC_JUMP_FIELD_PREF_SEQ_NUM: onJumpSeqNumPref(); break; case IDC_JUMP_FIELD_GO_BTN: onJumpBtnClick(); break; } break; case WM_HSCROLL: if (lParam == (LPARAM)hCaretFlash) setTbarPosition(getTbarPosition(), TRUE); break; case WM_INITDIALOG: NPPDM_AutoSubclassAndThemeChildControls(_hSelf); break; case WM_CTLCOLORDLG: case WM_CTLCOLORSTATIC: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorDarker(reinterpret_cast<HDC>(wParam)); } break; case WM_CTLCOLORLISTBOX: if (NPPDM_IsEnabled()) { return NPPDM_OnCtlColorListbox(wParam, lParam); } break; case WM_PRINTCLIENT: if (NPPDM_IsEnabled()) return TRUE; break; } return FALSE; } void JumpToField::localize() { SetWindowText(_hSelf, JUMP_FIELD_DIALOG_TITLE); SetDlgItemText(_hSelf, IDC_JUMP_FIELD_LABEL, JUMP_FIELD_SELECT_LABEL); SetDlgItemText(_hSelf, IDC_JUMP_FIELD_PREF_SEQ_NUM, JUMP_FIELD_PREF_SEQ_NUM); SetDlgItemText(_hSelf, IDC_JUMP_CARET_FLASH_LABEL, JUMP_LABEL_CARET_FLASH); SetDlgItemText(_hSelf, IDC_JUMP_FIELD_GO_BTN, JUMP_FIELD_GO_BTN); SetDlgItemText(_hSelf, IDCLOSE, JUMP_FIELD_CLOSE_BTN); } void JumpToField::loadJumpList(int fieldIndex) { if (fieldIndex < 0) fieldIndex = static_cast<int>(SendMessage(hFieldList, CB_GETCURSEL, 0, 0)); SendMessage(hFieldList, CB_RESETCONTENT, NULL, NULL); wchar_t seqNo[5]; bool showSeqNo{ (_configIO.getPreferenceBool(PREF_JUMP_FIELD_SEQ, FALSE)) }; int fieldCount{ static_cast<int>(pFieldLabels->size()) }; for (int i{}; i < fieldCount; ++i) { swprintf(seqNo, 5, L"%02d. ", (i + 1)); SendMessage(hFieldList, CB_ADDSTRING, NULL, (LPARAM)((showSeqNo ? seqNo : L"") + pFieldLabels->at(i)).c_str()); } if (fieldCount > 0) Utils::setComboBoxSelection(hFieldList, fieldIndex < 0 ? 0 : fieldIndex); } void JumpToField::onJumpSeqNumPref() { _configIO.setPreferenceBool(PREF_JUMP_FIELD_SEQ, (IsDlgButtonChecked(_hSelf, IDC_JUMP_FIELD_PREF_SEQ_NUM) == BST_CHECKED)); loadJumpList(); } void JumpToField::onJumpBtnClick() { display(FALSE); _vizPanel.jumpToField(initFileType, initRecordRegIndex, static_cast<int>(SendMessage(hFieldList, CB_GETCURSEL, NULL, NULL))); } int JumpToField::getTbarPosition() const { return static_cast<int>(SendMessage(hCaretFlash, TBM_GETPOS, 0, 0)); } void JumpToField::setTbarPosition(int val, bool savePref) { SetDlgItemInt(_hSelf, IDC_JUMP_CARET_FLASH_VALUE, val, FALSE); if (savePref) _configIO.setPreferenceInt(PREF_CARET_FLASH, val); }
4,813
C++
.cpp
122
34.442623
142
0.706982
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,114
NppDarkMode.cpp
shriprem_FWDataViz/src/Darkmode/NppDarkMode.cpp
// This file is part of Notepad++ project // Copyright (C)2021 adzm / Adam D. Walling // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // at your option any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #include "NppDarkMode.h" #include "DarkMode.h" #include <dwmapi.h> #include <uxtheme.h> #include <vssym32.h> #include <shlwapi.h> #include <cmath> #include <cassert> #ifdef __GNUC__ #include <cmath> #define WINAPI_LAMBDA WINAPI #else #define WINAPI_LAMBDA #endif #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE #define DWMWA_USE_IMMERSIVE_DARK_MODE 20 #endif extern HWND nppHandle; namespace NppDarkMode { struct Brushes { HBRUSH background = nullptr; HBRUSH softerBackground = nullptr; HBRUSH hotBackground = nullptr; HBRUSH pureBackground = nullptr; HBRUSH errorBackground = nullptr; HBRUSH edgeBrush = nullptr; HBRUSH hotEdgeBrush = nullptr; HBRUSH disabledEdgeBrush = nullptr; Brushes(const Colors& colors) : background(::CreateSolidBrush(colors.background)) , softerBackground(::CreateSolidBrush(colors.softerBackground)) , hotBackground(::CreateSolidBrush(colors.hotBackground)) , pureBackground(::CreateSolidBrush(colors.pureBackground)) , errorBackground(::CreateSolidBrush(colors.errorBackground)) , edgeBrush(::CreateSolidBrush(colors.edge)) , hotEdgeBrush(::CreateSolidBrush(colors.hotEdge)) , disabledEdgeBrush(::CreateSolidBrush(colors.disabledEdge)) {} ~Brushes() { ::DeleteObject(background); background = nullptr; ::DeleteObject(softerBackground); softerBackground = nullptr; ::DeleteObject(hotBackground); hotBackground = nullptr; ::DeleteObject(pureBackground); pureBackground = nullptr; ::DeleteObject(errorBackground); errorBackground = nullptr; ::DeleteObject(edgeBrush); edgeBrush = nullptr; ::DeleteObject(hotEdgeBrush); hotEdgeBrush = nullptr; ::DeleteObject(disabledEdgeBrush); disabledEdgeBrush = nullptr; } void change(const Colors& colors) { ::DeleteObject(background); ::DeleteObject(softerBackground); ::DeleteObject(hotBackground); ::DeleteObject(pureBackground); ::DeleteObject(errorBackground); ::DeleteObject(edgeBrush); ::DeleteObject(hotEdgeBrush); ::DeleteObject(disabledEdgeBrush); background = ::CreateSolidBrush(colors.background); softerBackground = ::CreateSolidBrush(colors.softerBackground); hotBackground = ::CreateSolidBrush(colors.hotBackground); pureBackground = ::CreateSolidBrush(colors.pureBackground); errorBackground = ::CreateSolidBrush(colors.errorBackground); edgeBrush = ::CreateSolidBrush(colors.edge); hotEdgeBrush = ::CreateSolidBrush(colors.hotEdge); disabledEdgeBrush = ::CreateSolidBrush(colors.disabledEdge); } }; struct Pens { HPEN darkerTextPen = nullptr; HPEN edgePen = nullptr; HPEN hotEdgePen = nullptr; HPEN disabledEdgePen = nullptr; Pens(const Colors& colors) : darkerTextPen(::CreatePen(PS_SOLID, 1, colors.darkerText)) , edgePen(::CreatePen(PS_SOLID, 1, colors.edge)) , hotEdgePen(::CreatePen(PS_SOLID, 1, colors.hotEdge)) , disabledEdgePen(::CreatePen(PS_SOLID, 1, colors.disabledEdge)) {} ~Pens() { ::DeleteObject(darkerTextPen); darkerTextPen = nullptr; ::DeleteObject(edgePen); edgePen = nullptr; ::DeleteObject(hotEdgePen); hotEdgePen = nullptr; ::DeleteObject(disabledEdgePen); disabledEdgePen = nullptr; } void change(const Colors& colors) { ::DeleteObject(darkerTextPen); ::DeleteObject(edgePen); ::DeleteObject(hotEdgePen); ::DeleteObject(disabledEdgePen); darkerTextPen = ::CreatePen(PS_SOLID, 1, colors.darkerText); edgePen = ::CreatePen(PS_SOLID, 1, colors.edge); hotEdgePen = ::CreatePen(PS_SOLID, 1, colors.hotEdge); disabledEdgePen = ::CreatePen(PS_SOLID, 1, colors.disabledEdge); } }; // black (default) static const Colors darkColors{ HEXRGB(0x202020), // background HEXRGB(0x404040), // softerBackground HEXRGB(0x404040), // hotBackground HEXRGB(0x202020), // pureBackground HEXRGB(0xB00000), // errorBackground HEXRGB(0xE0E0E0), // textColor HEXRGB(0xC0C0C0), // darkerTextColor HEXRGB(0x808080), // disabledTextColor HEXRGB(0xFFFF00), // linkTextColor HEXRGB(0x646464), // edgeColor HEXRGB(0x9B9B9B), // hotEdgeColor HEXRGB(0x484848) // disabledEdgeColor }; struct Theme { Colors _colors; Brushes _brushes; Pens _pens; Theme(const Colors& colors) : _colors(colors) , _brushes(colors) , _pens(colors) {} void change(const Colors& colors) { _colors = colors; _brushes.change(colors); _pens.change(colors); } }; COLORREF intToRGB(int color) { return RGB(GetRValue(color), GetGValue(color), GetBValue(color)); } int scaleDPIX(int x) { HDC hdc = GetDC(NULL); if (!hdc) return 0; int scaleX{ MulDiv(x, GetDeviceCaps(hdc, LOGPIXELSX), 96) }; ReleaseDC(NULL, hdc); return scaleX; } int scaleDPIY(int y) { HDC hdc = GetDC(NULL); if (!hdc) return 0; int scaleY{ MulDiv(y, GetDeviceCaps(hdc, LOGPIXELSY), 96) }; ReleaseDC(NULL, hdc); return scaleY; } int nppMessage(UINT messageID, WPARAM wparam = 0, LPARAM lparam = 0) { return static_cast<int>(SendMessage(nppHandle, messageID, wparam, lparam)); } Theme tCurrent(darkColors); static boolean _isDarkModeEnabled; void queryNPPDarkmode() { _isDarkModeEnabled = static_cast<boolean>(nppMessage(NPPM_ISDARKMODEENABLED)); Colors customColors{}; nppMessage(NPPM_GETDARKMODECOLORS, sizeof(customColors), reinterpret_cast<LPARAM>(&customColors)); tCurrent.change(customColors); } void initDarkMode() { queryNPPDarkmode(); ::InitDarkMode(); ::SetDarkMode(_isDarkModeEnabled, true); } bool isEnabled() { return _isDarkModeEnabled; } bool isExperimentalSupported() { return g_darkModeSupported; } bool isWindows10() { return IsWindows10(); } bool isWindows11() { return IsWindows11(); } DWORD getWindowsBuildNumber() { return GetWindowsBuildNumber(); } COLORREF invertLightness(COLORREF c) { WORD h = 0; WORD s = 0; WORD l = 0; ColorRGBToHLS(c, &h, &l, &s); l = 240 - l; COLORREF invert_c = ColorHLSToRGB(h, l, s); return invert_c; } COLORREF invertLightnessSofter(COLORREF c) { WORD h = 0; WORD s = 0; WORD l = 0; ColorRGBToHLS(c, &h, &l, &s); l = min(240 - l, 211); COLORREF invert_c = ColorHLSToRGB(h, l, s); return invert_c; } TreeViewStyle treeViewStyle = TreeViewStyle::classic; COLORREF treeViewBg = intToRGB(static_cast<int>(nppMessage(NPPM_GETEDITORDEFAULTBACKGROUNDCOLOR))); double lightnessTreeView = 50.0; // adapted from https://stackoverflow.com/a/56678483 double calculatePerceivedLightness(COLORREF c) { auto linearValue = [](double colorChannel) -> double { colorChannel /= 255.0; if (colorChannel <= 0.04045) return colorChannel / 12.92; return std::pow(((colorChannel + 0.055) / 1.055), 2.4); }; double r = linearValue(static_cast<double>(GetRValue(c))); double g = linearValue(static_cast<double>(GetGValue(c))); double b = linearValue(static_cast<double>(GetBValue(c))); double luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b; double lighness = (luminance <= 216.0 / 24389.0) ? (luminance * 24389.0 / 27.0) : (std::pow(luminance, (1.0 / 3.0)) * 116.0 - 16.0); return lighness; } COLORREF getBackgroundColor() { return tCurrent._colors.background; } COLORREF getSofterBackgroundColor() { return tCurrent._colors.softerBackground; } COLORREF getHotBackgroundColor() { return tCurrent._colors.hotBackground; } COLORREF getDarkerBackgroundColor() { return tCurrent._colors.pureBackground; } COLORREF getErrorBackgroundColor() { return tCurrent._colors.errorBackground; } COLORREF getTextColor() { return tCurrent._colors.text; } COLORREF getDarkerTextColor() { return tCurrent._colors.darkerText; } COLORREF getDisabledTextColor() { return tCurrent._colors.disabledText; } COLORREF getLinkTextColor() { return tCurrent._colors.linkText; } COLORREF getEdgeColor() { return tCurrent._colors.edge; } COLORREF getHotEdgeColor() { return tCurrent._colors.hotEdge; } COLORREF getDisabledEdgeColor() { return tCurrent._colors.disabledEdge; } HBRUSH getBackgroundBrush() { return tCurrent._brushes.background; } HBRUSH getSofterBackgroundBrush() { return tCurrent._brushes.softerBackground; } HBRUSH getHotBackgroundBrush() { return tCurrent._brushes.hotBackground; } HBRUSH getDarkerBackgroundBrush() { return tCurrent._brushes.pureBackground; } HBRUSH getErrorBackgroundBrush() { return tCurrent._brushes.errorBackground; } HBRUSH getEdgeBrush() { return tCurrent._brushes.edgeBrush; } HBRUSH getHotEdgeBrush() { return tCurrent._brushes.hotEdgeBrush; } HBRUSH getDisabledEdgeBrush() { return tCurrent._brushes.disabledEdgeBrush; } HPEN getDarkerTextPen() { return tCurrent._pens.darkerTextPen; } HPEN getEdgePen() { return tCurrent._pens.edgePen; } HPEN getHotEdgePen() { return tCurrent._pens.hotEdgePen; } HPEN getDisabledEdgePen() { return tCurrent._pens.disabledEdgePen; } // from DarkMode.h void allowDarkModeForApp(bool allow) { ::AllowDarkModeForApp(allow); } bool allowDarkModeForWindow(HWND hWnd, bool allow) { return ::AllowDarkModeForWindow(hWnd, allow); } void setTitleBarThemeColor(HWND hWnd) { ::RefreshTitleBarThemeColor(hWnd); } void enableDarkScrollBarForWindowAndChildren(HWND hwnd) { ::EnableDarkScrollBarForWindowAndChildren(hwnd); } inline void paintRoundFrameRect(HDC hdc, const RECT rect, const HPEN hpen, int width, int height) { auto holdBrush = ::SelectObject(hdc, ::GetStockObject(NULL_BRUSH)); auto holdPen = ::SelectObject(hdc, hpen); ::RoundRect(hdc, rect.left, rect.top, rect.right, rect.bottom, width, height); ::SelectObject(hdc, holdBrush); ::SelectObject(hdc, holdPen); } struct ButtonData { HTHEME hTheme = nullptr; int iStateID = 0; ~ButtonData() { closeTheme(); } bool ensureTheme(HWND hwnd) { if (!hTheme) { hTheme = OpenThemeData(hwnd, L"Button"); } return hTheme != nullptr; } void closeTheme() { if (hTheme) { CloseThemeData(hTheme); hTheme = nullptr; } } }; void renderButton(HWND hwnd, HDC hdc, HTHEME hTheme, int iPartID, int iStateID) { RECT rcClient{}; WCHAR szText[256] = { '\0' }; DWORD nState = static_cast<DWORD>(SendMessage(hwnd, BM_GETSTATE, 0, 0)); DWORD uiState = static_cast<DWORD>(SendMessage(hwnd, WM_QUERYUISTATE, 0, 0)); DWORD nStyle = GetWindowLong(hwnd, GWL_STYLE); HFONT hFont = nullptr; HFONT hOldFont = nullptr; HFONT hCreatedFont = nullptr; LOGFONT lf {}; if (SUCCEEDED(GetThemeFont(hTheme, hdc, iPartID, iStateID, TMT_FONT, &lf))) { hCreatedFont = CreateFontIndirect(&lf); hFont = hCreatedFont; } if (!hFont) { hFont = reinterpret_cast<HFONT>(SendMessage(hwnd, WM_GETFONT, 0, 0)); } hOldFont = static_cast<HFONT>(SelectObject(hdc, hFont)); DWORD dtFlags = DT_LEFT; // DT_LEFT is 0 dtFlags |= (nStyle & BS_MULTILINE) ? DT_WORDBREAK : DT_SINGLELINE; dtFlags |= ((nStyle & BS_CENTER) == BS_CENTER) ? DT_CENTER : (nStyle & BS_RIGHT) ? DT_RIGHT : 0; dtFlags |= ((nStyle & BS_VCENTER) == BS_VCENTER) ? DT_VCENTER : (nStyle & BS_BOTTOM) ? DT_BOTTOM : 0; dtFlags |= (uiState & UISF_HIDEACCEL) ? DT_HIDEPREFIX : 0; if (!(nStyle & BS_MULTILINE) && !(nStyle & BS_BOTTOM) && !(nStyle & BS_TOP)) { dtFlags |= DT_VCENTER; } GetClientRect(hwnd, &rcClient); GetWindowText(hwnd, szText, _countof(szText)); SIZE szBox = { 13, 13 }; GetThemePartSize(hTheme, hdc, iPartID, iStateID, NULL, TS_DRAW, &szBox); RECT rcText = rcClient; GetThemeBackgroundContentRect(hTheme, hdc, iPartID, iStateID, &rcClient, &rcText); RECT rcBackground = rcClient; if (dtFlags & DT_SINGLELINE) { rcBackground.top += (rcText.bottom - rcText.top - szBox.cy) / 2; } rcBackground.bottom = rcBackground.top + szBox.cy; rcBackground.right = rcBackground.left + szBox.cx; rcText.left = rcBackground.right + 3; DrawThemeParentBackground(hwnd, hdc, &rcClient); DrawThemeBackground(hTheme, hdc, iPartID, iStateID, &rcBackground, nullptr); DTTOPTS dtto{}; dtto.dwSize = sizeof(DTTOPTS); dtto.dwFlags = DTT_TEXTCOLOR; dtto.crText = getTextColor(); if (nStyle & WS_DISABLED) { dtto.crText = getDisabledTextColor(); } DrawThemeTextEx(hTheme, hdc, iPartID, iStateID, szText, -1, dtFlags, &rcText, &dtto); if ((nState & BST_FOCUS) && !(uiState & UISF_HIDEFOCUS)) { RECT rcTextOut = rcText; dtto.dwFlags |= DTT_CALCRECT; DrawThemeTextEx(hTheme, hdc, iPartID, iStateID, szText, -1, dtFlags | DT_CALCRECT, &rcTextOut, &dtto); RECT rcFocus = rcTextOut; rcFocus.bottom++; rcFocus.left--; rcFocus.right++; DrawFocusRect(hdc, &rcFocus); } if (hCreatedFont) DeleteObject(hCreatedFont); SelectObject(hdc, hOldFont); } void paintButton(HWND hwnd, HDC hdc, ButtonData& buttonData) { DWORD nState = static_cast<DWORD>(SendMessage(hwnd, BM_GETSTATE, 0, 0)); const auto nStyle = GetWindowLongPtr(hwnd, GWL_STYLE); const auto nButtonStyle = nStyle & BS_TYPEMASK; int iPartID = BP_CHECKBOX; // Plugin might use BS_3STATE and BS_AUTO3STATE button style if (nButtonStyle == BS_CHECKBOX || nButtonStyle == BS_AUTOCHECKBOX || nButtonStyle == BS_3STATE || nButtonStyle == BS_AUTO3STATE) { iPartID = BP_CHECKBOX; } else if (nButtonStyle == BS_RADIOBUTTON || nButtonStyle == BS_AUTORADIOBUTTON) { iPartID = BP_RADIOBUTTON; } else { assert(false); } // states of BP_CHECKBOX and BP_RADIOBUTTON are the same int iStateID = RBS_UNCHECKEDNORMAL; if (nStyle & WS_DISABLED) iStateID = RBS_UNCHECKEDDISABLED; else if (nState & BST_PUSHED) iStateID = RBS_UNCHECKEDPRESSED; else if (nState & BST_HOT) iStateID = RBS_UNCHECKEDHOT; if (nState & BST_CHECKED) iStateID += 4; else if (nState & BST_INDETERMINATE) iStateID += 8; if (BufferedPaintRenderAnimation(hwnd, hdc)) { return; } BP_ANIMATIONPARAMS animParams{}; animParams.cbSize = sizeof(BP_ANIMATIONPARAMS); animParams.style = BPAS_LINEAR; if (iStateID != buttonData.iStateID) { GetThemeTransitionDuration(buttonData.hTheme, iPartID, buttonData.iStateID, iStateID, TMT_TRANSITIONDURATIONS, &animParams.dwDuration); } RECT rcClient {}; GetClientRect(hwnd, &rcClient); HDC hdcFrom = nullptr; HDC hdcTo = nullptr; HANIMATIONBUFFER hbpAnimation = BeginBufferedAnimation(hwnd, hdc, &rcClient, BPBF_COMPATIBLEBITMAP, nullptr, &animParams, &hdcFrom, &hdcTo); if (hbpAnimation) { if (hdcFrom) { renderButton(hwnd, hdcFrom, buttonData.hTheme, iPartID, buttonData.iStateID); } if (hdcTo) { renderButton(hwnd, hdcTo, buttonData.hTheme, iPartID, iStateID); } buttonData.iStateID = iStateID; EndBufferedAnimation(hbpAnimation, TRUE); } else { renderButton(hwnd, hdc, buttonData.hTheme, iPartID, iStateID); buttonData.iStateID = iStateID; } } constexpr UINT_PTR g_buttonSubclassID = 42; LRESULT CALLBACK ButtonSubclass( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData ) { UNREFERENCED_PARAMETER(uIdSubclass); auto pButtonData = reinterpret_cast<ButtonData*>(dwRefData); switch (uMsg) { case WM_UPDATEUISTATE: if (HIWORD(wParam) & (UISF_HIDEACCEL | UISF_HIDEFOCUS)) { InvalidateRect(hWnd, nullptr, FALSE); } break; case WM_NCDESTROY: RemoveWindowSubclass(hWnd, ButtonSubclass, g_buttonSubclassID); delete pButtonData; break; case WM_ERASEBKGND: if (isEnabled() && pButtonData->ensureTheme(hWnd)) { return TRUE; } else { break; } case WM_THEMECHANGED: pButtonData->closeTheme(); break; case WM_PRINTCLIENT: case WM_PAINT: if (isEnabled() && pButtonData->ensureTheme(hWnd)) { PAINTSTRUCT ps{}; HDC hdc = reinterpret_cast<HDC>(wParam); if (!hdc) { hdc = BeginPaint(hWnd, &ps); } paintButton(hWnd, hdc, *pButtonData); if (ps.hdc) { EndPaint(hWnd, &ps); } return 0; } else { break; } case WM_SIZE: case WM_DESTROY: BufferedPaintStopAllAnimations(hWnd); break; case WM_ENABLE: if (isEnabled()) { // skip the button's normal wndproc so it won't redraw out of wm_paint LRESULT lr = DefWindowProc(hWnd, uMsg, wParam, lParam); InvalidateRect(hWnd, nullptr, FALSE); return lr; } break; } return DefSubclassProc(hWnd, uMsg, wParam, lParam); } void subclassButtonControl(HWND hwnd) { DWORD_PTR pButtonData = reinterpret_cast<DWORD_PTR>(new ButtonData()); SetWindowSubclass(hwnd, ButtonSubclass, g_buttonSubclassID, pButtonData); } void paintGroupbox(HWND hwnd, HDC hdc, ButtonData& buttonData) { DWORD nStyle = GetWindowLong(hwnd, GWL_STYLE); bool isDisabled = (nStyle & WS_DISABLED) == WS_DISABLED; int iPartID = BP_GROUPBOX; int iStateID = isDisabled ? GBS_DISABLED : GBS_NORMAL; RECT rcClient{}; GetClientRect(hwnd, &rcClient); RECT rcText = rcClient; RECT rcBackground = rcClient; HFONT hFont = nullptr; HFONT hOldFont = nullptr; HFONT hCreatedFont = nullptr; LOGFONT lf = {}; if (SUCCEEDED(GetThemeFont(buttonData.hTheme, hdc, iPartID, iStateID, TMT_FONT, &lf))) { hCreatedFont = CreateFontIndirect(&lf); hFont = hCreatedFont; } if (!hFont) { hFont = reinterpret_cast<HFONT>(SendMessage(hwnd, WM_GETFONT, 0, 0)); } hOldFont = static_cast<HFONT>(::SelectObject(hdc, hFont)); WCHAR szText[256] = { '\0' }; GetWindowText(hwnd, szText, _countof(szText)); auto style = static_cast<long>(::GetWindowLongPtr(hwnd, GWL_STYLE)); bool isCenter = (style & BS_CENTER) == BS_CENTER; if (szText[0]) { SIZE textSize = {}; GetTextExtentPoint32(hdc, szText, static_cast<int>(wcslen(szText)), &textSize); int centerPosX = isCenter ? ((rcClient.right - rcClient.left - textSize.cx) / 2) : 7; rcBackground.top += textSize.cy / 2; rcText.left += centerPosX; rcText.bottom = rcText.top + textSize.cy; rcText.right = rcText.left + textSize.cx + 4; ExcludeClipRect(hdc, rcText.left, rcText.top, rcText.right, rcText.bottom); } else { SIZE textSize{}; GetTextExtentPoint32(hdc, L"M", 1, &textSize); rcBackground.top += textSize.cy / 2; } RECT rcContent = rcBackground; GetThemeBackgroundContentRect(buttonData.hTheme, hdc, BP_GROUPBOX, iStateID, &rcBackground, &rcContent); ExcludeClipRect(hdc, rcContent.left, rcContent.top, rcContent.right, rcContent.bottom); //DrawThemeParentBackground(hwnd, hdc, &rcClient); //DrawThemeBackground(buttonData.hTheme, hdc, BP_GROUPBOX, iStateID, &rcBackground, nullptr); paintRoundFrameRect(hdc, rcBackground, getEdgePen()); SelectClipRgn(hdc, nullptr); if (szText[0]) { rcText.right -= 2; rcText.left += 2; DTTOPTS dtto = { sizeof(DTTOPTS), DTT_TEXTCOLOR }; dtto.crText = isDisabled ? getDisabledTextColor() : getTextColor(); DWORD textFlags = isCenter ? DT_CENTER : DT_LEFT; DrawThemeTextEx(buttonData.hTheme, hdc, BP_GROUPBOX, iStateID, szText, -1, textFlags | DT_SINGLELINE, &rcText, &dtto); } if (hCreatedFont) DeleteObject(hCreatedFont); SelectObject(hdc, hOldFont); } constexpr UINT_PTR g_groupboxSubclassID = 42; LRESULT CALLBACK GroupboxSubclass( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData ) { UNREFERENCED_PARAMETER(uIdSubclass); auto pButtonData = reinterpret_cast<ButtonData*>(dwRefData); switch (uMsg) { case WM_NCDESTROY: RemoveWindowSubclass(hWnd, GroupboxSubclass, g_groupboxSubclassID); delete pButtonData; break; case WM_ERASEBKGND: if (isEnabled() && pButtonData->ensureTheme(hWnd)) { return TRUE; } else { break; } case WM_THEMECHANGED: pButtonData->closeTheme(); break; case WM_PRINTCLIENT: case WM_PAINT: if (isEnabled() && pButtonData->ensureTheme(hWnd)) { PAINTSTRUCT ps = { 0 }; HDC hdc = reinterpret_cast<HDC>(wParam); if (!hdc) { hdc = BeginPaint(hWnd, &ps); } paintGroupbox(hWnd, hdc, *pButtonData); if (ps.hdc) { EndPaint(hWnd, &ps); } return 0; } else { break; } break; } return DefSubclassProc(hWnd, uMsg, wParam, lParam); } void subclassGroupboxControl(HWND hwnd) { DWORD_PTR pButtonData = reinterpret_cast<DWORD_PTR>(new ButtonData()); SetWindowSubclass(hwnd, GroupboxSubclass, g_groupboxSubclassID, pButtonData); } constexpr UINT_PTR g_tabSubclassID = 42; LRESULT CALLBACK TabSubclass( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData ) { UNREFERENCED_PARAMETER(uIdSubclass); UNREFERENCED_PARAMETER(dwRefData); switch (uMsg) { case WM_PAINT: { if (!isEnabled()) { break; } LONG_PTR dwStyle = GetWindowLongPtr(hWnd, GWL_STYLE); if ((dwStyle & TCS_BUTTONS) || (dwStyle & TCS_VERTICAL)) { break; } PAINTSTRUCT ps; HDC hdc = ::BeginPaint(hWnd, &ps); ::FillRect(hdc, &ps.rcPaint, getDarkerBackgroundBrush()); auto holdPen = static_cast<HPEN>(::SelectObject(hdc, getEdgePen())); HRGN holdClip = CreateRectRgn(0, 0, 0, 0); if (1 != GetClipRgn(hdc, holdClip)) { DeleteObject(holdClip); holdClip = nullptr; } HFONT hFont = reinterpret_cast<HFONT>(SendMessage(hWnd, WM_GETFONT, 0, 0)); auto hOldFont = SelectObject(hdc, hFont); POINT ptCursor{}; ::GetCursorPos(&ptCursor); ScreenToClient(hWnd, &ptCursor); int nTabs = TabCtrl_GetItemCount(hWnd); int nSelTab = TabCtrl_GetCurSel(hWnd); for (int i = 0; i < nTabs; ++i) { RECT rcItem{}; TabCtrl_GetItemRect(hWnd, i, &rcItem); RECT rcFrame = rcItem; RECT rcIntersect{}; if (IntersectRect(&rcIntersect, &ps.rcPaint, &rcItem)) { bool bHot = PtInRect(&rcItem, ptCursor); bool isSelectedTab = (i == nSelTab); HRGN hClip = CreateRectRgnIndirect(&rcItem); SelectClipRgn(hdc, hClip); SetTextColor(hdc, (bHot || isSelectedTab) ? getTextColor() : getDarkerTextColor()); ::InflateRect(&rcItem, -1, -1); rcItem.right += 1; // for consistency getBackgroundBrush() // would be better, than getSofterBackgroundBrush(), // however default getBackgroundBrush() has same color // as getDarkerBackgroundBrush() ::FillRect(hdc, &rcItem, isSelectedTab ? getDarkerBackgroundBrush() : bHot ? getHotBackgroundBrush() : getSofterBackgroundBrush()); SetBkMode(hdc, TRANSPARENT); TCHAR label[MAX_PATH]{}; TCITEM tci{}; tci.mask = TCIF_TEXT; tci.pszText = label; tci.cchTextMax = MAX_PATH - 1; ::SendMessage(hWnd, TCM_GETITEM, i, reinterpret_cast<LPARAM>(&tci)); RECT rcText = rcItem; rcText.left += scaleDPIX(5); rcText.right -= scaleDPIX(3); if (isSelectedTab) { rcText.bottom -= scaleDPIY(4); ::InflateRect(&rcFrame, 0, 1); } if (i != nTabs - 1) { rcFrame.right += 1; } ::FrameRect(hdc, &rcFrame, getEdgeBrush()); DrawText(hdc, label, -1, &rcText, DT_LEFT | DT_VCENTER | DT_SINGLELINE); DeleteObject(hClip); SelectClipRgn(hdc, holdClip); } } SelectObject(hdc, hOldFont); SelectClipRgn(hdc, holdClip); if (holdClip) { DeleteObject(holdClip); holdClip = nullptr; } SelectObject(hdc, holdPen); EndPaint(hWnd, &ps); return 0; } case WM_NCDESTROY: { RemoveWindowSubclass(hWnd, TabSubclass, g_tabSubclassID); break; } case WM_PARENTNOTIFY: { switch (LOWORD(wParam)) { case WM_CREATE: { auto hwndUpdown = reinterpret_cast<HWND>(lParam); if (subclassUpDownControl(hwndUpdown)) { return 0; } break; } } return 0; } } return DefSubclassProc(hWnd, uMsg, wParam, lParam); } void subclassTabControl(HWND hwnd) { SetWindowSubclass(hwnd, TabSubclass, g_tabSubclassID, 0); } constexpr UINT_PTR g_customBorderSubclassID = 42; LRESULT CALLBACK CustomBorderSubclass( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData ) { UNREFERENCED_PARAMETER(dwRefData); static bool isHotStatic = false; switch (uMsg) { case WM_NCPAINT: { if (!isEnabled()) { break; } DefSubclassProc(hWnd, uMsg, wParam, lParam); HDC hdc = ::GetWindowDC(hWnd); RECT rcClient{}; ::GetClientRect(hWnd, &rcClient); rcClient.right += (2 * ::GetSystemMetrics(SM_CXEDGE)); auto style = ::GetWindowLongPtr(hWnd, GWL_STYLE); bool hasVerScrollbar = (style & WS_VSCROLL) == WS_VSCROLL; if (hasVerScrollbar) { rcClient.right += ::GetSystemMetrics(SM_CXVSCROLL); } rcClient.bottom += (2 * ::GetSystemMetrics(SM_CYEDGE)); bool hasHorScrollbar = (style & WS_HSCROLL) == WS_HSCROLL; if (hasHorScrollbar) { rcClient.bottom += ::GetSystemMetrics(SM_CYHSCROLL); } bool hasFocus = ::GetFocus() == hWnd; POINT ptCursor{}; ::GetCursorPos(&ptCursor); ::ScreenToClient(hWnd, &ptCursor); bool isHot = ::PtInRect(&rcClient, ptCursor); bool isWindowEnabled = ::IsWindowEnabled(hWnd) == TRUE; HPEN hEnabledPen = ((isHotStatic && isHot) || hasFocus ? getHotEdgePen() : getEdgePen()); paintRoundFrameRect(hdc, rcClient, isWindowEnabled ? hEnabledPen : getDisabledEdgePen()); ::ReleaseDC(hWnd, hdc); return 0; } break; case WM_NCCALCSIZE: { if (isEnabled()) { auto lpRect = reinterpret_cast<LPRECT>(lParam); ::InflateRect(lpRect, -(::GetSystemMetrics(SM_CXEDGE)), -(::GetSystemMetrics(SM_CYEDGE))); } } break; case WM_MOUSEMOVE: { if (!isEnabled()) { break; } if (::GetFocus() == hWnd) { break; } TRACKMOUSEEVENT tme{}; tme.cbSize = sizeof(TRACKMOUSEEVENT); tme.dwFlags = TME_LEAVE; tme.hwndTrack = hWnd; tme.dwHoverTime = HOVER_DEFAULT; TrackMouseEvent(&tme); if (!isHotStatic) { isHotStatic = true; ::SetWindowPos(hWnd, nullptr, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); } } break; case WM_MOUSELEAVE: { if (!isEnabled()) { break; } if (isHotStatic) { isHotStatic = false; ::SetWindowPos(hWnd, nullptr, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); } TRACKMOUSEEVENT tme{}; tme.cbSize = sizeof(TRACKMOUSEEVENT); tme.dwFlags = TME_LEAVE | TME_CANCEL; tme.hwndTrack = hWnd; tme.dwHoverTime = HOVER_DEFAULT; TrackMouseEvent(&tme); } break; case WM_NCDESTROY: { RemoveWindowSubclass(hWnd, CustomBorderSubclass, uIdSubclass); } break; } return DefSubclassProc(hWnd, uMsg, wParam, lParam); } void subclassCustomBorderForListBoxAndEditControls(HWND hwnd) { SetWindowSubclass(hwnd, CustomBorderSubclass, g_customBorderSubclassID, 0); } constexpr UINT_PTR g_comboBoxSubclassID = 42; LRESULT CALLBACK ComboBoxSubclass( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData ) { auto hwndEdit = reinterpret_cast<HWND>(dwRefData); switch (uMsg) { case WM_PAINT: { if (!isEnabled()) { break; } RECT rc{}; ::GetClientRect(hWnd, &rc); PAINTSTRUCT ps; auto hdc = ::BeginPaint(hWnd, &ps); ::SelectObject(hdc, reinterpret_cast<HFONT>(::SendMessage(hWnd, WM_GETFONT, 0, 0))); ::SetBkColor(hdc, getBackgroundColor()); auto holdBrush = ::SelectObject(hdc, getDarkerBackgroundBrush()); RECT rcArrow = {rc.right - scaleDPIX(17), rc.top + 1, rc.right - 1, rc.bottom - 1}; bool hasFocus{}; // CBS_DROPDOWN text is handled by parent by WM_CTLCOLOREDIT auto style = ::GetWindowLongPtr(hWnd, GWL_STYLE); if ((style & CBS_DROPDOWNLIST) == CBS_DROPDOWNLIST) { hasFocus = ::GetFocus() == hWnd; RECT rcTextBg = rc; rcTextBg.left += 1; rcTextBg.top += 1; rcTextBg.right = rcArrow.left - 1; rcTextBg.bottom -= 1; ::FillRect(hdc, &rcTextBg, getBackgroundBrush()); // erase background on item change auto index = static_cast<int>(::SendMessage(hWnd, CB_GETCURSEL, 0, 0)); if (index != CB_ERR) { ::SetTextColor(hdc, getTextColor()); ::SetBkColor(hdc, getBackgroundColor()); auto bufferLen = static_cast<size_t>(::SendMessage(hWnd, CB_GETLBTEXTLEN, index, 0)); TCHAR* buffer = new TCHAR[(bufferLen + 1)]; ::SendMessage(hWnd, CB_GETLBTEXT, index, reinterpret_cast<LPARAM>(buffer)); RECT rcText = rc; rcText.left += 4; rcText.right = rcArrow.left - 5; ::DrawText(hdc, buffer, -1, &rcText, DT_NOPREFIX | DT_LEFT | DT_VCENTER | DT_SINGLELINE); delete[]buffer; } } else if ((style & CBS_DROPDOWN) == CBS_DROPDOWN && hwndEdit != NULL) { hasFocus = ::GetFocus() == hwndEdit; } POINT ptCursor{}; ::GetCursorPos(&ptCursor); ScreenToClient(hWnd, &ptCursor); bool isHot = PtInRect(&rc, ptCursor); bool isWindowEnabled = ::IsWindowEnabled(hWnd) == TRUE; auto colorEnabledText = isHot ? getTextColor() : getDarkerTextColor(); ::SetTextColor(hdc, isWindowEnabled ? colorEnabledText : getDisabledTextColor()); ::SetBkColor(hdc, isHot ? getHotBackgroundColor() : getBackgroundColor()); ::ExtTextOut(hdc, rcArrow.left + (rcArrow.right - rcArrow.left) / 2 - scaleDPIX(4), rcArrow.top + 3, ETO_OPAQUE | ETO_CLIPPED, &rcArrow, L"˅", 1, nullptr); ::SetBkColor(hdc, getBackgroundColor()); auto hEnabledPen = (isHot || hasFocus) ? getHotEdgePen() : getEdgePen(); auto hSelectedPen = isWindowEnabled ? hEnabledPen : getDisabledEdgePen(); auto holdPen = static_cast<HPEN>(::SelectObject(hdc, hSelectedPen)); POINT edge[] = { {rcArrow.left - 1, rcArrow.top}, {rcArrow.left - 1, rcArrow.bottom} }; ::Polyline(hdc, edge, _countof(edge)); int roundCornerValue = isWindows11() ? scaleDPIX(4) : 0; paintRoundFrameRect(hdc, rc, hSelectedPen, roundCornerValue, roundCornerValue); ::SelectObject(hdc, holdPen); ::SelectObject(hdc, holdBrush); ::EndPaint(hWnd, &ps); return 0; } case WM_NCDESTROY: { ::RemoveWindowSubclass(hWnd, ComboBoxSubclass, uIdSubclass); break; } } return DefSubclassProc(hWnd, uMsg, wParam, lParam); } void subclassComboBoxControl(HWND hwnd) { DWORD_PTR hwndEditData = 0; auto style = ::GetWindowLongPtr(hwnd, GWL_STYLE); if ((style & CBS_DROPDOWN) == CBS_DROPDOWN) { POINT pt = { 5, 5 }; hwndEditData = reinterpret_cast<DWORD_PTR>(::ChildWindowFromPoint(hwnd, pt)); } SetWindowSubclass(hwnd, ComboBoxSubclass, g_comboBoxSubclassID, hwndEditData); } constexpr UINT_PTR g_listViewSubclassID = 42; LRESULT CALLBACK ListViewSubclass( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData ) { UNREFERENCED_PARAMETER(dwRefData); switch (uMsg) { case WM_NCDESTROY: { ::RemoveWindowSubclass(hWnd, ListViewSubclass, uIdSubclass); break; } case WM_NOTIFY: { switch (reinterpret_cast<LPNMHDR>(lParam)->code) { case NM_CUSTOMDRAW: { auto lpnmcd = reinterpret_cast<LPNMCUSTOMDRAW>(lParam); switch (lpnmcd->dwDrawStage) { case CDDS_PREPAINT: { if (isExperimentalSupported() && isEnabled()) { return CDRF_NOTIFYITEMDRAW; } return CDRF_DODEFAULT; } case CDDS_ITEMPREPAINT: { SetTextColor(lpnmcd->hdc, getDarkerTextColor()); return CDRF_NEWFONT; } default: return CDRF_DODEFAULT; } } break; } break; } break; } return DefSubclassProc(hWnd, uMsg, wParam, lParam); } void subclassListViewControl(HWND hwnd) { SetWindowSubclass(hwnd, ListViewSubclass, g_listViewSubclassID, 0); } void autoSubclassAndThemeChildControls(HWND hwndParent, bool subclass, bool theme) { struct Params { const wchar_t* themeClassName = nullptr; bool subclass = false; bool theme = false; }; Params p{ isEnabled() ? L"DarkMode_Explorer" : nullptr , subclass , theme }; ::EnableThemeDialogTexture(hwndParent, theme && !isEnabled() ? ETDT_ENABLETAB : ETDT_DISABLE); EnumChildWindows(hwndParent, [](HWND hwnd, LPARAM lParam) WINAPI_LAMBDA{ auto& p = *reinterpret_cast<Params*>(lParam); const size_t classNameLen = 16; TCHAR className[classNameLen] {}; GetClassName(hwnd, className, classNameLen); if (wcscmp(className, WC_COMBOBOX) == 0) { auto style = ::GetWindowLongPtr(hwnd, GWL_STYLE); if ((style & CBS_DROPDOWNLIST) == CBS_DROPDOWNLIST || (style & CBS_DROPDOWN) == CBS_DROPDOWN) { COMBOBOXINFO cbi = {}; cbi.cbSize = sizeof(COMBOBOXINFO); BOOL result = GetComboBoxInfo(hwnd, &cbi); if (result == TRUE) { if (p.theme && cbi.hwndList) { //dark scrollbar for listbox of combobox SetWindowTheme(cbi.hwndList, p.themeClassName, nullptr); } } subclassComboBoxControl(hwnd); } return TRUE; } if (wcscmp(className, WC_LISTBOX) == 0) { if (p.theme) { //dark scrollbar for listbox SetWindowTheme(hwnd, p.themeClassName, nullptr); } auto style = ::GetWindowLongPtr(hwnd, GWL_STYLE); bool isComboBox = (style & LBS_COMBOBOX) == LBS_COMBOBOX; auto exStyle = ::GetWindowLongPtr(hwnd, GWL_EXSTYLE); bool hasClientEdge = (exStyle & WS_EX_CLIENTEDGE) == WS_EX_CLIENTEDGE; if (p.subclass && !isComboBox && hasClientEdge) { subclassCustomBorderForListBoxAndEditControls(hwnd); } #ifndef __MINGW64__ // mingw build for 64 bit has issue with GetWindowSubclass, it is undefined bool changed = false; if (::GetWindowSubclass(hwnd, CustomBorderSubclass, g_customBorderSubclassID, nullptr) == TRUE) { if (isEnabled()) { if (hasClientEdge) { ::SetWindowLongPtr(hwnd, GWL_EXSTYLE, exStyle & ~WS_EX_CLIENTEDGE); changed = true; } } else if (!hasClientEdge) { ::SetWindowLongPtr(hwnd, GWL_EXSTYLE, exStyle | WS_EX_CLIENTEDGE); changed = true; } } if (changed) { ::SetWindowPos(hwnd, nullptr, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); } #endif // !__MINGW64__ return TRUE; } if (wcscmp(className, WC_EDIT) == 0) { auto style = ::GetWindowLongPtr(hwnd, GWL_STYLE); bool hasScrollBar = ((style & WS_HSCROLL) == WS_HSCROLL) || ((style & WS_VSCROLL) == WS_VSCROLL); if (p.theme && hasScrollBar) { //dark scrollbar for edit control SetWindowTheme(hwnd, p.themeClassName, nullptr); } auto exStyle = ::GetWindowLongPtr(hwnd, GWL_EXSTYLE); bool hasClientEdge = (exStyle & WS_EX_CLIENTEDGE) == WS_EX_CLIENTEDGE; if (p.subclass && hasClientEdge) { subclassCustomBorderForListBoxAndEditControls(hwnd); } #ifndef __MINGW64__ // mingw build for 64 bit has issue with GetWindowSubclass, it is undefined bool changed = false; if (::GetWindowSubclass(hwnd, CustomBorderSubclass, g_customBorderSubclassID, nullptr) == TRUE) { if (isEnabled()) { if (hasClientEdge) { ::SetWindowLongPtr(hwnd, GWL_EXSTYLE, exStyle & ~WS_EX_CLIENTEDGE); changed = true; } } else if (!hasClientEdge) { ::SetWindowLongPtr(hwnd, GWL_EXSTYLE, exStyle | WS_EX_CLIENTEDGE); changed = true; } } if (changed) { ::SetWindowPos(hwnd, nullptr, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); } #endif // !__MINGW64__ return TRUE; } if (wcscmp(className, WC_BUTTON) == 0) { auto nButtonStyle = ::GetWindowLongPtr(hwnd, GWL_STYLE); switch (nButtonStyle & BS_TYPEMASK) { case BS_CHECKBOX: case BS_AUTOCHECKBOX: case BS_3STATE: case BS_AUTO3STATE: case BS_RADIOBUTTON: case BS_AUTORADIOBUTTON: { if ((nButtonStyle & BS_PUSHLIKE) == BS_PUSHLIKE) { if (p.theme) { SetWindowTheme(hwnd, p.themeClassName, nullptr); } break; } if (IsWindows11() && p.theme) { SetWindowTheme(hwnd, p.themeClassName, nullptr); } if (p.subclass) { subclassButtonControl(hwnd); } break; } case BS_GROUPBOX: { if (p.subclass) { subclassGroupboxControl(hwnd); } break; } case BS_PUSHBUTTON: case BS_DEFPUSHBUTTON: case BS_SPLITBUTTON: case BS_DEFSPLITBUTTON: { if (p.theme) { SetWindowTheme(hwnd, p.themeClassName, nullptr); } break; } default: { break; } } } if (wcscmp(className, TOOLBARCLASSNAME) == 0) { setDarkLineAbovePanelToolbar(hwnd); setDarkTooltips(hwnd, ToolTipsType::toolbar); return TRUE; } if (wcscmp(className, WC_LISTVIEW) == 0) { setDarkListView(hwnd); setDarkTooltips(hwnd, ToolTipsType::listview); int fgColor{ static_cast<int>(nppMessage(NPPM_GETEDITORDEFAULTFOREGROUNDCOLOR)) }; int bgColor{ static_cast<int>(nppMessage(NPPM_GETEDITORDEFAULTBACKGROUNDCOLOR)) }; ListView_SetTextColor(hwnd, fgColor); ListView_SetTextBkColor(hwnd, bgColor); ListView_SetBkColor(hwnd, bgColor); if (p.subclass) { auto exStyle = ListView_GetExtendedListViewStyle(hwnd); ListView_SetExtendedListViewStyle(hwnd, exStyle | LVS_EX_DOUBLEBUFFER); subclassListViewControl(hwnd); } return TRUE; } if (wcscmp(className, WC_TREEVIEW) == 0) { int fgColor{ static_cast<int>(nppMessage(NPPM_GETEDITORDEFAULTFOREGROUNDCOLOR)) }; int bgColor{ static_cast<int>(nppMessage(NPPM_GETEDITORDEFAULTBACKGROUNDCOLOR)) }; TreeView_SetTextColor(hwnd, fgColor); TreeView_SetBkColor(hwnd, bgColor); calculateTreeViewStyle(); setTreeViewStyle(hwnd); setDarkTooltips(hwnd, ToolTipsType::treeview); return TRUE; } // Plugin might use rich edit control version 2.0 and later if (wcscmp(className, L"RichEdit20W") == 0 || wcscmp(className, L"RICHEDIT50W") == 0) { if (p.theme) { //dark scrollbar for rich edit control SetWindowTheme(hwnd, p.themeClassName, nullptr); } return TRUE; } if (wcscmp(className, UPDOWN_CLASS) == 0) { subclassUpDownControl(hwnd); return TRUE; } return TRUE; }, reinterpret_cast<LPARAM>(&p)); } LRESULT darkToolBarNotifyCustomDraw(LPARAM lParam) { auto nmtbcd = reinterpret_cast<LPNMTBCUSTOMDRAW>(lParam); static int roundCornerValue = 0; switch (nmtbcd->nmcd.dwDrawStage) { case CDDS_PREPAINT: { if (isEnabled()) { roundCornerValue = isWindows11() ? scaleDPIX(5) : 0; ::FillRect(nmtbcd->nmcd.hdc, &nmtbcd->nmcd.rc, getDarkerBackgroundBrush()); return CDRF_NOTIFYITEMDRAW; } return CDRF_DODEFAULT; } case CDDS_ITEMPREPAINT: { nmtbcd->hbrLines = getEdgeBrush(); nmtbcd->clrText = getTextColor(); nmtbcd->clrTextHighlight = getTextColor(); nmtbcd->clrBtnFace = getBackgroundColor(); nmtbcd->clrBtnHighlight = getSofterBackgroundColor(); nmtbcd->clrHighlightHotTrack = getHotBackgroundColor(); nmtbcd->nStringBkMode = TRANSPARENT; nmtbcd->nHLStringBkMode = TRANSPARENT; if ((nmtbcd->nmcd.uItemState & CDIS_CHECKED) == CDIS_CHECKED) { auto holdBrush = ::SelectObject(nmtbcd->nmcd.hdc, getSofterBackgroundBrush()); auto holdPen = ::SelectObject(nmtbcd->nmcd.hdc, getEdgePen()); ::RoundRect(nmtbcd->nmcd.hdc, nmtbcd->nmcd.rc.left, nmtbcd->nmcd.rc.top, nmtbcd->nmcd.rc.right, nmtbcd->nmcd.rc.bottom, roundCornerValue, roundCornerValue); ::SelectObject(nmtbcd->nmcd.hdc, holdBrush); ::SelectObject(nmtbcd->nmcd.hdc, holdPen); nmtbcd->nmcd.uItemState &= ~CDIS_CHECKED; } return TBCDRF_HILITEHOTTRACK | TBCDRF_USECDCOLORS | CDRF_NOTIFYPOSTPAINT; } case CDDS_ITEMPOSTPAINT: { bool isDropDown = false; auto exStyle = ::SendMessage(nmtbcd->nmcd.hdr.hwndFrom, TB_GETEXTENDEDSTYLE, 0, 0); if ((exStyle & TBSTYLE_EX_DRAWDDARROWS) == TBSTYLE_EX_DRAWDDARROWS) { TBBUTTONINFO tbButtonInfo{}; tbButtonInfo.cbSize = sizeof(TBBUTTONINFO); tbButtonInfo.dwMask = TBIF_STYLE; ::SendMessage(nmtbcd->nmcd.hdr.hwndFrom, TB_GETBUTTONINFO, nmtbcd->nmcd.dwItemSpec, reinterpret_cast<LPARAM>(&tbButtonInfo)); isDropDown = (tbButtonInfo.fsStyle & BTNS_DROPDOWN) == BTNS_DROPDOWN; } if (!isDropDown && (nmtbcd->nmcd.uItemState & CDIS_HOT) == CDIS_HOT) { paintRoundFrameRect(nmtbcd->nmcd.hdc, nmtbcd->nmcd.rc, getHotEdgePen(), roundCornerValue, roundCornerValue); } return CDRF_DODEFAULT; } default: return CDRF_DODEFAULT; } } LRESULT darkListViewNotifyCustomDraw(LPARAM lParam) { auto lplvcd = reinterpret_cast<LPNMLVCUSTOMDRAW>(lParam); switch (lplvcd->nmcd.dwDrawStage) { case CDDS_PREPAINT: { return CDRF_NOTIFYITEMDRAW; } case CDDS_ITEMPREPAINT: { auto isSelected = ListView_GetItemState(lplvcd->nmcd.hdr.hwndFrom, lplvcd->nmcd.dwItemSpec, LVIS_SELECTED) == LVIS_SELECTED; if (isEnabled()) { if (isSelected) { lplvcd->clrText = getTextColor(); lplvcd->clrTextBk = getSofterBackgroundColor(); ::FillRect(lplvcd->nmcd.hdc, &lplvcd->nmcd.rc, getSofterBackgroundBrush()); } else if ((lplvcd->nmcd.uItemState & CDIS_HOT) == CDIS_HOT) { lplvcd->clrText = getTextColor(); lplvcd->clrTextBk = getHotBackgroundColor(); ::FillRect(lplvcd->nmcd.hdc, &lplvcd->nmcd.rc, getHotBackgroundBrush()); } } if (isSelected) { ::DrawFocusRect(lplvcd->nmcd.hdc, &lplvcd->nmcd.rc); } return CDRF_NEWFONT; } default: return CDRF_DODEFAULT; } } LRESULT darkTreeViewNotifyCustomDraw(LPARAM lParam) { auto lptvcd = reinterpret_cast<LPNMTVCUSTOMDRAW>(lParam); switch (lptvcd->nmcd.dwDrawStage) { case CDDS_PREPAINT: { if (isEnabled()) { return CDRF_NOTIFYITEMDRAW; } return CDRF_DODEFAULT; } case CDDS_ITEMPREPAINT: { if ((lptvcd->nmcd.uItemState & CDIS_SELECTED) == CDIS_SELECTED) { lptvcd->clrText = getTextColor(); lptvcd->clrTextBk = getSofterBackgroundColor(); ::FillRect(lptvcd->nmcd.hdc, &lptvcd->nmcd.rc, getSofterBackgroundBrush()); return CDRF_NEWFONT | CDRF_NOTIFYPOSTPAINT; } if ((lptvcd->nmcd.uItemState & CDIS_HOT) == CDIS_HOT) { lptvcd->clrText = getTextColor(); lptvcd->clrTextBk = getHotBackgroundColor(); ::FillRect(lptvcd->nmcd.hdc, &lptvcd->nmcd.rc, getHotBackgroundBrush()); return CDRF_NEWFONT | CDRF_NOTIFYPOSTPAINT; } return CDRF_DODEFAULT; } case CDDS_ITEMPOSTPAINT: { RECT rcFrame = lptvcd->nmcd.rc; rcFrame.left -= 1; rcFrame.right += 1; if ((lptvcd->nmcd.uItemState & CDIS_HOT) == CDIS_HOT) { paintRoundFrameRect(lptvcd->nmcd.hdc, rcFrame, getHotEdgePen(), 0, 0); } else if ((lptvcd->nmcd.uItemState & CDIS_SELECTED) == CDIS_SELECTED) { paintRoundFrameRect(lptvcd->nmcd.hdc, rcFrame, getEdgePen(), 0, 0); } return CDRF_DODEFAULT; } default: return CDRF_DODEFAULT; } } void autoThemeChildControls(HWND hwndParent) { autoSubclassAndThemeChildControls(hwndParent, false, true); } constexpr UINT_PTR g_tabUpDownSubclassID = 42; LRESULT CALLBACK UpDownSubclass( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData ) { auto pButtonData = reinterpret_cast<ButtonData*>(dwRefData); auto style = ::GetWindowLongPtr(hWnd, GWL_STYLE); switch (uMsg) { case WM_PRINTCLIENT: case WM_PAINT: { if (!isEnabled()) { break; } bool hasTheme = pButtonData->ensureTheme(hWnd); RECT rcClient{}; ::GetClientRect(hWnd, &rcClient); PAINTSTRUCT ps{}; auto hdc = ::BeginPaint(hWnd, &ps); auto holdPen = static_cast<HPEN>(::SelectObject(hdc, getEdgePen())); ::FillRect(hdc, &rcClient, getDarkerBackgroundBrush()); RECT rcArrowUp{}; RECT rcArrowDown{}; if ((style & UDS_HORZ) == UDS_HORZ) { rcArrowUp = { rcClient.left, rcClient.top, rcClient.right - ((rcClient.right - rcClient.left) / 2) , rcClient.bottom }; rcArrowDown = { rcArrowUp.right, rcClient.top, rcClient.right, rcClient.bottom }; } else { rcArrowUp = { rcClient.left, rcClient.top, rcClient.right, rcClient.bottom - ((rcClient.bottom - rcClient.top) / 2) }; rcArrowDown = { rcClient.left, rcArrowUp.bottom, rcClient.right, rcArrowUp.bottom + ((rcClient.bottom - rcClient.top) / 2) }; } POINT ptCursor = {}; ::GetCursorPos(&ptCursor); ::ScreenToClient(hWnd, &ptCursor); bool isHotUp = ::PtInRect(&rcArrowUp, ptCursor); bool isHotDown = ::PtInRect(&rcArrowDown, ptCursor); if (isHotDown) isHotUp = false; ::SetBkMode(hdc, TRANSPARENT); if (hasTheme) { int roundCornerValue = isWindows11() ? scaleDPIX(4) : 0; holdPen = static_cast<HPEN>(::SelectObject(hdc, getEdgePen())); paintRoundFrameRect(hdc, rcArrowUp, getEdgePen(), roundCornerValue, roundCornerValue); paintRoundFrameRect(hdc, rcArrowDown, getEdgePen(), roundCornerValue, roundCornerValue); } else { ::FillRect(hdc, &rcArrowUp, isHotUp ? getHotBackgroundBrush() : getBackgroundBrush()); ::FillRect(hdc, &rcArrowDown, isHotDown ? getHotBackgroundBrush() : getBackgroundBrush()); } LOGFONT lf{}; auto font = reinterpret_cast<HFONT>(SendMessage(hWnd, WM_GETFONT, 0, 0)); ::GetObject(font, sizeof(lf), &lf); lf.lfHeight = (scaleDPIY(16) - 5) * -1; lf.lfWeight = 900; auto holdFont = static_cast<HFONT>(::SelectObject(hdc, CreateFontIndirect(&lf))); if ((style & UDS_HORZ) == UDS_HORZ) { auto mPosX = ((rcArrowUp.right - rcArrowUp.left - scaleDPIX(7) + 1) / 2); auto mPosY = ((rcArrowUp.bottom - rcArrowUp.top + lf.lfHeight - scaleDPIY(1) - 3) / 2); ::SetTextColor(hdc, isHotUp ? getTextColor() : getDarkerTextColor()); ::ExtTextOut(hdc, rcArrowUp.left + mPosX, rcArrowUp.top + mPosY, ETO_CLIPPED, &rcArrowUp, L"<", 1, nullptr); ::SetTextColor(hdc, isHotDown ? getTextColor() : getDarkerTextColor()); ::ExtTextOut(hdc, rcArrowDown.left + mPosX - scaleDPIX(2) + 3, rcArrowDown.top + mPosY, ETO_CLIPPED, &rcArrowDown, L">", 1, nullptr); } else { auto mPosX = scaleDPIX(4); ::SetTextColor(hdc, isHotUp ? getTextColor() : getDarkerTextColor()); ::ExtTextOut(hdc, rcArrowUp.left + mPosX, rcArrowUp.top + scaleDPIX(2), ETO_CLIPPED, &rcArrowUp, L"˄", 1, nullptr); ::SetTextColor(hdc, isHotDown ? getTextColor() : getDarkerTextColor()); ::ExtTextOut(hdc, rcArrowDown.left + mPosX, rcArrowDown.top, ETO_CLIPPED, &rcArrowDown, L"˅", 1, nullptr); } if (!hasTheme) { auto holdBrush = ::SelectObject(hdc, ::GetStockObject(NULL_BRUSH)); ::Rectangle(hdc, rcArrowUp.left, rcArrowUp.top, rcArrowUp.right, rcArrowUp.bottom); ::Rectangle(hdc, rcArrowDown.left, rcArrowDown.top, rcArrowDown.right, rcArrowDown.bottom); ::SelectObject(hdc, holdBrush); } ::SelectObject(hdc, holdPen); ::SelectObject(hdc, holdFont); ::EndPaint(hWnd, &ps); return FALSE; } case WM_THEMECHANGED: { pButtonData->closeTheme(); break; } case WM_NCDESTROY: { ::RemoveWindowSubclass(hWnd, UpDownSubclass, uIdSubclass); delete pButtonData; break; } case WM_ERASEBKGND: { if (isEnabled()) { RECT rcClient{}; ::GetClientRect(hWnd, &rcClient); ::FillRect(reinterpret_cast<HDC>(wParam), &rcClient, getDarkerBackgroundBrush()); return TRUE; } break; } } return DefSubclassProc(hWnd, uMsg, wParam, lParam); } bool subclassUpDownControl(HWND hwnd) { constexpr size_t classNameLen = 16; TCHAR className[classNameLen]{}; GetClassName(hwnd, className, classNameLen); if (wcscmp(className, UPDOWN_CLASS) == 0) { auto pButtonData = reinterpret_cast<DWORD_PTR>(new ButtonData()); SetWindowSubclass(hwnd, UpDownSubclass, g_tabUpDownSubclassID, pButtonData); setDarkExplorerTheme(hwnd); return true; } return false; } void setDarkTitleBar(HWND hwnd) { constexpr DWORD win10Build2004 = 19041; if (NppDarkMode::getWindowsBuildNumber() >= win10Build2004) { BOOL value = NppDarkMode::isEnabled() ? TRUE : FALSE; DwmSetWindowAttribute(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &value, sizeof(value)); } else { allowDarkModeForWindow(hwnd, isEnabled()); setTitleBarThemeColor(hwnd); } } void setDarkExplorerTheme(HWND hwnd) { SetWindowTheme(hwnd, isEnabled() ? L"DarkMode_Explorer" : nullptr, nullptr); } void setDarkScrollBar(HWND hwnd) { setDarkExplorerTheme(hwnd); } void setDarkTooltips(HWND hwnd, ToolTipsType type) { UINT msg = 0; switch (type) { case ToolTipsType::toolbar: msg = TB_GETTOOLTIPS; break; case ToolTipsType::listview: msg = LVM_GETTOOLTIPS; break; case ToolTipsType::treeview: msg = TVM_GETTOOLTIPS; break; case ToolTipsType::tabbar: msg = TCM_GETTOOLTIPS; break; default: msg = 0; break; } if (msg == 0) { setDarkExplorerTheme(hwnd); } else { auto hTips = reinterpret_cast<HWND>(::SendMessage(hwnd, msg, 0, 0)); if (hTips != nullptr) { setDarkExplorerTheme(hTips); } } } void setDarkLineAbovePanelToolbar(HWND hwnd) { COLORSCHEME scheme{}; scheme.dwSize = sizeof(COLORSCHEME); if (isEnabled()) { scheme.clrBtnHighlight = getDarkerBackgroundColor(); scheme.clrBtnShadow = getDarkerBackgroundColor(); } else { scheme.clrBtnHighlight = CLR_DEFAULT; scheme.clrBtnShadow = CLR_DEFAULT; } ::SendMessage(hwnd, TB_SETCOLORSCHEME, 0, reinterpret_cast<LPARAM>(&scheme)); } void setDarkListView(HWND hwnd) { if (isExperimentalSupported()) { bool useDark = isEnabled(); HWND hHeader = ListView_GetHeader(hwnd); allowDarkModeForWindow(hHeader, useDark); SetWindowTheme(hHeader, useDark ? L"ItemsView" : nullptr, nullptr); allowDarkModeForWindow(hwnd, useDark); SetWindowTheme(hwnd, L"Explorer", nullptr); } } void disableVisualStyle(HWND hwnd, bool doDisable) { if (doDisable) { SetWindowTheme(hwnd, L"", L""); } else { SetWindowTheme(hwnd, nullptr, nullptr); } } // range to determine when it should be better to use classic style constexpr double middleGrayRange = 2.0; void calculateTreeViewStyle() { COLORREF bgColor{};// = NppParameters::getInstance().getCurrentDefaultBgColor(); if (treeViewBg != bgColor || lightnessTreeView == 50.0) { lightnessTreeView = calculatePerceivedLightness(bgColor); treeViewBg = bgColor; } if (lightnessTreeView < (50.0 - middleGrayRange)) { treeViewStyle = TreeViewStyle::dark; } else if (lightnessTreeView > (50.0 + middleGrayRange)) { treeViewStyle = TreeViewStyle::light; } else { treeViewStyle = TreeViewStyle::classic; } } void setTreeViewStyle(HWND hwnd) { auto style = static_cast<long>(::GetWindowLongPtr(hwnd, GWL_STYLE)); bool hasHotStyle = (style & TVS_TRACKSELECT) == TVS_TRACKSELECT; bool change = false; switch (treeViewStyle) { case TreeViewStyle::light: { if (!hasHotStyle) { style |= TVS_TRACKSELECT; change = true; } SetWindowTheme(hwnd, L"Explorer", nullptr); break; } case TreeViewStyle::dark: { if (!hasHotStyle) { style |= TVS_TRACKSELECT; change = true; } SetWindowTheme(hwnd, L"DarkMode_Explorer", nullptr); break; } default: { if (hasHotStyle) { style &= ~TVS_TRACKSELECT; change = true; } SetWindowTheme(hwnd, nullptr, nullptr); break; } } if (change) { ::SetWindowLongPtr(hwnd, GWL_STYLE, style); } } void setBorder(HWND hwnd, bool border) { auto style = static_cast<long>(::GetWindowLongPtr(hwnd, GWL_STYLE)); bool hasBorder = (style & WS_BORDER) == WS_BORDER; bool change = false; if (!hasBorder && border) { style |= WS_BORDER; change = true; } else if (hasBorder && !border) { style &= ~WS_BORDER; change = true; } if (change) { ::SetWindowLongPtr(hwnd, GWL_STYLE, style); ::SetWindowPos(hwnd, nullptr, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); } } void initSysLink(HWND hCtl) { LITEM item = { 0 }; item.iLink = 0; item.mask = LIF_ITEMINDEX | LIF_STATE; item.state = LIS_DEFAULTCOLORS; item.stateMask = LIS_DEFAULTCOLORS; SendMessage(hCtl, LM_SETITEM, 0, (LPARAM)&item); } LRESULT onCtlColor(HDC hdc) { ::SetTextColor(hdc, getTextColor()); ::SetBkColor(hdc, getBackgroundColor()); return reinterpret_cast<LRESULT>(getBackgroundBrush()); } LRESULT onCtlColorSofter(HDC hdc) { ::SetTextColor(hdc, getTextColor()); ::SetBkColor(hdc, getSofterBackgroundColor()); return reinterpret_cast<LRESULT>(getSofterBackgroundBrush()); } LRESULT onCtlColorDarker(HDC hdc) { ::SetTextColor(hdc, getTextColor()); ::SetBkColor(hdc, getDarkerBackgroundColor()); return reinterpret_cast<LRESULT>(getDarkerBackgroundBrush()); } LRESULT onCtlColorError(HDC hdc) { ::SetTextColor(hdc, getTextColor()); ::SetBkColor(hdc, getErrorBackgroundColor()); return reinterpret_cast<LRESULT>(getErrorBackgroundBrush()); } LRESULT onCtlColorSysLink(HDC hdc) { if (isEnabled()) { SetTextColor(hdc, getLinkTextColor()); SetBkColor(hdc, getBackgroundColor()); return reinterpret_cast<LRESULT>(getBackgroundBrush()); } else { SetTextColor(hdc, GetSysColor(COLOR_HIGHLIGHT)); return FALSE; } } LRESULT onCtlColorIfEnabled(HDC hdc, bool bEnabled) { LRESULT result{ FALSE }; if (isEnabled()) { result = onCtlColorDarker(hdc); SetTextColor(hdc, bEnabled ? getTextColor() : getDisabledTextColor()); } else { SetTextColor(hdc, GetSysColor(bEnabled ? COLOR_WINDOWTEXT : COLOR_GRAYTEXT)); } return result; } LRESULT onCtlHiliteIfEnabled(HDC hdc, bool bEnabled) { if (isEnabled()) { SetTextColor(hdc, bEnabled ? getLinkTextColor() : getDisabledTextColor()); SetBkColor(hdc, getBackgroundColor()); return reinterpret_cast<LRESULT>(getBackgroundBrush()); } else { SetTextColor(hdc, GetSysColor(bEnabled ? COLOR_HIGHLIGHT : COLOR_GRAYTEXT)); return FALSE; } } INT_PTR onCtlColorListbox(WPARAM wParam, LPARAM lParam) { auto hdc = reinterpret_cast<HDC>(wParam); auto hwnd = reinterpret_cast<HWND>(lParam); auto style = ::GetWindowLongPtr(hwnd, GWL_STYLE); bool isComboBox = (style & LBS_COMBOBOX) == LBS_COMBOBOX; if (!isComboBox && ::IsWindowEnabled(hwnd)) { return static_cast<INT_PTR>(onCtlColorSofter(hdc)); } return static_cast<INT_PTR>(onCtlColor(hdc)); } }
66,099
C++
.cpp
1,849
26.143862
168
0.581782
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,115
NPP_Plugin_Darkmode.cpp
shriprem_FWDataViz/src/Darkmode/NPP_Plugin_Darkmode.cpp
#include "NPP_Plugin_Darkmode.h" #include "NppDarkMode.h" HWND nppHandle; void NPPDM_InitDarkMode(const HWND _nppHandle) { nppHandle = _nppHandle; return NppDarkMode::initDarkMode(); } void NPPDM_QueryNPPDarkmode() { NppDarkMode::queryNPPDarkmode(); } bool NPPDM_IsEnabled() { return NppDarkMode::isEnabled(); } void NPPDM_AutoSubclassAndThemeChildControls(HWND hwndParent) { NppDarkMode::autoSubclassAndThemeChildControls(hwndParent); } void NPPDM_AutoThemeChildControls(HWND hwndParent) { NppDarkMode::autoThemeChildControls(hwndParent); } void NPPDM_SetDarkTitleBar(HWND hwnd) { NppDarkMode::setDarkTitleBar(hwnd); } void NPPDM_InitSysLink(HWND hCtl) { NppDarkMode::initSysLink(hCtl); } LRESULT NPPDM_OnCtlColor(HDC hdc) { return NppDarkMode::onCtlColor(hdc); } LRESULT NPPDM_OnCtlColorSofter(HDC hdc) { return NppDarkMode::onCtlColorSofter(hdc); } LRESULT NPPDM_OnCtlColorDarker(HDC hdc) { return NppDarkMode::onCtlColorDarker(hdc); } LRESULT NPPDM_OnCtlColorError(HDC hdc) { return NppDarkMode::onCtlColorError(hdc); } LRESULT NPPDM_OnCtlColorSysLink(HDC hdc) { return NppDarkMode::onCtlColorSysLink(hdc); } LRESULT NPPDM_OnCtlColorIfEnabled(HDC hdc, bool isEnabled) { return NppDarkMode::onCtlColorIfEnabled(hdc, isEnabled); } LRESULT NPPDM_OnCtlHiliteIfEnabled(HDC hdc, bool isEnabled) { return NppDarkMode::onCtlHiliteIfEnabled(hdc, isEnabled); } INT_PTR NPPDM_OnCtlColorListbox(WPARAM wParam, LPARAM lParam) { return NppDarkMode::onCtlColorListbox(wParam, lParam); }
1,540
C++
.cpp
49
29.122449
63
0.804746
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,118
dpiManagerV2.cpp
shriprem_FWDataViz/src/NPP/dpiManagerV2.cpp
// This file is part of Notepad++ project // Copyright (c) 2024 ozone10 and Notepad++ team // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // at your option any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #include "dpiManagerV2.h" #include <commctrl.h> #if defined(__GNUC__) && __GNUC__ > 8 #define WINAPI_LAMBDA_RETURN(return_t) -> return_t WINAPI #elif defined(__GNUC__) #define WINAPI_LAMBDA_RETURN(return_t) WINAPI -> return_t #else #define WINAPI_LAMBDA_RETURN(return_t) -> return_t #endif template <typename P> bool ptrFn(HMODULE handle, P& pointer, const char* name) { auto p = reinterpret_cast<P>(::GetProcAddress(handle, name)); if (p != nullptr) { pointer = p; return true; } return false; } using fnGetDpiForSystem = UINT (WINAPI*)(VOID); using fnGetDpiForWindow = UINT (WINAPI*)(HWND hwnd); using fnGetSystemMetricsForDpi = int (WINAPI*)(int nIndex, UINT dpi); using fnSystemParametersInfoForDpi = BOOL (WINAPI*)(UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni, UINT dpi); using fnSetThreadDpiAwarenessContext = DPI_AWARENESS_CONTEXT (WINAPI*)(DPI_AWARENESS_CONTEXT dpiContext); using fnAdjustWindowRectExForDpi = BOOL (WINAPI*)(LPRECT lpRect, DWORD dwStyle, BOOL bMenu, DWORD dwExStyle, UINT dpi); fnGetDpiForSystem _fnGetDpiForSystem = nullptr; fnGetDpiForWindow _fnGetDpiForWindow = nullptr; fnGetSystemMetricsForDpi _fnGetSystemMetricsForDpi = nullptr; fnSystemParametersInfoForDpi _fnSystemParametersInfoForDpi = nullptr; fnSetThreadDpiAwarenessContext _fnSetThreadDpiAwarenessContext = nullptr; fnAdjustWindowRectExForDpi _fnAdjustWindowRectExForDpi = nullptr; void DPIManagerV2::initDpiAPI() { if (NppDarkMode::isWindows10()) { HMODULE hUser32 = ::GetModuleHandleW(L"user32.dll"); if (hUser32 != nullptr) { ptrFn(hUser32, _fnGetDpiForSystem, "GetDpiForSystem"); ptrFn(hUser32, _fnGetDpiForWindow, "GetDpiForWindow"); ptrFn(hUser32, _fnGetSystemMetricsForDpi, "GetSystemMetricsForDpi"); ptrFn(hUser32, _fnSystemParametersInfoForDpi, "SystemParametersInfoForDpi"); ptrFn(hUser32, _fnSetThreadDpiAwarenessContext, "SetThreadDpiAwarenessContext"); ptrFn(hUser32, _fnAdjustWindowRectExForDpi, "AdjustWindowRectExForDpi"); } } } int DPIManagerV2::getSystemMetricsForDpi(int nIndex, UINT dpi) { if (_fnGetSystemMetricsForDpi != nullptr) { return _fnGetSystemMetricsForDpi(nIndex, dpi); } return DPIManagerV2::scale(::GetSystemMetrics(nIndex), dpi); } DPI_AWARENESS_CONTEXT DPIManagerV2::setThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT dpiContext) { if (_fnSetThreadDpiAwarenessContext != nullptr) { return _fnSetThreadDpiAwarenessContext(dpiContext); } return NULL; } BOOL DPIManagerV2::adjustWindowRectExForDpi(LPRECT lpRect, DWORD dwStyle, BOOL bMenu, DWORD dwExStyle, UINT dpi) { if (_fnAdjustWindowRectExForDpi != nullptr) { return _fnAdjustWindowRectExForDpi(lpRect, dwStyle, bMenu, dwExStyle, dpi); } return FALSE; } UINT DPIManagerV2::getDpiForSystem() { if (_fnGetDpiForSystem != nullptr) { return _fnGetDpiForSystem(); } UINT dpi = USER_DEFAULT_SCREEN_DPI; HDC hdc = ::GetDC(nullptr); if (hdc != nullptr) { dpi = ::GetDeviceCaps(hdc, LOGPIXELSX); ::ReleaseDC(nullptr, hdc); } return dpi; } UINT DPIManagerV2::getDpiForWindow(HWND hWnd) { if (_fnGetDpiForWindow != nullptr) { const auto dpi = _fnGetDpiForWindow(hWnd); if (dpi > 0) { return dpi; } } return getDpiForSystem(); } void DPIManagerV2::setPositionDpi(LPARAM lParam, HWND hWnd, UINT flags) { const auto prcNewWindow = reinterpret_cast<RECT*>(lParam); ::SetWindowPos(hWnd, nullptr, prcNewWindow->left, prcNewWindow->top, prcNewWindow->right - prcNewWindow->left, prcNewWindow->bottom - prcNewWindow->top, flags); } LOGFONT DPIManagerV2::getDefaultGUIFontForDpi(UINT dpi, FontType type) { int result = 0; LOGFONT lf{}; NONCLIENTMETRICS ncm{}; ncm.cbSize = sizeof(NONCLIENTMETRICS); if (_fnSystemParametersInfoForDpi != nullptr && (_fnSystemParametersInfoForDpi(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0, dpi) != FALSE)) { result = 2; } else if (::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0) != FALSE) { result = 1; } if (result > 0) { switch (type) { case FontType::menu: { lf = ncm.lfMenuFont; break; } case FontType::status: { lf = ncm.lfStatusFont; break; } case FontType::caption: { lf = ncm.lfCaptionFont; break; } case FontType::smcaption: { lf = ncm.lfSmCaptionFont; break; } //case FontType::message: default: { lf = ncm.lfMessageFont; break; } } } else // should not happen, fallback { auto hf = static_cast<HFONT>(::GetStockObject(DEFAULT_GUI_FONT)); ::GetObject(hf, sizeof(LOGFONT), &lf); } if (result < 2) { lf.lfHeight = scaleFont(lf.lfHeight, dpi); } return lf; } void DPIManagerV2::loadIcon(HINSTANCE hinst, const wchar_t* pszName, int cx, int cy, HICON* phico, UINT fuLoad) { if (::LoadIconWithScaleDown(hinst, pszName, cx, cy, phico) != S_OK) { *phico = static_cast<HICON>(::LoadImage(hinst, pszName, IMAGE_ICON, cx, cy, fuLoad)); } }
5,685
C++
.cpp
189
27.703704
120
0.753978
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,119
ConfigIO.h
shriprem_FWDataViz/src/ConfigIO.h
#pragma once #include "Utils.h" #include <locale> #include <commdlg.h> #include <filesystem> #include <fstream> #include <iostream> #include <regex> #include <ShlObj_core.h> #include <time.h> #include <unordered_map> #include <vector> #define PREF_ADFT "AutoDetectFileType" #define PREF_CARET_FLASH "CaretFlashSeconds" #define PREF_MBCHARS_SHOW "ShowMBCharsOnPanel" #define PREF_MBCHARS_STATE "PanelMBCharState" #define PREF_JUMP_FIELD_SEQ "ShowJumpFieldSeqNo" #define PREF_DEF_BACKGROUND "DefaultBackground" #define PREF_SHOW_CALLTIP "ShowCalltip" #define PREF_COPY_TRIM "CopyFieldTrim" #define PREF_HOP_RT_LEFT_EDGE "HopRightLeftEdge" #define PREF_PASTE_LPAD "PasteFieldLPAD" #define PREF_PASTE_RPAD "PasteFieldRPAD" #define PREF_CLEARVIZ_AUTO "ClearVizWithAutoDetect" #define PREF_CLEARVIZ_PANEL "ClearVizOnPanelClose" #define PREF_FOLDLINE_COLOR "FoldLineColor" #define PREF_FOLDLINE_ALPHA "FoldLineAlpha" struct StyleInfo { int backColor{}; int foreColor{}; int bold{}; int italics{}; }; struct FoldingInfo { int recTypeIndex{}; int priority{ 0 }; bool recursive{ FALSE }; wstring endRecords{}; }; using std::vector; class ConfigIO { public: enum CF_TYPES { CONFIG_VIZ, CONFIG_THEMES, CONFIG_PREFS, CONFIG_EXTRACTS, CONFIG_FIELD_TYPES, CONFIG_FOLDSTRUCTS, }; void init(); int setVizConfig(const string& docFileType); void userVizConfig(); void defaultVizConfig(); bool isCurrentVizConfigDefault() const { return (wCurrentConfigFile == defaultConfigFile); } wstring getConfigFile(CF_TYPES cfType); wstring getActiveConfigFile(CF_TYPES cfType); string getConfigStringA(const string& section, const string& key, const string& defaultVal = "", string file = "") const; string getConfigStringA(const wstring& section, const string& key, const string& defaultVal = "", wstring file = L"") const; wstring getConfigWideChar(const string& section, const string& key, const string& defaultVal = "", string file = "") const; wstring getConfigWideChar(const wstring& section, const string& key, const string& defaultVal = "", wstring file = L"") const; void setConfigStringA(const string& section, const string& key, const string& value, string file = "") const; void setConfigMultiByte(const string& section, const string& key, const wstring& value, string file = "") const; int getConfigInt(const string& section, const string& key, const int& defaultVal = 0, string file = "") const; int getConfigInt(const wstring& section, const string& key, const int& defaultVal = 0, wstring file = L"") const; wstring getStyleValue(const wstring& theme, const string& styleName, wstring file = L"") const; void getFullStyle(const wstring& theme, const string& styleName, StyleInfo& style, wstring file = L"") const; string getFieldStyleText(const wstring& fieldName) const; void parseFieldStyle(const string& styleText, StyleInfo& style); int getFoldStructCount(wstring file = L"") const; string getFoldStructValueA(string foldStructType, string key, wstring file = L"") const; string getFoldStructValue(wstring foldStructType, string key, wstring file = L"") const; void getFoldStructFoldingInfo(wstring foldStructType, vector<FoldingInfo>& vFoldInfo, wstring file = L""); wstring getPreference(const string key, const string defaultVal = "") const; void setPreference(const string key, const wstring value) const; bool getPreferenceBool(const string key, const bool defaultVal = TRUE) const; void setPreferenceBool(const string key, const bool value) const; int getPreferenceInt(const string key, const int defaultVal = 0) const; void setPreferenceInt(const string key, const int value) const; void setPanelMBCharState(UINT state) const; bool getMultiByteLexing(string fileType) const; int getConfigAllSections(string& sections, const string file); int getConfigAllSectionsList(vector<string>& sectionsList, const string file); int getConfigAllSectionsList(vector<wstring>& sectionsList, const wstring file); int getConfigAllKeys(const string& section, string& keys, const string file); int getConfigAllKeysList(const string& section, vector<string>& keysList, const string file); int getConfigAllKeysList(const string& section, vector<wstring>& keysList, const string file); int getConfigValueList(vector<string>& valList, const string& section, const string& key, const string& defaultVal = "", string file = ""); int getThemesList(vector<wstring>& valList, wstring file = L""); int Tokenize(const string& text, vector<string>& results, const string& delim = ","); int Tokenize(const wstring& text, vector<wstring>& results, const wstring& delim = L","); int Tokenize(const string& text, vector<int>& results, const string& delim = ","); void ActivateNewLineTabs(wstring& str); void deleteKey(const string& section, const string& key, string file = "") const; void deleteKey(const wstring& section, const wstring& key, wstring file = L"") const; void deleteSection(const string& section, string file = ""); string readConfigFile(wstring file = L"") const; bool queryConfigFileName(HWND hwnd, bool bOpen, bool backupFolder, wstring& backupConfigFile) const; void saveConfigFile(const wstring& fileData, wstring file); int getBackupTempFileName(wstring& tempFileName) const; void backupConfigFile(wstring file) const; void viewBackupFolder() const; void flushConfigFile(); bool checkConfigFilesforUTF8(); bool fixIfNotUTF8File(CF_TYPES cfType); bool fixIfNotUTF8File(wstring file); protected: TCHAR pluginConfigDir[MAX_PATH]{}; TCHAR pluginConfigBackupDir[MAX_PATH]{}; TCHAR defaultConfigFile[MAX_PATH]{}; TCHAR defaultThemeFile[MAX_PATH]{}; TCHAR defaultFoldStructFile[MAX_PATH]{}; static constexpr int CONFIG_FILE_COUNT{ CONFIG_FOLDSTRUCTS + 1 }; const wstring CONFIG_FILES[CONFIG_FILE_COUNT]{ L"Visualizer.ini", L"Themes.ini", L"Preferences.ini", L"Extracts.ini", L"FieldTypes.ini", L"FoldStructs.ini"}; wstring WCONFIG_FILE_PATHS[CONFIG_FILE_COUNT]; string CONFIG_FILE_PATHS[CONFIG_FILE_COUNT]; wstring wCurrentConfigFile{}, wCurrentThemeFile{}, wCurrentFoldStructFile{}; string currentConfigFile{}; enum ENC_TYPE { UTF8, UTF8_BOM, UCS16_LE, UCS16_BE }; ENC_TYPE getBOM(wstring file); };
6,480
C++
.h
128
46.953125
129
0.748972
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,120
Utils.h
shriprem_FWDataViz/src/Utils.h
#pragma once #include "PluginDefinition.h" #include <codecvt> #include <regex> #include <ShlObj_core.h> #define mbox(message) MessageBox(NULL, message, L"", MB_OK) #define mboxA(message) MessageBoxA(NULL, message, "", MB_OK) namespace Utils { constexpr int PREFS_TIP_MAX_WIDTH{ 400 }; int StringtoInt(const string& str, int base = 10); int StringtoInt(const wstring& str, int base = 10); LPCWSTR ToUpper(LPWSTR str); wstring NarrowToWide(const string& str); string WideToNarrow(const wstring& wStr); bool isInvalidRegex(const string& expr); bool isInvalidRegex(const wstring& expr, HWND hWnd, const wstring& context); COLORREF intToRGB(int color); wstring getSpecialFolder(int folderID); wstring getKnownFolderPath(REFKNOWNFOLDERID folderID); HWND addTooltip(HWND hDlg, int controlID, const wstring& pTitle, const wstring& pMessage, bool bBalloon = TRUE); HWND addTooltip(HWND hDlg, int controlID, const wstring& pTitle, const wstring& pMessage, int duration, bool bBalloon); void updateTooltip(HWND hDlg, int controlID, HWND hTip, const wstring& pMessage); void addToolbarIcon(int menuIndex, int std, int fluent, int dark); void checkMenuItem(int menuIndex, bool check); void showEditBalloonTip(HWND hEdit, LPCWSTR title, LPCWSTR text); bool checkBaseOS(winVer os); float getNPPVersion(); bool checkKeyHeldDown(int vKey); wstring getListBoxItem(HWND hList, bool currentSelection = TRUE, const int itemIndex = 0); void setComboBoxSelection(HWND hList, int index); bool getClipboardText(HWND hwnd, wstring& clipText); wstring getVersionInfo(LPCWSTR key); void loadBitmap(HWND hDlg, int controlID, int resource); void setFont(HWND hDlg, int controlID, wstring& name, int height, int weight = FW_REGULAR, bool italic = FALSE, bool underline = FALSE); bool setFontRegular(HWND hDlg, int controlID); bool setFontBold(HWND hDlg, int controlID); bool setFontItalic(HWND hDlg, int controlID); bool setFontUnderline(HWND hDlg, int controlID); int scaleDPIX(int x); int scaleDPIY(int y); int getTextPixelWidth(HWND hDlg, const wstring& text); bool checkDirectoryExists(LPCWSTR lpDirPath); bool checkFileExists(LPCWSTR lpFilePath); }
2,252
C++
.h
45
46.377778
122
0.760692
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,121
PluginDefinition.h
shriprem_FWDataViz/src/PluginDefinition.h
//This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #pragma once #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <string> #include <windows.h> #include <CommCtrl.h> #include <Shlwapi.h> #include <shellapi.h> #include "NPP/PluginInterface.h" #include "Resources/resource.h" #include "Resources/control_ids.h" #include "Resources/FWVIZ_messages.h" #include "Resources/localization.h" #define PLUGIN_FOLDER_NAME L"FWDataViz" using std::string; using std::string_view; using std::wstring; using std::to_string; using std::to_wstring; constexpr int FW_LINE_MAX_LENGTH{ 32767 }; constexpr int ADFT_MAX{ 3 }; constexpr int _gLanguage{ LANG_ENGLISH }; const enum MenuIndex { MI_FWVIZ_PANEL, MI_CONFIG_DIALOG, MI_CONFIG_THEMES, MI_SEPARATOR_1, MI_FIELD_JUMP, MI_FIELD_LEFT, MI_FIELD_RIGHT, MI_FIELD_COPY, MI_FIELD_PASTE, MI_DATA_EXTRACTION, MI_SEPARATOR_2, MI_DEMO_SINGLE_REC_FILES, MI_DEMO_MULTI_REC_FILES, MI_DEMO_MULTI_LINE_FILES, MI_SEPARATOR_3, MI_ABOUT_DIALOG, MI_COUNT }; typedef LRESULT (*PSCIFUNC_T)(void*, int, WPARAM, LPARAM); void pluginInit(HANDLE hModule); void pluginCleanUp(); void commandMenuInit(); void commandMenuCleanUp(); bool setCommand(size_t index, const wstring& cmdName, PFUNCPLUGINCMD pFunc, ShortcutKey* sk = NULL, bool checkOnInit = false); HWND getCurrentScintilla(); bool getDirectScintillaFunc(PSCIFUNC_T& fn, void*& ptr); LRESULT nppMessage(UINT messageID, WPARAM wparam = 0, LPARAM lparam = 0); // Plugin Command Functions void ShowVisualizerPanel(bool show); void ToggleVisualizerPanel(); void RefreshVisualizerPanel(); void ShowConfigDialog(); void ShowThemeDialog(); void ShowJumpDialog(); void FieldLeft(); void FieldRight(); void FieldCopy(); void FieldPaste(); void ShowDataExtractDialog(); void ShowAboutDialog(); void refreshDarkMode();
2,540
C++
.h
77
31.12987
126
0.774918
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,122
SubmenuManager.h
shriprem_FWDataViz/src/SubmenuManager.h
#pragma once #include "PluginDefinition.h" #include <vector> class SubmenuManager { public: void listSampleFiles(); void loadSampleFile(WPARAM wParam, LPARAM lParam) const; void initSamplesPopup(HMENU hPopup); private: static HMENU getPluginSubMenu(); size_t itemCount; size_t itemIDStart; TCHAR pluginSamplesDir[MAX_PATH]; };
353
C++
.h
14
22.357143
59
0.781437
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,123
ConfigureDialog.h
shriprem_FWDataViz/src/Dialogs/ConfigureDialog.h
#pragma once #include "../Utils.h" #include "../ConfigIO.h" #include "../NPP/StaticDialog.h" #include <regex> #include <vector> constexpr int FILE_TYPE_LIMIT{ 999 }; constexpr int REC_TYPE_LIMIT{ 999 }; const wstring REGEX_META_CHARS{ L"\\^\\$\\\\(\\)\\{\\}\\[\\]\\<\\>\\.\\?\\*\\+\\,\\-\\|\\!\\:\\=" }; using std::wregex; using std::regex_replace; using std::vector; using Utils::showEditBalloonTip; extern NppData nppData; extern ConfigIO _configIO; class ConfigureDialog : public StaticDialog { public: ConfigureDialog() : StaticDialog() {}; void doDialog(HINSTANCE hInst); void display(bool toShow = TRUE); void refreshDarkMode(); void setFieldEditCaretOnFocus(HWND hEdit); void hiliteFieldEditPairedItem(HWND hThis, HWND hThat); void syncFieldEditScrolling(HWND hThis, HWND hThat); HWND hFieldLabels{}, hFieldWidths{}; private: enum move_dir { MOVE_DOWN = 1, MOVE_UP = -1 }; struct RecordType { wstring label; wstring marker; wstring fieldLabels; wstring fieldWidths; wstring theme{}; }; struct FileType { wstring label{}; wstring theme{}; wstring eol{}; bool multiByte{}; vector<RecordType> vRecTypes; int lineNums[ADFT_MAX]{}; wstring regExprs[ADFT_MAX]{}; }; INT_PTR CALLBACK run_dlgProc(UINT Message, WPARAM wParam, LPARAM); void localize(); void indicateCleanStatus(); int loadConfigInfo(); int loadFileTypeInfo(int vIndex, const string& fileType, const wstring& sConfigFile); bool promptDiscardChangesNo(); void saveConfigInfo(); void showEximDialog(bool bExtract); int appendFileTypeConfigs(const wstring& sConfigFile); wstring getOnlyStartsWith(wstring expr); int getCurrentFileTypeIndex() const; bool getCurrentFileTypeInfo(FileType*& fileInfo); FileType getNewFileType(); int getFileTypeConfig(size_t idxFT, bool cr_lf, wstring& ftCode, wstring& ftConfig); int getCurrentRecIndex() const; bool getCurrentRecInfo(RecordType*& recInfo); RecordType getNewRec(); void fillFileTypes(); void onFileTypeSelect(); void onFileTypeSelectFill(FileType* fileInfo); void enableMoveFileButtons(); void enableFileSelection(); int moveFileType(move_dir dir); int fileEditAccept(bool accept = true); void fileEditNew(); void fileEditClone(); int fileEditDelete(); bool checkFTLimit(bool clone); void fillRecTypes(); void onRecTypeSelect(); void onRecTypeSelectFill(RecordType* recInfo); void enableMoveRecButtons(); void enableRecSelection(); int moveRecType(move_dir dir); void onRecStartEditChange() const; void onRecRegexEditChange(); int recEditAccept(bool accept = true); void recEditNew(bool clone); int recEditDelete(); void fillFieldTypes(); void fieldEditsAccept(); wstring configFile{}; bool loadingEdits{}, cleanConfigFile{ true }, cleanFileVals{ true }, cleanRecVals{ true }, cleanFieldVals{ true }; int editLabelsCaret{}, editWidthsCaret{}; HWND hFilesLB{}, hFileEOL{}, hFileThemes{}, hADFTLine[ADFT_MAX]{}, hADFTRegex[ADFT_MAX]{}, hRecsLB{}, hRecStart{}, hRecRegex{}, hRecThemes{}; vector<FileType> vFileTypes; }; LRESULT CALLBACK procNumberEditControl(HWND hwnd, UINT messageId, WPARAM wParam, LPARAM lParam, UINT_PTR, DWORD_PTR); LRESULT CALLBACK procFieldEditMessages(HWND hwnd, UINT messageId, WPARAM wParam, LPARAM lParam, UINT_PTR, DWORD_PTR);
3,452
C++
.h
96
31.9375
117
0.72512
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,124
PreferencesDialog.h
shriprem_FWDataViz/src/Dialogs/PreferencesDialog.h
#pragma once #include "../Utils.h" #include "../ConfigIO.h" #include "../NPP/StaticDialog.h" extern NppData nppData; extern ConfigIO _configIO; class PreferencesDialog : public StaticDialog { public: PreferencesDialog() : StaticDialog() {}; ~PreferencesDialog() { if (hbr != NULL) DeleteObject(hbr); }; void doDialog(HINSTANCE hInst); void refreshDarkMode(); static COLORREF getPreferenceFoldLineColor(); static void applyFoldLineColorAlpha(); private: INT_PTR CALLBACK run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam); void localize(); void initCheckbox(int nIDButton, const string& preference, bool defaultVal); void setCheckbox(int nIDButton, const string& preference); void chooseColor(); void setPreferenceFoldLineColor(COLORREF rgbColor); void displayFoldLineColor(); INT_PTR colorStaticControl(WPARAM wParam, LPARAM lParam); void setFoldLineAlpha(); HBRUSH hbr{}; };
938
C++
.h
26
32.884615
79
0.763012
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,125
ThemeDialog.h
shriprem_FWDataViz/src/Dialogs/ThemeDialog.h
#pragma once #include "StyleDefComponent.h" #include "../NPP/StaticDialog.h" #include <regex> #include <vector> constexpr int THEME_ITEM_LIMIT{ 999 }; constexpr int STYLE_ITEM_LIMIT{ 99 }; constexpr int SWATCH_ITEM_COUNT{ 29 }; using std::wregex; using std::regex_replace; using std::vector; class ThemeDialog : public StaticDialog, StyleDefComponent { public: ThemeDialog() : StaticDialog() {}; void doDialog(HINSTANCE hInst); void display(bool toShow = TRUE); void refreshDarkMode(); void initPreviewSwatch(int idxStart = 0, int idxEnd = SWATCH_ITEM_COUNT); private: enum move_dir { MOVE_DOWN = 1, MOVE_UP = -1 }; struct ThemeType { wstring label; StyleInfo eolStyle; vector<StyleInfo> vStyleInfo; }; INT_PTR CALLBACK run_dlgProc(UINT Message, WPARAM wParam, LPARAM); void localize(); void indicateCleanStatus(); int loadConfigInfo(); int loadThemeInfo(int vIndex, const wstring& themeType, const wstring& sThemeFile); bool promptDiscardChangesNo(); void saveConfigInfo(); void showEximDialog(bool bExtract); int appendThemeConfigs(const wstring& sThemeFile); int getCurrentThemeIndex() const; bool getCurrentThemeInfo(ThemeType*& fileInfo); ThemeType getNewTheme(); void getThemeConfig(size_t idxTh, bool cr_lf, wstring& themeLabel, wstring& ttConfig); int getCurrentStyleIndex() const; bool getCurrentStyleInfo(StyleInfo*& styleInfo); StyleInfo getNewStyle(); void fillThemes(); void onThemeSelect(); void onThemeSelectFill(ThemeType* themeInfo); void enableMoveThemeButtons(); void enableThemeSelection(); int moveThemeType(move_dir dir); void themeEditAccept(bool accept = true); void themeEditNew(); void themeEditClone(); int themeEditDelete(); bool checkThemeLimit(bool clone); void fillStyles(); void onStyleSelect(); void enableMoveStyleButtons(); void enableStyleSelection(); int moveStyleType(move_dir dir); void styleEditNew(bool clone); int styleEditDelete(); void setStyleDefColor(bool setEdit, int color, bool back); void fillStyleDefs(); wstring getStyleConfig(int idx, StyleInfo& style); void styleDefsAccept(); INT_PTR colorPreviewSwatch(WPARAM wParam, LPARAM lParam); void processSwatchClick(int ctrlID); void chooseStyleDefColor(bool back); wstring themeFile{}; int swatchTopIndex{}; bool loadingEdits{}, cleanConfigFile{ true }, cleanThemeVals{ true }; HWND hThemesLB{}, hStylesLB{}; vector<ThemeType> vThemeTypes; }; LRESULT CALLBACK procStylesListBox(HWND hwnd, UINT messageId, WPARAM wParam, LPARAM lParam, UINT_PTR, DWORD_PTR);
2,669
C++
.h
76
31.302632
113
0.750194
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,126
FieldTypeDialog.h
shriprem_FWDataViz/src/Dialogs/FieldTypeDialog.h
#pragma once #include "StyleDefComponent.h" #include "../NPP/StaticDialog.h" class FieldTypeDialog : public StaticDialog, StyleDefComponent { public: FieldTypeDialog() : StaticDialog() {}; void doDialog(HINSTANCE hInst); void refreshDarkMode(); private: INT_PTR CALLBACK run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam); void localize(); int getCurrentFieldIndex() const; string getNewStyle(); string getStyleConfig(); void fillFields(); void onFieldSelect(); void enableFieldSelection(); void fieldEditNew(); void fieldEditClone(); void fieldEditDelete(); void setStyleDefColor(bool setEdit, int color, bool back); void fillStyleDefs(); void styleDefSave(); void chooseStyleDefColor(bool back); bool loadingEdits{}, newFieldDef{}; string fieldDefConfigFile{}, fieldDefStyle; wstring fieldDefLabel, fieldDefRegex; HWND hFieldsLB{}; };
918
C++
.h
29
28.034483
76
0.754266
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,127
EximFileTypeDialog.h
shriprem_FWDataViz/src/Dialogs/EximFileTypeDialog.h
#pragma once #include "../Utils.h" #include "../ConfigIO.h" #include "../NPP/StaticDialog.h" extern NppData nppData; extern ConfigIO _configIO; class EximFileTypeDialog : public StaticDialog { public: enum exim_clients { FWTYPES_DLG, THEMES_DLG, FOLDS_DLG, EXIM_DLGS }; EximFileTypeDialog() : StaticDialog() {}; void doDialog(HINSTANCE hInst); void initDialog(HWND hWnd, exim_clients mode, bool bExtract); void refreshDarkMode(); void setFileTypeData(const wstring& ftConfig); private: INT_PTR CALLBACK run_dlgProc(UINT Message, WPARAM wParam, LPARAM lParam); void localize(); void appendExtractFile(); void loadExtractFile(); void saveExtractFile(); wstring getEditControlText(); bool extractMode{}; exim_clients exim_mode{}; HWND hClientDlg{}; LPCWSTR APPEND_TITLE[EXIM_DLGS]{ EXIM_APPEND_FT_TITLE, EXIM_APPEND_THEME_TITLE, EXIM_APPEND_FOLD_TITLE }; LPCWSTR EXTRACT_TITLE[EXIM_DLGS]{ EXIM_EXTRACT_FT_TITLE, EXIM_EXTRACT_THEME_TITLE, EXIM_EXTRACT_FOLD_TITLE }; LPCWSTR EDIT_LABEL[EXIM_DLGS]{ EXIM_EDIT_FT_LABEL, EXIM_EDIT_THEME_LABEL, EXIM_EDIT_FOLD_LABEL }; LPCWSTR APPEND_BTN[EXIM_DLGS]{ EXIM_APPEND_FT_BTN, EXIM_APPEND_THEME_BTN, EXIM_APPEND_FOLD_BTN }; };
1,254
C++
.h
34
33.147059
112
0.73493
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,128
VisualizerPanel.h
shriprem_FWDataViz/src/Dialogs/VisualizerPanel.h
#pragma once #include "../Utils.h" #include "../ConfigIO.h" #include "../SubmenuManager.h" #include "../NPP/DockingDlgInterface.h" #include "../NPP/menuCmdID.h" #include <regex> #define FW_DEBUG_SET_STYLES FALSE #define FW_DEBUG_LOAD_REGEX FALSE #define FW_DEBUG_APPLY_LEXER FALSE #define FW_DEBUG_APPLIED_STYLES FALSE #define FW_DEBUG_LEXER_COUNT FALSE #define FW_DEBUG_COPY_TRIM FALSE #define FW_DEBUG_DOC_INFO FALSE #define FW_DEBUG_FOLD_INFO FALSE constexpr int FW_STYLE_THEMES_START_INDEX{ STYLE_LASTPREDEFINED + 1 }; constexpr int FW_STYLE_THEMES_MAX_ITEMS{ 200 }; constexpr int FW_STYLE_FIELDS_MIN_INDEX{ FW_STYLE_THEMES_START_INDEX + 36 }; constexpr int FW_TIP_LONG{ 30 }; constexpr int FW_TIP_MEDIUM{ 20 }; constexpr int FW_TIP_SHORT{ 10 }; constexpr int FOLDING_MARGIN{ 3 }; static bool idemPotentKey{ FALSE }; extern NppData nppData; extern ConfigIO _configIO; using std::regex; using std::vector; class VisualizerPanel : public DockingDlgInterface { public: struct RecordInfo { wstring label; string marker; regex regExpr; wstring theme; vector<int> fieldStarts; vector<int> fieldWidths; vector<wstring> fieldLabels; vector<int> fieldStyles; }; VisualizerPanel() :DockingDlgInterface(IDD_VISUALIZER_DOCKPANEL) {}; ~VisualizerPanel() { if (hbr != NULL) DeleteObject(hbr); }; void initPanel(); virtual void display(bool toShow = TRUE); void refreshDarkMode(); void initMBCharsCheckbox(); void updateHopRightTip(); void setParent(HWND parent2set); void setFocusOnEditor(); void loadListFileTypes(); bool getDocFileType(string& fileType); void loadListThemes() const; void onBufferActivate(); void renderCurrentPage(); void visualizeFile(string fileType, bool bCachedFT, bool bAutoFT, bool bSyncFT); void delDocInfo(intptr_t bufferID); void showConfigDialog(); void showThemeDialog(); void showJumpDialog(); void showAboutDialog(); void jumpToField(const string fileType, const int recordIndex, const int fieldIdx); void fieldLeft(); void fieldRight(); void fieldCopy(); void fieldPaste(); void showExtractDialog(); #if FW_DEBUG_LEXER_COUNT int lexCount{}; #endif private: HWND hFTList{}, hThemesLB{}, hFieldInfo{}, hTipIniFiles{}, hTipHopRight{}; HBRUSH hbr{}; // Field Info tracking intptr_t caretRecordStartPos{}, caretRecordEndPos{}, caretEolMarkerPos{}; int caretRecordRegIndex{}, caretFieldIndex{}; bool panelMounted{}, unlexed{}, utf8Config{}, leftAlign{}, themeEnabled{}, fieldEnabled{}; string calltipText{}; // Needed for the PostMessage call // File Type Info struct FileTypeInfo { string fileType{}; wstring fileLabel{}; }; vector<FileTypeInfo> vFileTypes{}; // Doc Info struct DocInfo { wstring fileName{}; string docType{}; string docTheme{}; string foldStructType{}; bool folded{}; }; vector<DocInfo> vDocInfo{}; // Styleset data struct ThemeInfo { wstring name{}; int styleCount{}; int rangeStartIndex{}; }; vector<ThemeInfo> vThemes{}; int loadedStyleCount{}; // Regex data string fwVizRegexed{}; vector<RecordInfo> vRecInfo; virtual INT_PTR CALLBACK run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam); void localize(); bool detectFileType(HWND hScintilla, string& fileType); bool detectFileTypeByVizConfig(HWND hScintilla, string& fileType, bool defaultConfig); const wstring getCurrentFileName(); void setDocInfo(bool bDocType, string val); bool getDocTheme(wstring& theme); string getDocFoldStructType(); bool getDocFolded(); void setDocFileType(string fileType); void setDocTheme(string theme, string fileType = ""); void setDocFoldStructType(string foldStructType); void setDocFolded(bool bFolding); void setADFTCheckbox(); void setPanelMBCharState(); void setPanelMBCharIndicator(string fileType); void setDefaultBackground(); void setShowCalltip(); void initCalltipStyle(); void enableThemeList(bool enable); void syncListFileTypes(); void syncListThemes(); void enableFieldControls(bool enable); void clearVisualize(bool sync = TRUE); int loadTheme(const wstring theme); int loadUsedThemes(); int loadLexer(); void applyLexer(const intptr_t startLine, intptr_t endLine); void clearLexer(); void visualizeTheme(); void displayCaretFieldInfo(const intptr_t startLine, const intptr_t endLine); void clearCaretFieldInfo(); void onPanelResize(LPARAM lParam); int getFieldEdges(const string fileType, const int fieldIdx, const int rightPullback, intptr_t& leftPos, intptr_t& rightPos); void moveToFieldEdge(const string fileType, const int fieldIdx, bool jumpTo, bool rightEdge, bool hilite); void setFieldAlign(bool left); void popupSamplesMenu(); string detectFoldStructType(string fileType); void applyFolding(string fsType); void removeFolding(); void enableFoldableControls(bool bFoldable); void enableFoldedControls(bool bFolded); void toggleFolding(); int foldLevelFromPopup(bool bFold); void expandFoldLevel(bool bExpand, int level); void foldLevelMenu(); void unfoldLevelMenu(); void showFoldStructDialog(); static DWORD WINAPI threadPositionHighlighter(void*); };
5,347
C++
.h
152
31.276316
128
0.745015
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,129
StyleDefComponent.h
shriprem_FWDataViz/src/Dialogs/StyleDefComponent.h
#pragma once #include "../Utils.h" #include "../ConfigIO.h" extern NppData nppData; extern ConfigIO _configIO; class StyleDefComponent { public: ~StyleDefComponent(); protected: void initComponent(HWND hDlg); void localize() const; int getStyleDefColor(bool back) const; void setStyleDefColor(bool setEdit, int color, bool back); void setOutputFontStyle() const; void fillStyleDefs(StyleInfo& style); void setPangram() const; INT_PTR colorStaticControl(WPARAM wParam, LPARAM lParam); void chooseStyleDefColor(bool back); bool cleanStyleDefs{ true }, styleDefColor{}; HWND _hDialog{}; HBRUSH hbr{}; COLORREF styleBack{}, styleFore{}, customColors[16]{}; }; LRESULT CALLBACK procHexColorEditControl(HWND hwnd, UINT messageId, WPARAM wParam, LPARAM lParam, UINT_PTR, DWORD_PTR);
826
C++
.h
24
31.333333
119
0.761965
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,130
JumpToField.h
shriprem_FWDataViz/src/Dialogs/JumpToField.h
#pragma once #include "../Utils.h" #include "../ConfigIO.h" #include "../NPP/StaticDialog.h" extern NppData nppData; extern ConfigIO _configIO; class JumpToField : public StaticDialog { public: JumpToField() : StaticDialog() {}; void doDialog(HINSTANCE hInst); void refreshDarkMode(); void initDialog(const string fileType, int recordIndex, int fieldIndex, const vector<wstring>& fieldLabels); void setFileTypeData(const wstring& ftConfig); private: INT_PTR CALLBACK run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam); void localize(); void loadJumpList(int fieldIndex = -1); void onJumpSeqNumPref(); void onJumpBtnClick(); int getTbarPosition() const; void setTbarPosition(int val, bool savePref); string initFileType{}; int initRecordRegIndex{}; HWND hFieldList{}, hCaretFlash{}; const vector<wstring>* pFieldLabels{}; };
885
C++
.h
26
30.884615
111
0.752056
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,131
DataExtractDialog.h
shriprem_FWDataViz/src/Dialogs/DataExtractDialog.h
#pragma once #include "../NPP/StaticDialog.h" #include "VisualizerPanel.h" constexpr int LINES_PER_PAGE{ 10 }; constexpr int MAX_PAGES{ 3 }; constexpr int MAX_BUFFER_LINES{ LINES_PER_PAGE * MAX_PAGES }; constexpr int MAX_TEMPLATE_NAME{ 50 }; extern NppData nppData; extern ConfigIO _configIO; typedef VisualizerPanel::RecordInfo RecordInfo; class DataExtractDialog : public StaticDialog { public: DataExtractDialog() : StaticDialog() {}; void doDialog(HINSTANCE hInst); void initDialog(const string fileType, const vector<RecordInfo>& recInfoList); void refreshDarkMode(); bool processKey(HWND hCtrl, WPARAM wParam); bool processSysKey(HWND hCtrl, WPARAM wParam); private: struct LineItemInfo { wstring prefix; int recType{}; int fieldType{}; wstring suffix; }; INT_PTR CALLBACK run_dlgProc(UINT Message, WPARAM wParam, LPARAM lParam); void localize(); void initRecTypeLists(); void initLineItemFieldList(int line); void moveIndicators(int line, bool focusPrefix); void resetDropDown(HWND hList); bool isBlankLineItem(const LineItemInfo& lineItem); void addLineItem(int line); void delLineItem(int line); void clearLineItem(int line); void getLineItem(int line, LineItemInfo& lineItem); void setLineItem(int line, LineItemInfo& lineItem); void swapLineItems(int lineFrom, int lineTo); void gotoLine(int ctrlID, int lineTo); size_t getValidLineItems(vector<LineItemInfo>& validLIs, bool validFieldType, bool activateNLT); void extractData(); int loadTemplatesList(); void loadTemplate(); string getSelectedTemplate() const; string getTemplateName() const; void enableSaveTemplate(); void enableDeleteTemplate(); void saveTemplate(); void newTemplate(); void deleteTemplate(); int getPageCount(int items = 0); void loadPage(int pageNum); void readPage(); void previousPage(); void nextPage(); void addPage(); void deletePage(); void enablePageButtons(); int currentLineItem{}, currentPage{}; string extractsConfigFile{}, initFileType{}; wstring initFileTypeLabel{}; const vector<RecordInfo>* pRecInfoList{}; HWND hIndicator{}, hTemplatesList{}, hTemplateName{}; vector<LineItemInfo> liBuffer{}; };
2,275
C++
.h
65
31.246154
99
0.750911
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,132
FoldStructDialog.h
shriprem_FWDataViz/src/Dialogs/FoldStructDialog.h
#pragma once #include "../Utils.h" #include "../ConfigIO.h" #include "../NPP/StaticDialog.h" #include <regex> #include <vector> using std::vector; extern NppData nppData; extern ConfigIO _configIO; class FoldStructDialog : public StaticDialog { public: FoldStructDialog() : StaticDialog() {}; void doDialog(HINSTANCE hInst); void refreshDarkMode(); private: enum move_dir { MOVE_DOWN = 1, MOVE_UP = -1 }; // Type Info struct TypeInfo { string type{}; wstring label{}; }; // Block Info struct BlockInfo { TypeInfo hdrRec{}; int priority{}; bool recursive{}; vector<TypeInfo> vEndRecs{}; }; // Fold Struct Info struct FoldStructInfo { TypeInfo fileType{}; bool autoFold{}; vector<BlockInfo> vBlocks{}; }; INT_PTR CALLBACK run_dlgProc(UINT Message, WPARAM wParam, LPARAM); void localize(); void indicateCleanStatus(); int loadStructsInfo(); int loadFoldStructInfo(int vIndex, string fsType, const wstring& sStructsFile); bool promptDiscardChangesNo(); void saveFoldStructInfo(); void showEximDialog(bool bExtract); int appendFoldStructInfo(const wstring& sConfigFile); int getCurrentFoldStructIndex() const; bool getCurrentFoldStructInfo(FoldStructInfo*& structInfo); int getFoldStructInfo(size_t idxFS, bool cr_lf, wstring& fsConfig); int getCurrentBlockIndex() const; bool getCurrentBlockInfo(BlockInfo*& blockInfo); int loadFileTypesList(); int loadRecTypesList(string fileType); void fillFoldStructs(); void onFoldStructSelect(); void onFoldStructSelectFill(FoldStructInfo* fsInfo); void enableMoveStructButtons(); void enableStructSelection(); int moveStructType(move_dir dir); int structEditAccept(bool accept = true); void structEditNew(); void structEditClone(); int structEditDelete(); void fillFoldBlocks(); void onFoldBlockSelect(); void onFoldBlockSelectFill(BlockInfo* blockInfo); void enableMoveBlockButtons(); void enableBlockSelection(); int moveBlockType(move_dir dir); int blockEditAccept(bool accept = true); void blockEditNew(bool clone); int blockEditDelete(); void fillImplicitEndRecs(); void fillExplicitEndRecs(BlockInfo* blockInfo); void onEndRecSelect(); void onEndRecSelectFill(); void enableEndRecSelection(); int endRecEditAccept(bool accept = true); void endRecEditNew(); int endRecEditDelete(); wstring structsFile{}; bool loadingEdits{}, cleanStructsFile{ true }, cleanStructVals{ true }, cleanBlockVals{ true }, cleanEndRecVals{ true }; HWND hFoldStructs{}, hFTList{}, hFoldBlocks{}, hHdrRTList{}, hImplRecs{}, hExplRecs{}, hExplRTList{}; vector<TypeInfo> vFileTypes{}; vector<TypeInfo> vRecTypes{}; vector<FoldStructInfo> vFoldStructs{}; };
2,848
C++
.h
87
28.563218
123
0.733577
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,133
AboutDialog.h
shriprem_FWDataViz/src/Dialogs/AboutDialog.h
#pragma once #include "../Utils.h" #include "../NPP/StaticDialog.h" using Utils::getVersionInfo; extern NppData nppData; class AboutDialog : public StaticDialog { public: AboutDialog() : StaticDialog() {}; void doDialog(HINSTANCE hInst); void refreshDarkMode(); private: INT_PTR CALLBACK run_dlgProc(UINT Message, WPARAM wParam, LPARAM lParam); void localize(); };
385
C++
.h
14
25.071429
76
0.754098
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,134
NppDarkMode.h
shriprem_FWDataViz/src/Darkmode/NppDarkMode.h
// This file is part of Notepad++ project // Copyright (c) 2021 adzm / Adam D. Walling // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // at your option any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #pragma once #pragma comment(lib, "dwmapi.lib") #pragma comment(lib, "comctl32.lib") #pragma comment(lib, "shlwapi.lib") #pragma comment(lib, "uxtheme.lib") #include "../NPP/Notepad_plus_msgs.h" constexpr COLORREF HEXRGB(DWORD rrggbb) { // from 0xRRGGBB like natural #RRGGBB // to the little-endian 0xBBGGRR return ((rrggbb & 0xFF0000) >> 16) | ((rrggbb & 0x00FF00) ) | ((rrggbb & 0x0000FF) << 16); } namespace NppDarkMode { struct Colors { COLORREF background = 0; COLORREF softerBackground = 0; COLORREF hotBackground = 0; COLORREF pureBackground = 0; COLORREF errorBackground = 0; COLORREF text = 0; COLORREF darkerText = 0; COLORREF disabledText = 0; COLORREF linkText = 0; COLORREF edge = 0; COLORREF hotEdge = 0; COLORREF disabledEdge = 0; }; enum class ToolTipsType { tooltip, toolbar, listview, treeview, tabbar }; enum class TreeViewStyle { classic = 0, light = 1, dark = 2 }; void initDarkMode(); void queryNPPDarkmode(); // sync options from NPP instance bool isEnabled(); bool isExperimentalSupported(); bool isWindows10(); bool isWindows11(); DWORD getWindowsBuildNumber(); COLORREF invertLightness(COLORREF c); COLORREF invertLightnessSofter(COLORREF c); double calculatePerceivedLightness(COLORREF c); COLORREF getBackgroundColor(); COLORREF getSofterBackgroundColor(); COLORREF getHotBackgroundColor(); COLORREF getDarkerBackgroundColor(); COLORREF getErrorBackgroundColor(); COLORREF getTextColor(); COLORREF getDarkerTextColor(); COLORREF getDisabledTextColor(); COLORREF getLinkTextColor(); COLORREF getEdgeColor(); COLORREF getHotEdgeColor(); COLORREF getDisabledEdgeColor(); HBRUSH getBackgroundBrush(); HBRUSH getDarkerBackgroundBrush(); HBRUSH getSofterBackgroundBrush(); HBRUSH getHotBackgroundBrush(); HBRUSH getErrorBackgroundBrush(); HBRUSH getEdgeBrush(); HBRUSH getHotEdgeBrush(); HBRUSH getDisabledEdgeBrush(); HPEN getDarkerTextPen(); HPEN getEdgePen(); HPEN getHotEdgePen(); HPEN getDisabledEdgePen(); // from DarkMode.h void allowDarkModeForApp(bool allow); bool allowDarkModeForWindow(HWND hWnd, bool allow); void setTitleBarThemeColor(HWND hWnd); // enhancements to DarkMode.h void enableDarkScrollBarForWindowAndChildren(HWND hwnd); inline void paintRoundFrameRect(HDC hdc, const RECT rect, const HPEN hpen, int width = 0, int height = 0); void subclassButtonControl(HWND hwnd); void subclassComboBoxControl(HWND hwnd); void subclassGroupboxControl(HWND hwnd); void subclassTabControl(HWND hwnd); bool subclassUpDownControl(HWND hwnd); void autoSubclassAndThemeChildControls(HWND hwndParent, bool subclass = true, bool theme = true); void autoThemeChildControls(HWND hwndParent); void setDarkTitleBar(HWND hwnd); void setDarkExplorerTheme(HWND hwnd); void setDarkScrollBar(HWND hwnd); void setDarkTooltips(HWND hwnd, ToolTipsType type); void setDarkLineAbovePanelToolbar(HWND hwnd); void setDarkListView(HWND hwnd); void disableVisualStyle(HWND hwnd, bool doDisable); void calculateTreeViewStyle(); void setTreeViewStyle(HWND hwnd); void setBorder(HWND hwnd, bool border = true); void initSysLink(HWND hCtl); LRESULT onCtlColor(HDC hdc); LRESULT onCtlColorSofter(HDC hdc); LRESULT onCtlColorDarker(HDC hdc); LRESULT onCtlColorError(HDC hdc); LRESULT onCtlColorSysLink(HDC hdc); LRESULT onCtlColorIfEnabled(HDC hdc, bool bEnabled); LRESULT onCtlHiliteIfEnabled(HDC hdc, bool bEnabled); INT_PTR onCtlColorListbox(WPARAM wParam, LPARAM lParam); }
4,520
C++
.h
127
31.409449
109
0.743584
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,135
DarkMode.h
shriprem_FWDataViz/src/Darkmode/DarkMode.h
#pragma once extern bool g_darkModeSupported; extern bool g_darkModeEnabled; bool ShouldAppsUseDarkMode(); bool AllowDarkModeForWindow(HWND hWnd, bool allow); bool IsHighContrast(); void RefreshTitleBarThemeColor(HWND hWnd); void SetTitleBarThemeColor(HWND hWnd, BOOL dark); bool IsColorSchemeChangeMessage(LPARAM lParam); bool IsColorSchemeChangeMessage(UINT message, LPARAM lParam); void AllowDarkModeForApp(bool allow); void EnableDarkScrollBarForWindowAndChildren(HWND hwnd); void InitDarkMode(); void SetDarkMode(bool useDarkMode, bool fixDarkScrollbar); bool IsWindows10(); bool IsWindows11(); DWORD GetWindowsBuildNumber();
634
C++
.h
17
36.117647
61
0.859935
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,137
NPP_Plugin_Darkmode.h
shriprem_FWDataViz/src/Darkmode/NPP_Plugin_Darkmode.h
#pragma once #include <Windows.h> #ifdef NPP_PLUGIN_DARKMODE_EXPORTS #define NPP_PLUGIN_DARKMODE_API __declspec(dllexport) #else #define NPP_PLUGIN_DARKMODE_API __declspec(dllimport) #endif // NPP_PLUGIN_DARKMODE_EXPORTS #ifdef NPP_PLUGIN_MODE_LIB_AND_DLL extern "C" NPP_PLUGIN_DARKMODE_API void NPPDM_InitDarkMode(const HWND _nppHandle); extern "C" NPP_PLUGIN_DARKMODE_API void NPPDM_QueryNPPDarkmode(); extern "C" NPP_PLUGIN_DARKMODE_API bool NPPDM_IsEnabled(); extern "C" NPP_PLUGIN_DARKMODE_API void NPPDM_AutoSubclassAndThemeChildControls(HWND hwndParent); extern "C" NPP_PLUGIN_DARKMODE_API void NPPDM_AutoThemeChildControls(HWND hwndParent); extern "C" NPP_PLUGIN_DARKMODE_API void NPPDM_SetDarkTitleBar(HWND hwnd); extern "C" NPP_PLUGIN_DARKMODE_API void NPPDM_InitSysLink(HWND hCtl); extern "C" NPP_PLUGIN_DARKMODE_API LRESULT NPPDM_OnCtlColor(HDC hdc); extern "C" NPP_PLUGIN_DARKMODE_API LRESULT NPPDM_OnCtlColorSofter(HDC hdc); extern "C" NPP_PLUGIN_DARKMODE_API LRESULT NPPDM_OnCtlColorDarker(HDC hdc); extern "C" NPP_PLUGIN_DARKMODE_API LRESULT NPPDM_OnCtlColorError(HDC hdc); extern "C" NPP_PLUGIN_DARKMODE_API LRESULT NPPDM_OnCtlColorSysLink(HDC hdc); extern "C" NPP_PLUGIN_DARKMODE_API LRESULT NPPDM_OnCtlColorIfEnabled(HDC hdc, bool isEnabled); extern "C" NPP_PLUGIN_DARKMODE_API LRESULT NPPDM_OnCtlHiliteIfEnabled(HDC hdc, bool isEnabled); extern "C" NPP_PLUGIN_DARKMODE_API INT_PTR NPPDM_OnCtlColorListbox(WPARAM wParam, LPARAM lParam); #else void NPPDM_InitDarkMode(const HWND _nppHandle); void NPPDM_QueryNPPDarkmode(); bool NPPDM_IsEnabled(); void NPPDM_AutoSubclassAndThemeChildControls(HWND hwndParent); void NPPDM_AutoThemeChildControls(HWND hwndParent); void NPPDM_SetDarkTitleBar(HWND hwnd); void NPPDM_InitSysLink(HWND hCtl); LRESULT NPPDM_OnCtlColor(HDC hdc); LRESULT NPPDM_OnCtlColorSofter(HDC hdc); LRESULT NPPDM_OnCtlColorDarker(HDC hdc); LRESULT NPPDM_OnCtlColorError(HDC hdc); LRESULT NPPDM_OnCtlColorSysLink(HDC hdc); LRESULT NPPDM_OnCtlColorIfEnabled(HDC hdc, bool isEnabled); LRESULT NPPDM_OnCtlHiliteIfEnabled(HDC hdc, bool isEnabled); INT_PTR NPPDM_OnCtlColorListbox(WPARAM wParam, LPARAM lParam); #endif // NPP_PLUGIN_MODE_LIB_AND_DLL
2,186
C++
.h
40
53.375
97
0.822482
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,543,139
dpiManagerV2.h
shriprem_FWDataViz/src/NPP/dpiManagerV2.h
// This file is part of Notepad++ project // Copyright (c) 2024 ozone10 and Notepad++ team // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // at your option any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #pragma once #include "../Darkmode/NppDarkMode.h" #ifndef WM_DPICHANGED #define WM_DPICHANGED 0x02E0 #endif #ifndef WM_DPICHANGED_BEFOREPARENT #define WM_DPICHANGED_BEFOREPARENT 0x02E2 #endif #ifndef WM_DPICHANGED_AFTERPARENT #define WM_DPICHANGED_AFTERPARENT 0x02E3 #endif #ifndef WM_GETDPISCALEDSIZE #define WM_GETDPISCALEDSIZE 0x02E4 #endif class DPIManagerV2 { public: DPIManagerV2() { setDpiWithSystem(); } virtual ~DPIManagerV2() = default; enum class FontType { menu, status, message, caption, smcaption }; static void initDpiAPI(); static int getSystemMetricsForDpi(int nIndex, UINT dpi); int getSystemMetricsForDpi(int nIndex) const { return getSystemMetricsForDpi(nIndex, _dpi); } static DPI_AWARENESS_CONTEXT setThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT dpiContext); static BOOL adjustWindowRectExForDpi(LPRECT lpRect, DWORD dwStyle, BOOL bMenu, DWORD dwExStyle, UINT dpi); static UINT getDpiForSystem(); static UINT getDpiForWindow(HWND hWnd); static UINT getDpiForParent(HWND hWnd) { return getDpiForWindow(::GetParent(hWnd)); } void setDpiWithSystem() { _dpi = getDpiForSystem(); } // parameter is WPARAM void setDpiWP(WPARAM wParam) { _dpi = LOWORD(wParam); } void setDpi(UINT newDpi) { _dpi = newDpi; } void setDpi(HWND hWnd) { setDpi(getDpiForWindow(hWnd)); } void setDpiWithParent(HWND hWnd) { setDpi(::GetParent(hWnd)); } UINT getDpi() const { return _dpi; } static void setPositionDpi(LPARAM lParam, HWND hWnd, UINT flags = SWP_NOZORDER | SWP_NOACTIVATE); static int scale(int x, UINT toDpi, UINT fromDpi) { return MulDiv(x, toDpi, fromDpi); } static int scale(int x, UINT dpi) { return scale(x, dpi, USER_DEFAULT_SCREEN_DPI); } static int unscale(int x, UINT dpi) { return scale(x, USER_DEFAULT_SCREEN_DPI, dpi); } static int scale(int x, HWND hWnd) { return scale(x, getDpiForWindow(hWnd), USER_DEFAULT_SCREEN_DPI); } static int unscale(int x, HWND hWnd) { return scale(x, USER_DEFAULT_SCREEN_DPI, getDpiForWindow(hWnd)); } int scale(int x) const { return scale(x, _dpi); } int unscale(int x) const { return unscale(x, _dpi); } static int scaleFont(int pt, UINT dpi) { return -(scale(pt, dpi, 72)); } static int scaleFont(int pt, HWND hWnd) { return -(scale(pt, getDpiForWindow(hWnd), 72)); } int scaleFont(int pt) const { return scaleFont(pt, _dpi); } static LOGFONT getDefaultGUIFontForDpi(UINT dpi, FontType type = FontType::message); static LOGFONT getDefaultGUIFontForDpi(HWND hWnd, FontType type = FontType::message) { return getDefaultGUIFontForDpi(getDpiForWindow(hWnd), type); } LOGFONT getDefaultGUIFontForDpi(FontType type = FontType::message) const { return getDefaultGUIFontForDpi(_dpi, type); } static void loadIcon(HINSTANCE hinst, const wchar_t* pszName, int cx, int cy, HICON* phico, UINT fuLoad = LR_DEFAULTCOLOR); private: UINT _dpi = USER_DEFAULT_SCREEN_DPI; };
3,674
C++
.h
109
31.513761
124
0.76359
shriprem/FWDataViz
37
6
0
GPL-2.0
9/20/2024, 10:45:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false