쿼리 편집기 레이아웃 — 카드 두 장, 갈래 칩, 그리고 《컨트롤명》 치환

목업대로 다시 짰다. 색·모서리·간격은 SheetMe 토큰을 그대로 쓴다.

■ 레이아웃

머리말(제목 + 대상 칩) / SQL 편집기 카드 / 치환 변수 카드 / 아래 버튼 줄.
편집기 카드에는 툴바(포맷·주석·자동완성 · 전체 지우기)와 상태 줄(연결 상태 · 글자·줄 수 · 줄,열)을 뒀다.
변수 카드에는 검색 + 갈래 칩 + 접이식 그룹 + 행마다 + 버튼을 뒀다.

+ 버튼을 넣은 이유는 더블클릭이 유일한 삽입 수단이었기 때문이다 — 화면에 드러나지 않는 조작이다.

■ 《컨트롤명》 치환 — 아예 없던 기능

레거시 화면에는 Controls 목록이 따로 있었다. 우리에겐 그 문법 자체가 없었다.
clsMDataTable.ConvertQuery 는 <<…>> 를 모두 치환한 뒤 《 로 다시 쪼개
poAllControlOnSheet(이름).GETVALUE 를 박는다(:78-94). 즉 같은 서식의 다른 컨트롤 값을
쿼리 조건에 넣을 수 있다.

이제 이 서식의 컨트롤이 '컨트롤' 갈래로 목록에 뜨고, 토크나이저도 《》 를 변수로 잡아
색이 붙고 검증에 걸린다. 다만 디자인 시점에는 컨트롤 목록이 없어 런타임이 무조건 "0" 으로
치환한다(:86) — 검증 실행이 통과해도 운영에서는 다른 값이 들어간다는 뜻이라 코드에 적어 뒀다.

■ 형식(String/Int32/DataRow) 표시

레거시가 '목록/형식' 두 열로 보여 주던 정보다. DataRow 인지 아닌지가 곧
'컬럼명을 더 채워야 하는가'를 뜻해서 고를 때 필요하다.

■ 갈래 칩

그룹이 일곱이라 칩으로 다 늘어놓으면 그것대로 목록이 된다.
'값이 어디서 오는가'로 네 갈래(환자·서식·컨트롤·작업자)로 묶고, 같은 칩을 다시 누르면 해제된다.

■ 포맷(Ctrl+Shift+F 상당 — 툴바 버튼)

예약어·함수를 대문자로 바꾸고 주요 절 앞에서 줄을 나누며 괄호 깊이만큼 들여쓴다.
문자열·주석·치환 변수는 손대지 않는다 — 특히 치환 변수는 대소문자가 맞아야 런타임이 찾으므로
대문자로 바꾸면 그 칸이 조용히 빈다. 이 포매터가 저지를 수 있는 가장 나쁜 일이라 테스트로 막았다.
두 번 눌러도 결과가 같다(안정성도 테스트로 고정).

단위 테스트 14건 추가(포매터 11 · 컨트롤 치환 3).
회귀: 테스트 230/230, 편집 스모크 실패 0, 팝업 점검 7/7, 검증 실행 점검 10/10,
DB 왕복 1,271건 diff 0/예외 0, 종이 렌더 P062 바이트 동일.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Msystech
2026-08-13 15:53:56 +09:00
co-authored by Claude Opus 5
parent 7ce7506286
commit 68fc01c6ba
13 changed files with 847 additions and 168 deletions
@@ -0,0 +1,24 @@
using System.Globalization;
using System.Windows.Data;
using SheetMe.Core.Catalog;
namespace SheetMe.Designer.Controls;
/// <summary>
/// 치환 변수 그룹을 처음에 펼쳐 둘지 — 그룹 이름으로 판단한다.
///
/// 일곱 그룹을 다 펴 두면 목록이 길어져 원하는 그룹이 화면 밖으로 밀리고,
/// 다 접어 두면 무엇이 있는지 한 번은 눌러 봐야 안다.
/// 가장 많이 쓰는 '환자'와, 이 서식에서만 유효해서 존재 자체가 정보인 '컨트롤'만 펴 둔다.
/// </summary>
public sealed class QueryGroupExpandedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var name = value as string ?? string.Empty;
return name is "환자" || name == LegacyQueryVariableCatalog.ControlGroup;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> throw new NotSupportedException();
}
@@ -113,7 +113,7 @@ public static class DialogShots
{
("01-sheet-open", () => new Views.SheetOpenDialogView(_ => SampleSheets())),
("02-sheet-history", () => new Views.SheetHistoryDialogView("S999", "표본 서식", SampleVersions())),
("03-query-editor", () => new Views.QueryEditorWindow("데이터소스",
("03-query-editor", () => NewQueryEditor(designer,
"SELECT ChtNum, PatNam FROM P_PatMst\nWHERE ChtNum = <<M.CMM.HISOperatingInfo.bzPatientInfo.ChtNum>>")),
// 실제 카탈로그(384종)와 실제 제안 순위로 찍는다 — 표본 몇 개로는 분류·건수가 안 보인다
("04-tag-picker", () => new Views.TagPickerDialogView(
@@ -311,6 +311,10 @@ public static class DialogShots
};
/// <summary>폰트 관리자·미리보기용 표본 문서 — 컨트롤이 있어야 목록이 비지 않는다</summary>
/// <summary>쿼리 편집기 — 이 서식의 컨트롤을 《컨트롤명》 후보로 넘겨 그룹이 실제로 차는지 본다</summary>
private static Window NewQueryEditor(DesignerViewModel designer, string sql)
=> new Views.QueryEditorWindow("데이터소스", sql, controlNames: designer.ControlNames());
private static DesignerViewModel SampleDesigner()
{
var document = new FormDocument { FormId = "S999", Title = "표본 서식" };
@@ -47,6 +47,7 @@
오류는 B.CloseHover 와 같은 값이라 다크 팔레트에 새 색이 늘지 않는다. -->
<SolidColorBrush x:Key="B.Warning" Color="#E0A33A" />
<SolidColorBrush x:Key="B.Danger" Color="#E04A2B" />
<SolidColorBrush x:Key="B.Ok" Color="#5BC46E" />
<!-- SQL 구문 색 — 어두운 배경 대비 4.5:1 이상 -->
<SolidColorBrush x:Key="B.SqlKeyword" Color="#6FB6F2" />
@@ -81,6 +81,7 @@
-->
<SolidColorBrush x:Key="B.Warning" Color="#B45309" />
<SolidColorBrush x:Key="B.Danger" Color="#C4321A" />
<SolidColorBrush x:Key="B.Ok" Color="#1A7F37" />
<!-- SQL 구문 색 — 흰 배경 대비 4.5:1 이상.
치환 변수는 이 편집기에서 가장 중요한 조각이라 가장 진하게 둔다. -->
@@ -946,6 +946,13 @@ public sealed class DesignerViewModel : ViewModelBase
}
}
/// <summary>
/// 문서의 모든 컨트롤 이름 — 쿼리의 《컨트롤명》 치환 후보.
/// 런타임도 같은 서식 안에서만 이름을 찾으므로(clsMDataTable 의 poAllControlOnSheet) 범위가 같다.
/// </summary>
public IReadOnlyList<string> ControlNames()
=> AllControls().Select(c => c.Id).Where(id => id.Length > 0).Distinct(StringComparer.Ordinal).ToList();
/// <summary>문서 전체 컨트롤 순회(컨테이너 자식 포함, 모델 순서)</summary>
private IEnumerable<ControlViewModel> AllControls()
{
@@ -130,7 +130,10 @@ public partial class DesignerCanvasView : UserControl
// 데이터소스(MDataTable)는 인라인 대신 전용 쿼리 편집기 창
if (target is DataTableViewModel dataTable)
{
var queryDialog = new QueryEditorWindow(dataTable.Id, dataTable.Model.Props.GetText("Query") ?? string.Empty)
// 《컨트롤명》 치환 후보 — 같은 서식의 컨트롤만 유효하다
var queryDialog = new QueryEditorWindow(dataTable.Id,
dataTable.Model.Props.GetText("Query") ?? string.Empty,
controlNames: subscribedDesigner.ControlNames())
{
Owner = Window.GetWindow(this),
};
+294 -129
View File
@@ -2,157 +2,322 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctl="clr-namespace:SheetMe.Designer.Controls"
Title="쿼리 편집" Width="1060" Height="640" MinWidth="780" MinHeight="440"
Title="쿼리 편집" Width="1180" Height="760" MinWidth="880" MinHeight="520"
WindowStartupLocation="CenterOwner" ShowInTaskbar="False"
Style="{StaticResource ThemedWindow}">
<DockPanel Margin="12">
<TextBlock x:Name="HintText" DockPanel.Dock="Top" Foreground="{DynamicResource B.Muted}" TextWrapping="Wrap" Margin="0,0,0,8"
Text="작성 시점에 &lt;&lt;변수&gt;&gt; 가 실제 값으로 치환됩니다. 변수는 클래스 전체 이름을 포함해야 하므로 우측 목록에서 삽입하세요 — 임의로 줄여 쓰면 치환되지 않고 SQL 에 그대로 남아 오류가 납니다."/>
<Window.Resources>
<!-- 처음 펼쳐 둘 그룹 판단 — 가장 많이 쓰는 '환자'와 이 서식의 컨트롤만 펴 둔다 -->
<ctl:QueryGroupExpandedConverter x:Key="GroupExpanded"/>
<DockPanel DockPanel.Dock="Bottom" Margin="0,10,0,0">
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
<TextBlock x:Name="LengthText" VerticalAlignment="Center" Margin="0,0,12,0"
Foreground="{DynamicResource B.Muted}" FontSize="11.5"/>
<Button x:Name="TrialButton" Content="검증 실행" Padding="14,5" Click="OnTrial"
ToolTip="DB 에서 실제로 돌려 봅니다 (F5). 조회만 실행되며 표본 몇 행만 가져옵니다."/>
<Button Content="확인" Padding="20,5" Margin="8,0,0,0" Click="OnConfirm" IsDefault="True"/>
<Button Content="취소" Padding="20,5" Margin="8,0,0,0" IsCancel="True"/>
<!-- 카드: 두 영역을 눈으로 갈라 준다 -->
<Style x:Key="Card" TargetType="Border">
<Setter Property="CornerRadius" Value="10"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush" Value="{DynamicResource B.InputBorder}"/>
<Setter Property="Background" Value="{DynamicResource B.Surface}"/>
</Style>
<Style x:Key="CardTitle" TargetType="TextBlock">
<Setter Property="FontSize" Value="13.5"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Foreground" Value="{DynamicResource B.Ink}"/>
</Style>
<!-- 편집기 툴바 버튼 -->
<Style x:Key="ToolBtn" TargetType="Button" BasedOn="{StaticResource Subtle}">
<Setter Property="Padding" Value="8,3"/>
<Setter Property="FontSize" Value="11.5"/>
<Setter Property="Foreground" Value="{DynamicResource B.Ink}"/>
</Style>
<!-- 갈래 칩 -->
<Style x:Key="BucketChip" TargetType="ToggleButton">
<Setter Property="FontSize" Value="11.5"/>
<Setter Property="Padding" Value="10,3"/>
<Setter Property="Margin" Value="0,0,6,0"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Foreground" Value="{DynamicResource B.Ink}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Border x:Name="chip" CornerRadius="12" Padding="{TemplateBinding Padding}"
Background="{DynamicResource B.Input}"
BorderBrush="{DynamicResource B.InputBorder}" BorderThickness="1">
<ContentPresenter VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="chip" Property="Background" Value="{DynamicResource B.Accent}"/>
<Setter TargetName="chip" Property="BorderBrush" Value="{DynamicResource B.Accent}"/>
<Setter Property="Foreground" Value="{DynamicResource B.OnAccent}"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="chip" Property="BorderBrush" Value="{DynamicResource B.Accent}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<DockPanel Margin="16,14,16,14">
<!-- ── 머리말 ── -->
<StackPanel DockPanel.Dock="Top" Margin="0,0,0,12">
<StackPanel Orientation="Horizontal">
<TextBlock Text="쿼리 편집" FontSize="17" FontWeight="Bold"
Foreground="{DynamicResource B.Ink}" VerticalAlignment="Center"/>
<Border x:Name="TargetChip" CornerRadius="6" Padding="8,2" Margin="10,0,0,0"
VerticalAlignment="Center"
Background="{DynamicResource B.Input}" BorderBrush="{DynamicResource B.InputBorder}"
BorderThickness="1">
<TextBlock x:Name="TargetChipText" FontSize="11.5" FontFamily="Consolas, D2Coding, 굴림체"
Foreground="{DynamicResource B.AccentText}"/>
</Border>
</StackPanel>
<TextBlock x:Name="HintText" Margin="0,6,0,0" FontSize="11.5" TextWrapping="Wrap"
Foreground="{DynamicResource B.Muted}"
Text="작성 시점에 &lt;&lt;변수&gt;&gt; 가 실제 값으로 치환됩니다. 변수는 클래스 전체 이름을 포함해야 하므로 우측 목록에서 삽입하세요."/>
</StackPanel>
<!-- ── 아래 버튼 줄 ── -->
<DockPanel DockPanel.Dock="Bottom" Margin="0,12,0,0">
<TextBlock x:Name="ProblemText" VerticalAlignment="Center" Margin="0,0,12,0"
Foreground="{DynamicResource B.Danger}" FontSize="11.5"
TextTrimming="CharacterEllipsis"/>
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
<Button x:Name="TrialButton" Padding="14,6" Click="OnTrial"
ToolTip="DB 에서 실제로 돌려 봅니다 (F5). 조회만 실행되며 표본 몇 행만 가져옵니다.">
<StackPanel Orientation="Horizontal">
<TextBlock Text="▶" FontSize="10" VerticalAlignment="Center" Margin="0,0,6,0"/>
<TextBlock Text="검증 실행" VerticalAlignment="Center"/>
</StackPanel>
</Button>
<Button Content="확인" Padding="24,6" Margin="8,0,0,0"
Style="{StaticResource Primary}" Click="OnConfirm" IsDefault="True"/>
<Button Content="취소" Padding="20,6" Margin="8,0,0,0" IsCancel="True"/>
</StackPanel>
</DockPanel>
<!-- 검증 결과 — 실행했을 때만 뜬다 -->
<Border x:Name="TrialPane" DockPanel.Dock="Bottom" Visibility="Collapsed" Margin="0,10,0,0"
MaxHeight="200" CornerRadius="6" BorderThickness="1"
BorderBrush="{DynamicResource B.InputBorder}" Background="{DynamicResource B.Surface}">
<DockPanel Margin="10,8">
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,6">
<Button DockPanel.Dock="Right" Content="닫기" Padding="8,1" Style="{StaticResource Subtle}"
Click="OnCloseTrial"/>
<TextBlock x:Name="TrialSummary" FontSize="11.5" TextWrapping="Wrap"/>
</DockPanel>
<DataGrid x:Name="TrialGrid" AutoGenerateColumns="True" IsReadOnly="True"
HeadersVisibility="Column" FontSize="11.5" MaxHeight="150"
GridLinesVisibility="Horizontal" Background="Transparent"
AutomationProperties.Name="검증 결과 표본"/>
</DockPanel>
</Border>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition x:Name="SplitterColumn" Width="8"/>
<ColumnDefinition x:Name="VariableColumn" Width="360"/>
<ColumnDefinition x:Name="SplitterColumn" Width="12"/>
<ColumnDefinition x:Name="VariableColumn" Width="430"/>
</Grid.ColumnDefinitions>
<!-- SQL 편집 영역.
색칠은 뒤에 깔린 SqlHighlightLayer 가 하고, 편집은 위에 얹힌 투명 TextBox 가 그대로 한다
(캐럿·선택·실행취소·IME 를 직접 만들지 않기 위해서다).
두 요소의 글꼴·크기·여백이 어긋나면 글자와 색이 어긋난다 — 반드시 같이 고칠 것. -->
<Border Grid.Column="0" BorderThickness="1" CornerRadius="6" ClipToBounds="True"
BorderBrush="{DynamicResource B.InputBorder}" Background="{DynamicResource B.Input}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!-- ══ SQL 편집기 카드 ══ -->
<Border Grid.Column="0" Style="{StaticResource Card}">
<DockPanel Margin="14,12,14,12">
<TextBlock DockPanel.Dock="Top" Text="SQL 편집기" Style="{StaticResource CardTitle}"
Margin="0,0,0,10"/>
<!-- 줄 번호 -->
<Border Grid.Column="0" Background="{DynamicResource B.Surface}" Padding="6,6,6,6">
<TextBlock x:Name="LineNumbers" FontFamily="Consolas, D2Coding, 굴림체" FontSize="13"
Foreground="{DynamicResource B.Muted}" TextAlignment="Right" MinWidth="26"/>
<!-- 툴바 -->
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,8">
<Button DockPanel.Dock="Right" Style="{StaticResource ToolBtn}" Click="OnClearAll"
Foreground="{DynamicResource B.Danger}" Content="전체 지우기"
ToolTip="편집 내용을 모두 지웁니다"/>
<StackPanel Orientation="Horizontal">
<Button Style="{StaticResource ToolBtn}" Content="포맷" Click="OnFormat"
ToolTip="예약어를 대문자로 바꾸고 절마다 줄을 나눕니다 (Ctrl+Shift+F). 문자열·치환 변수는 건드리지 않습니다."/>
<Button Style="{StaticResource ToolBtn}" Content="주석" Click="OnToggleComment"
ToolTip="선택한 줄에 -- 를 붙이거나 뗍니다 (Ctrl+/)"/>
<Button Style="{StaticResource ToolBtn}" Content="자동완성" Click="OnInvokeCompletion"
ToolTip="커서 위치에서 후보를 띄웁니다 (Ctrl+Space)"/>
</StackPanel>
</DockPanel>
<!-- 상태 줄 -->
<Border DockPanel.Dock="Bottom" Margin="0,8,0,0" Padding="10,5" CornerRadius="6"
Background="{DynamicResource B.Input}">
<DockPanel>
<TextBlock DockPanel.Dock="Right" x:Name="CaretText" FontSize="11"
Foreground="{DynamicResource B.Muted}"/>
<StackPanel Orientation="Horizontal">
<Ellipse x:Name="ConnDot" Width="7" Height="7" VerticalAlignment="Center"
Margin="0,0,6,0" Fill="{DynamicResource B.Muted}"/>
<TextBlock x:Name="ConnText" FontSize="11" VerticalAlignment="Center"
Foreground="{DynamicResource B.Muted}"/>
<TextBlock Text="│" FontSize="11" Margin="10,0" VerticalAlignment="Center"
Foreground="{DynamicResource B.InputBorder}"/>
<TextBlock x:Name="LengthText" FontSize="11" VerticalAlignment="Center"
Foreground="{DynamicResource B.Muted}"/>
</StackPanel>
</DockPanel>
</Border>
<Grid Grid.Column="1">
<ctl:SqlHighlightLayer x:Name="Highlight" IsHitTestVisible="False"/>
<!-- 자동완성 목록 — 커서 아래에 띄운다. StaysOpen 이라 목록을 눌러도 편집 포커스를 잃지 않는다 -->
<!-- StaysOpen=False 여야 바깥을 클릭했을 때 닫힌다.
True 로 두면 목록 항목을 고르기 전까지 화면에 계속 남는다. -->
<Popup x:Name="CompletionPopup" Placement="Relative" AllowsTransparency="True"
StaysOpen="False" PopupAnimation="None" Focusable="False">
<Border Background="{DynamicResource B.Surface}" BorderThickness="1"
BorderBrush="{DynamicResource B.InputBorder}" CornerRadius="6" Padding="2">
<ListBox x:Name="CompletionList" MaxHeight="240" MinWidth="260" FontSize="12"
BorderThickness="0" Background="Transparent"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
MouseDoubleClick="OnCompletionPicked">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel MinWidth="240">
<TextBlock DockPanel.Dock="Right" Text="{Binding KindLabel}" FontSize="10"
Foreground="{DynamicResource B.Muted}" Margin="10,0,0,0"
VerticalAlignment="Center"/>
<TextBlock Text="{Binding Text}" FontFamily="Consolas, D2Coding, 굴림체"
TextTrimming="CharacterEllipsis"/>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- 검증 결과 -->
<Border x:Name="TrialPane" DockPanel.Dock="Bottom" Visibility="Collapsed" Margin="0,8,0,0"
MaxHeight="190" CornerRadius="8" BorderThickness="1"
BorderBrush="{DynamicResource B.InputBorder}" Background="{DynamicResource B.Input}">
<DockPanel Margin="10,8">
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,6">
<Button DockPanel.Dock="Right" Content="닫기" Padding="8,1"
Style="{StaticResource ToolBtn}" Click="OnCloseTrial"/>
<TextBlock x:Name="TrialSummary" FontSize="11.5" TextWrapping="Wrap"/>
</DockPanel>
<DataGrid x:Name="TrialGrid" AutoGenerateColumns="True" IsReadOnly="True"
HeadersVisibility="Column" FontSize="11.5" MaxHeight="140"
GridLinesVisibility="Horizontal" Background="Transparent"
AutomationProperties.Name="검증 결과 표본"/>
</DockPanel>
</Border>
<!-- 편집 영역: 색칠 레이어 + 투명 TextBox -->
<Border BorderThickness="1" CornerRadius="8" ClipToBounds="True"
BorderBrush="{DynamicResource B.InputBorder}" Background="{DynamicResource B.Input}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Background="{DynamicResource B.Surface}" Padding="8,6">
<TextBlock x:Name="LineNumbers" FontFamily="Consolas, D2Coding, 굴림체" FontSize="13"
Foreground="{DynamicResource B.Muted}" TextAlignment="Right" MinWidth="24"/>
</Border>
</Popup>
<TextBox x:Name="SqlBox"
FontFamily="Consolas, D2Coding, 굴림체" FontSize="13"
AcceptsReturn="True" AcceptsTab="False"
TextWrapping="NoWrap" Padding="6"
Background="Transparent" BorderThickness="0"
Foreground="Transparent"
CaretBrush="{DynamicResource B.Ink}"
SelectionBrush="{DynamicResource B.Accent}" SelectionOpacity="0.35"
HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"
TextChanged="OnSqlChanged" PreviewKeyDown="OnSqlKeyDown"
SelectionChanged="OnSqlSelectionChanged" LostFocus="OnSqlLostFocus"
AutomationProperties.Name="SQL 편집"/>
</Grid>
</Grid>
<Grid Grid.Column="1">
<ctl:SqlHighlightLayer x:Name="Highlight" IsHitTestVisible="False"/>
<!-- StaysOpen=False 여야 바깥을 클릭했을 때 닫힌다 -->
<Popup x:Name="CompletionPopup" Placement="Relative" AllowsTransparency="True"
StaysOpen="False" PopupAnimation="None" Focusable="False">
<Border Background="{DynamicResource B.Surface}" BorderThickness="1"
BorderBrush="{DynamicResource B.InputBorder}" CornerRadius="8" Padding="3">
<ListBox x:Name="CompletionList" MaxHeight="260" MinWidth="280" FontSize="12"
BorderThickness="0" Background="Transparent"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
MouseDoubleClick="OnCompletionPicked">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel MinWidth="260">
<TextBlock DockPanel.Dock="Right" Text="{Binding KindLabel}" FontSize="10"
Foreground="{DynamicResource B.Muted}" Margin="10,0,0,0"
VerticalAlignment="Center"/>
<TextBlock Text="{Binding Text}" FontFamily="Consolas, D2Coding, 굴림체"
TextTrimming="CharacterEllipsis"/>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
</Popup>
<TextBox x:Name="SqlBox"
FontFamily="Consolas, D2Coding, 굴림체" FontSize="13"
AcceptsReturn="True" AcceptsTab="False"
TextWrapping="NoWrap" Padding="8,6"
Background="Transparent" BorderThickness="0"
Foreground="Transparent"
CaretBrush="{DynamicResource B.Ink}"
SelectionBrush="{DynamicResource B.Accent}" SelectionOpacity="0.35"
HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"
TextChanged="OnSqlChanged" PreviewKeyDown="OnSqlKeyDown"
SelectionChanged="OnSqlSelectionChanged" LostFocus="OnSqlLostFocus"
AutomationProperties.Name="SQL 편집"/>
</Grid>
</Grid>
</Border>
</DockPanel>
</Border>
<GridSplitter Grid.Column="1" Style="{StaticResource ColSplitter}"/>
<!-- 치환 변수 (SQL 용도에서만) -->
<DockPanel x:Name="VariablePane" Grid.Column="2">
<TextBlock DockPanel.Dock="Top" Text="치환 변수" FontWeight="Bold"
Foreground="{DynamicResource B.Muted}" Margin="4,0,0,6"/>
<TextBox x:Name="VariableSearch" DockPanel.Dock="Top" Margin="0,0,0,6" Padding="6,3"
VerticalContentAlignment="Center" TextChanged="OnVariableSearchChanged"
AutomationProperties.Name="치환 변수 검색"
ToolTip="이름·설명·초성으로 찾습니다 (예: ㅊㅌㅂㅎ → 차트번호)"/>
<TextBlock DockPanel.Dock="Bottom" x:Name="VariableHint" FontSize="10.5" TextWrapping="Wrap"
Foreground="{DynamicResource B.Muted}" Margin="4,6,0,0"
Text="더블클릭 또는 Enter 로 커서 위치에 삽입합니다."/>
<ListBox x:Name="VariableList" FontSize="11" MouseDoubleClick="OnInsertVariable"
KeyDown="OnVariableListKeyDown"
FontFamily="Consolas, D2Coding, 굴림체"
HorizontalContentAlignment="Stretch"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
AutomationProperties.Name="치환 변수 목록">
<!-- 토큰 전체(60자 넘음)를 줄마다 깔면 앞 40자가 전부 같아 정작 다른 부분이 잘린다.
설명 + 속성명만 띄우고 전체는 툴팁으로 둔다. -->
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel Margin="0,2" ToolTip="{Binding Token}">
<TextBlock DockPanel.Dock="Right" Text="{Binding ShortForm}"
Foreground="{DynamicResource B.Muted}" FontSize="10.5"
VerticalAlignment="Center" Margin="8,0,0,0"/>
<TextBlock Text="{Binding Description}" FontFamily="Segoe UI, 맑은 고딕" FontSize="12"
TextTrimming="CharacterEllipsis" VerticalAlignment="Center"/>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" FontWeight="Bold" Margin="2,8,0,3"
FontFamily="Segoe UI, 맑은 고딕" FontSize="12"
Foreground="{DynamicResource B.AccentText}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListBox.GroupStyle>
</ListBox>
</DockPanel>
<!-- ══ 치환 변수 카드 ══ -->
<Border x:Name="VariablePane" Grid.Column="2" Style="{StaticResource Card}">
<DockPanel Margin="14,12,14,12">
<TextBlock DockPanel.Dock="Top" Text="치환 변수" Style="{StaticResource CardTitle}"
Margin="0,0,0,10"/>
<TextBox x:Name="VariableSearch" DockPanel.Dock="Top" Margin="0,0,0,8" Padding="8,4"
VerticalContentAlignment="Center" TextChanged="OnVariableSearchChanged"
AutomationProperties.Name="치환 변수 검색"
ToolTip="변수명·설명·초성으로 찾습니다 (예: ㅊㅌㅂㅎ → 차트번호)"/>
<!-- 갈래 칩 -->
<ItemsControl x:Name="BucketChips" DockPanel.Dock="Top" Margin="0,0,0,8">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate><WrapPanel/></ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ToggleButton Style="{StaticResource BucketChip}"
IsChecked="{Binding IsActive, Mode=OneWay}"
Tag="{Binding Name}" Click="OnBucketClick">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Count}" Margin="6,0,0,0" Opacity="0.75"/>
</StackPanel>
</ToggleButton>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- 안내 -->
<Border DockPanel.Dock="Bottom" Margin="0,8,0,0" Padding="10,7" CornerRadius="8"
Background="{DynamicResource B.Input}">
<TextBlock x:Name="VariableHint" FontSize="10.5" TextWrapping="Wrap"
Foreground="{DynamicResource B.Muted}"/>
</Border>
<ListBox x:Name="VariableList" FontSize="11.5" MouseDoubleClick="OnInsertVariable"
KeyDown="OnVariableListKeyDown"
BorderThickness="0" Background="Transparent"
HorizontalContentAlignment="Stretch"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
AutomationProperties.Name="치환 변수 목록">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel Margin="0,3" ToolTip="{Binding Token}">
<!-- ⊕ 로 바로 삽입 — 더블클릭을 모르는 사람도 넣을 수 있어야 한다 -->
<Button DockPanel.Dock="Right" Width="22" Height="22" Padding="0"
Margin="8,0,0,0" Style="{StaticResource ToolBtn}"
Content="" FontSize="13"
Foreground="{DynamicResource B.AccentText}"
Command="{Binding DataContext.InsertCommand,
RelativeSource={RelativeSource AncestorType=ListBox}}"
CommandParameter="{Binding}"
ToolTip="커서 위치에 삽입"/>
<TextBlock DockPanel.Dock="Right" Text="{Binding ShortForm}"
Foreground="{DynamicResource B.Muted}" FontSize="10.5"
FontFamily="Consolas, D2Coding, 굴림체"
VerticalAlignment="Center" Margin="8,0,0,0"/>
<TextBlock Text="{Binding Description}" FontFamily="Segoe UI, 맑은 고딕" FontSize="12"
TextTrimming="CharacterEllipsis" VerticalAlignment="Center"/>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="GroupItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="GroupItem">
<Expander IsExpanded="{Binding Name,
Converter={StaticResource GroupExpanded}, Mode=OneTime}"
Margin="0,4,0,0">
<Expander.Header>
<DockPanel MinWidth="330">
<Border DockPanel.Dock="Right" CornerRadius="9" Padding="6,1"
VerticalAlignment="Center" Margin="6,0,0,0"
Background="{DynamicResource B.Input}">
<TextBlock Text="{Binding ItemCount}" FontSize="10"
Foreground="{DynamicResource B.Muted}"/>
</Border>
<TextBlock Text="{Binding Name}" FontWeight="SemiBold"
FontFamily="Segoe UI, 맑은 고딕" FontSize="12"/>
</DockPanel>
</Expander.Header>
<ItemsPresenter Margin="8,2,0,6"/>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListBox.GroupStyle>
</ListBox>
</DockPanel>
</Border>
</Grid>
</DockPanel>
</Window>
@@ -49,6 +49,17 @@ public partial class QueryEditorWindow : Window
/// <summary>목록이 걸려 있는 낱말의 끝 — 커서가 이 범위를 벗어나면 목록은 더 이상 유효하지 않다</summary>
private int completionEnd;
/// <summary>이 서식의 컨트롤 이름 — 《컨트롤명》 치환 후보</summary>
private readonly IReadOnlyList<string> controlNames;
/// <summary>고른 갈래 칩 — 빈 문자열이면 전체</summary>
private string activeBucket = string.Empty;
#endregion
#region Properties - Commands
/// <summary>목록 행의 + 버튼 — 더블클릭을 모르는 사람도 넣을 수 있어야 한다</summary>
public M.Framework.WPF.ICustomCommand InsertCommand { get; }
#endregion
#region Properties
@@ -60,16 +71,32 @@ public partial class QueryEditorWindow : Window
/// <param name="ownerLabel">제목에 붙일 대상 이름</param>
/// <param name="initialQuery">초기 텍스트</param>
/// <param name="showVariables">SQL 치환 변수 패널 표시 여부 — 상용구 등 SQL 이 아닌 용도에서는 false</param>
public QueryEditorWindow(string ownerLabel, string initialQuery, bool showVariables = true)
/// <param name="controlNames">
/// 같은 서식의 컨트롤 이름 — 《컨트롤명》 치환 후보가 된다.
/// 이 목록은 문서마다 다르므로 카탈로그가 아니라 호출부가 준다.
/// </param>
public QueryEditorWindow(string ownerLabel, string initialQuery, bool showVariables = true,
IReadOnlyList<string>? controlNames = null)
{
InitializeComponent();
isSql = showVariables;
this.controlNames = controlNames ?? Array.Empty<string>();
InsertCommand = new M.Framework.WPF.Command((object parameter) =>
{
if (parameter is QueryVariable variable)
{
InsertVariable(variable);
}
});
DataContext = this;
SqlBox.Text = initialQuery;
TargetChipText.Text = ownerLabel;
if (showVariables)
{
Title = $"쿼리 편집 — {ownerLabel}";
Highlight.Source = SqlBox;
RebuildBucketChips();
ApplyVariableFilter(string.Empty);
var connection = Services.ConfigService.Current.ConnectionString;
workbench = new SheetMe.Data.Stores.OracleQueryWorkbench(connection);
@@ -78,6 +105,8 @@ public partial class QueryEditorWindow : Window
TrialButton.IsEnabled = false;
TrialButton.ToolTip = "DB 접속이 설정되지 않아 검증 실행을 쓸 수 없습니다.";
}
ConnText.Text = workbench.CanUseDb ? "연결 상태: 정상" : "연결 상태: 없음(오프라인)";
ConnDot.Fill = (System.Windows.Media.Brush)FindResource(workbench.CanUseDb ? "B.Ok" : "B.Muted");
}
else
{
@@ -88,6 +117,8 @@ public partial class QueryEditorWindow : Window
VariablePane.Visibility = Visibility.Collapsed;
SplitterColumn.Width = new GridLength(0);
VariableColumn.Width = new GridLength(0);
TrialButton.Visibility = Visibility.Collapsed;
ConnText.Text = "텍스트 편집";
}
// 편집기가 스크롤되면 목록이 걸린 자리가 화면에서 움직인다 — 따라가지 않고 닫는다
@@ -429,10 +460,59 @@ public partial class QueryEditorWindow : Window
{
var text = SqlBox.Text;
LengthText.Text = $"{text.Length:N0}자 · {CountLines(text)}줄";
UpdateCaretText();
UpdateLineNumbers(text);
UpdateProblems(text);
}
/// <summary>줄·열 표시 — 오류 메시지의 위치를 찾아갈 때 쓴다</summary>
private void UpdateCaretText()
{
var caret = Math.Clamp(SqlBox.CaretIndex, 0, SqlBox.Text.Length);
var line = SqlBox.GetLineIndexFromCharacterIndex(caret);
var column = line >= 0 ? caret - SqlBox.GetCharacterIndexFromLineIndex(line) : 0;
CaretText.Text = $"줄 {Math.Max(0, line) + 1}, 열 {Math.Max(0, column) + 1}";
}
/// <summary>포맷 — 예약어 대문자, 절마다 줄바꿈. 문자열·치환 변수는 건드리지 않는다</summary>
private void OnFormat(object sender, RoutedEventArgs e)
{
if (!isSql)
{
return;
}
var formatted = SqlFormatter.Format(SqlBox.Text);
if (!string.Equals(formatted, SqlBox.Text, StringComparison.Ordinal))
{
SqlBox.Text = formatted;
SqlBox.CaretIndex = SqlBox.Text.Length;
}
}
private void OnToggleComment(object sender, RoutedEventArgs e)
{
SqlBox.Focus();
ToggleComment();
}
private void OnInvokeCompletion(object sender, RoutedEventArgs e)
{
SqlBox.Focus();
UpdateCompletion();
}
/// <summary>전체 지우기 — 되돌릴 수 있게 TextBox 실행취소에 남긴다</summary>
private void OnClearAll(object sender, RoutedEventArgs e)
{
if (SqlBox.Text.Length == 0)
{
return;
}
SqlBox.SelectAll();
SqlBox.SelectedText = string.Empty;
SqlBox.Focus();
}
private static int CountLines(string text)
{
var lines = 1;
@@ -714,23 +794,57 @@ public partial class QueryEditorWindow : Window
private void OnVariableSearchChanged(object sender, TextChangedEventArgs e)
=> ApplyVariableFilter(VariableSearch.Text);
/// <summary>이름·설명·초성으로 좁힌다 — 목록이 길어 눈으로 훑기 어렵다</summary>
/// <summary>카탈로그 + 이 서식의 컨트롤 — 컨트롤은 문서마다 달라 여기서 합친다</summary>
private IReadOnlyList<QueryVariable> AllVariables()
=> LegacyQueryVariableCatalog.All
.Concat(LegacyQueryVariableCatalog.ControlVariables(controlNames))
.ToList();
/// <summary>상단 칩을 다시 만든다 — 갈래별 개수는 검색과 무관하게 전체 기준으로 둔다</summary>
private void RebuildBucketChips()
{
var all = AllVariables();
var chips = new List<object>
{
new { Name = "전체", Count = all.Count, IsActive = activeBucket.Length == 0 },
};
foreach (var group in all.GroupBy(v => v.Bucket).OrderByDescending(g => g.Count()))
{
chips.Add(new { Name = group.Key, Count = group.Count(), IsActive = activeBucket == group.Key });
}
BucketChips.ItemsSource = chips;
}
private void OnBucketClick(object sender, RoutedEventArgs e)
{
if (sender is not System.Windows.Controls.Primitives.ToggleButton { Tag: string name })
{
return;
}
// 같은 칩을 다시 누르면 해제 — '전체'와 같은 뜻이라 따로 누를 필요가 없다
activeBucket = name == "전체" || activeBucket == name ? string.Empty : name;
RebuildBucketChips();
ApplyVariableFilter(VariableSearch.Text);
}
/// <summary>이름·설명·초성으로 좁히고 갈래 칩을 함께 적용한다</summary>
private void ApplyVariableFilter(string keyword)
{
var all = AllVariables();
var tokens = keyword.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var matched = tokens.Length == 0
? LegacyQueryVariableCatalog.All
: LegacyQueryVariableCatalog.All
.Where(v => tokens.All(t =>
TagSearch.Matches(v.Description, t) || TagSearch.Matches(v.Token, t)))
.ToList();
var matched = all
.Where(v => activeBucket.Length == 0 || v.Bucket == activeBucket)
.Where(v => tokens.Length == 0 || tokens.All(t =>
TagSearch.Matches(v.Description, t) || TagSearch.Matches(v.Token, t)))
.ToList();
var view = new CollectionViewSource { Source = matched };
view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(QueryVariable.Group)));
VariableList.ItemsSource = view.View;
VariableHint.Text = matched.Count == LegacyQueryVariableCatalog.All.Count
? $"{matched.Count}개 · 더블클릭 또는 Enter 로 삽입합니다."
: $"{matched.Count}/{LegacyQueryVariableCatalog.All.Count}개 · 더블클릭 또는 Enter 로 삽입니다.";
var scope = matched.Count == all.Count ? $"{matched.Count}개" : $"{matched.Count}/{all.Count}개";
VariableHint.Text = $"{scope} · + 를 누르거나 더블클릭하면 커서 위치에 삽입니다. " +
"편집기에서 << 를 치면 자동완성으로도 고를 수 있습니다.";
if (matched.Count > 0)
{
VariableList.SelectedIndex = 0;
@@ -750,10 +864,14 @@ public partial class QueryEditorWindow : Window
private void InsertSelectedVariable()
{
if (VariableList.SelectedItem is not QueryVariable variable)
if (VariableList.SelectedItem is QueryVariable variable)
{
return;
InsertVariable(variable);
}
}
private void InsertVariable(QueryVariable variable)
{
var caret = SqlBox.CaretIndex;
SqlBox.Text = SqlBox.Text.Insert(caret, variable.Token);
SqlBox.Focus();