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
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
using System.Drawing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Dapplo.Windows.User32;
using ScreenGrab.Extensions;
using ScreenGrab.Utilities;
using Color = System.Windows.Media.Color;
using Point = System.Windows.Point;
using Size = System.Windows.Size;

namespace ScreenGrab;

public enum OcrType
{
    WechatOCR,
    ComicOCR
}

/// <summary>
///     Extracted from the project <see href="https://github.com/TheJoeFin/Text-Grab" />
/// </summary>
public partial class ScreenGrabView
{
    #region Constructors

    public ScreenGrabView(Action<Bitmap, string>? action, bool isAuxiliary = false)
    {
        InitializeComponent();
        _onImageCaptured = action;
        _isAuxiliary = isAuxiliary;
    }

    #endregion Constructors

    #region Properties

    public Action? OnGrabClose { get; set; }
    private DisplayInfo? CurrentScreen { get; set; }

    public OcrType _OcrMode { get; set; } = OcrType.WechatOCR;



    #endregion Properties

    #region Fields

    private Point _clickedPoint;
    private DpiScale? _dpiScale;
    private bool _isSelecting;
    private bool _isShiftDown;
    private double _selectLeft;
    private double _selectTop;
    private Point _shiftPoint;
    private double _xShiftDelta;
    private double _yShiftDelta;
    private Point _promptMsgTopLeft;
    private Point _promptMsgBottomRight;
    private bool _isFreezeHandle;

    private readonly Border _selectBorder = new();
    private const double SelectBorderThickness = 2;
    private readonly Color _borderColor = Color.FromArgb(255, 146, 202, 244);

    private readonly Action<Bitmap, string>? _onImageCaptured;
    private readonly bool _isAuxiliary;

    #endregion Fields

    #region Window Events

    private void Window_Closed(object? sender, EventArgs e)
    {
        InputMethodOperate(false);

        Close();

        GC.Collect();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        WindowState = WindowState.Maximized;
        FullWindow.Rect = new Rect(0, 0, Width, Height);
        KeyDown += ScreenGrab_KeyDown;
        KeyUp += ScreenGrab_KeyUp;

        SetImageToBackground();

#if DEBUG
        Topmost = false;
#endif
        InputMethodOperate();

        if (this.IsMouseInWindow())
            SetPromptMsgVisibility(true);

        if (!_isAuxiliary) return;
        (HorizontalLine.X1, VerticalLine.Y1, (HorizontalLine.X2, VerticalLine.Y2)) = (0, 0, this.GetWidthHeight());

        // Set the Auxiliary to be visible when the mouse in the window
        if (this.IsMouseInWindow())
            SetAuxiliaryVisibility(true);
    }

    private void Window_Unloaded(object sender, RoutedEventArgs e)
    {
        FreezeBgImage();
        BackgroundImage.UpdateLayout();
        CurrentScreen = null;
        _dpiScale = null;

        Loaded -= Window_Loaded;
        Unloaded -= Window_Unloaded;

        RegionClickCanvas.MouseDown -= RegionClickCanvas_MouseDown;
        RegionClickCanvas.MouseMove -= RegionClickCanvas_MouseMove;
        RegionClickCanvas.MouseUp -= RegionClickCanvas_MouseUp;

        KeyDown -= ScreenGrab_KeyDown;
        KeyUp -= ScreenGrab_KeyUp;
    }

    private void ScreenGrab_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.Key)
        {
            case Key.Escape:
                CloseAllScreenGrabs();
                break;
            case Key.F:
                FreezeUnfreezeAllScreenGrabs();
                break;
            case Key.O:
                if (_OcrMode == OcrType.WechatOCR)
                {
                    _OcrMode = OcrType.ComicOCR;
                    OCRTYPE.Text = "漫画识别";
                }
                else if (_OcrMode == OcrType.ComicOCR)
                {
                    _OcrMode = OcrType.WechatOCR;
                    OCRTYPE.Text = "文字识别";
                }
                break;
        }
    }

    private void ScreenGrab_KeyUp(object sender, KeyEventArgs e)
    {
        switch (e.Key)
        {
            case Key.LeftShift:
            case Key.RightShift:
                _isShiftDown = false;
                _clickedPoint = new Point(_clickedPoint.X + _xShiftDelta, _clickedPoint.Y + _yShiftDelta);
                break;
        }
    }

    private void SetImageToBackground()
    {
        FreezeBgImage();
        BackgroundImage.Source = this.GetWindowBoundsImage();
        BackgroundBrush.Opacity = 0.2;
    }

    private async void FreezeUnfreeze()
    {
        _isFreezeHandle = true;
        if (BackgroundImage.Source == null)
        {
            if (_isAuxiliary)
                SetAuxiliaryVisibility(false);

            SetPromptMsgVisibility(false);
            BackgroundBrush.Opacity = 0;
            await Task.Delay(150);
            SetImageToBackground();

            if (this.IsMouseInWindow())
            {
                SetAuxiliaryVisibility(_isAuxiliary);
                SetPromptMsgVisibility(true);
            }

            // 刷新提示词
            FreezeTb.Text = "取消冻结窗口";
        }
        else
        {
            FreezeBgImage();
            // 刷新提示词
            FreezeTb.Text = "冻结窗口";
        }
        _isFreezeHandle = false;
    }

    private void CloseAllScreenGrabs()
    {
        foreach (var window in Application.Current.Windows)
            if (window is ScreenGrabView sgv)
                sgv.Close();
        OnGrabClose?.Invoke();
    }

    private void FreezeUnfreezeAllScreenGrabs()
    {
        foreach (var window in Application.Current.Windows)
            if (window is ScreenGrabView sgv)
                sgv.FreezeUnfreeze();
    }

    private void FreezeBgImage()
    {
        BackgroundImage.Source?.Freeze();
        BackgroundImage.Source = null;
    }

    private void SetAuxiliaryVisibility(bool isVisible)
    {
        var setVisibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
        if (HorizontalLine.Visibility == setVisibility && VerticalLine.Visibility == setVisibility)
            return;
        HorizontalLine.Visibility = setVisibility;
        VerticalLine.Visibility = setVisibility;
    }

    private void SetPromptMsgVisibility(bool isVisible)
    {
        var setVisibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
        if (PromptMsg.Visibility == setVisibility)
            return;

        PromptMsg.Visibility = setVisibility;
    }

    #endregion

    #region Mouse Events

    private void RegionClickCanvas_MouseLeave(object sender, MouseEventArgs e)
    {
        SetAuxiliaryVisibility(false);
        SetPromptMsgVisibility(false);
    }

    private void RegionClickCanvas_MouseEnter(object sender, MouseEventArgs e)
    {
        SetAuxiliaryVisibility(_isAuxiliary);
        SetPromptMsgVisibility(true);

        // 获取 PromptMsg 控件的边界
        _promptMsgTopLeft = PromptMsg.TranslatePoint(new Point(0, 0), this);
        _promptMsgBottomRight =
            PromptMsg.TranslatePoint(new Point(PromptMsg.ActualWidth, PromptMsg.ActualHeight), this);
    }

    private void RegionClickCanvas_MouseDown(object sender, MouseButtonEventArgs e)
    {
        // Right click to close
        if (e.RightButton == MouseButtonState.Pressed)
        {
            CloseAllScreenGrabs();
            return;
        }

        _isSelecting = true;
        SetAuxiliaryVisibility(false);
        SetPromptMsgVisibility(false);
        RegionClickCanvas.CaptureMouse();
        CursorClipper.ClipCursor(this);
        _clickedPoint = e.GetPosition(this);
        _selectBorder.Height = 2;
        _selectBorder.Width = 2;

        _dpiScale = VisualTreeHelper.GetDpi(this);

        try
        {
            RegionClickCanvas.Children.Remove(_selectBorder);
        }
        catch (Exception)
        {
            // ignored
        }

        _selectBorder.BorderThickness = new Thickness(SelectBorderThickness);
        _selectBorder.BorderBrush = new SolidColorBrush(_borderColor);
        _ = RegionClickCanvas.Children.Add(_selectBorder);
        Canvas.SetLeft(_selectBorder, _clickedPoint.X);
        Canvas.SetTop(_selectBorder, _clickedPoint.Y);

        // Initialize ClippingGeometry.Rect with a valid Rect
        ClippingGeometry.Rect = new Rect(_clickedPoint, new Size(0, 0));

        WindowUtilities.GetMousePosition(out var mousePoint);
        foreach (var screen in DisplayInfo.AllDisplayInfos)
        {
            var bound = screen.ScaledBounds();
            if (bound.Contains(mousePoint))
                CurrentScreen = screen;
        }
    }

    private void RegionClickCanvas_MouseMove(object sender, MouseEventArgs e)
    {
        if (_isFreezeHandle) return;

        var movingPoint = e.GetPosition(this);

        if (!_isSelecting)
        {
            // 检查鼠标是否在 PromptMsg 控件区域内
            var isMouseInPromptMsg = movingPoint.X >= _promptMsgTopLeft.X && movingPoint.X <= _promptMsgBottomRight.X &&
                                     movingPoint.Y >= _promptMsgTopLeft.Y && movingPoint.Y <= _promptMsgBottomRight.Y;

            SetPromptMsgVisibility(!isMouseInPromptMsg);

            // Determine whether to update auxiliary line information based on configuration
            if (!_isAuxiliary) return;

            // Update the horizontal line to match the mouse Y position
            HorizontalLine.Y1 = HorizontalLine.Y2 = movingPoint.Y;

            // Update the vertical line to match the mouse X position
            VerticalLine.X1 = VerticalLine.X2 = movingPoint.X;
            return;
        }

        if (Keyboard.Modifiers == ModifierKeys.Shift)
        {
            PanSelection(movingPoint);
            return;
        }

        _isShiftDown = false;

        var left = Math.Min(_clickedPoint.X, movingPoint.X);
        var top = Math.Min(_clickedPoint.Y, movingPoint.Y);

        _selectBorder.Height = Math.Max(_clickedPoint.Y, movingPoint.Y) - top;
        _selectBorder.Width = Math.Max(_clickedPoint.X, movingPoint.X) - left;
        _selectBorder.Height += SelectBorderThickness;
        _selectBorder.Width += SelectBorderThickness;

        ClippingGeometry.Rect = new Rect(
            new Point(left, top),
            new Size(_selectBorder.Width - SelectBorderThickness, _selectBorder.Height - SelectBorderThickness));
        Canvas.SetLeft(_selectBorder, left - 1);
        Canvas.SetTop(_selectBorder, top - 1);
    }

    private void RegionClickCanvas_MouseUp(object sender, MouseButtonEventArgs e)
    {
        if (!_isSelecting || _dpiScale is null)
            return;

        _isSelecting = false;
        CurrentScreen = null;
        CursorClipper.UnClipCursor();
        RegionClickCanvas.ReleaseMouseCapture();
        ClippingGeometry.Rect = new Rect(new Point(0, 0), new Size(0, 0));

        // Get the scaled dimensions of the selection border except the border thickness
        var xDimScaled = (Canvas.GetLeft(_selectBorder) + SelectBorderThickness) * _dpiScale.Value.DpiScaleX;
        var yDimScaled = (Canvas.GetTop(_selectBorder) + SelectBorderThickness) * _dpiScale.Value.DpiScaleY;

        // Get the scaled dimensions of the selection border except the border thickness
        Rectangle regionScaled = new(
            (int)xDimScaled,
            (int)yDimScaled,
            (int)((_selectBorder.Width - 2 * SelectBorderThickness) * _dpiScale.Value.DpiScaleX),
            (int)((_selectBorder.Height - 2 * SelectBorderThickness) * _dpiScale.Value.DpiScaleY));

        try
        {
            RegionClickCanvas.Children.Remove(_selectBorder);
        }
        catch
        {
            // ignored
        }

        var absPosPoint = this.GetAbsolutePosition();

        var thisCorrectedLeft = (int)absPosPoint.X + regionScaled.Left;
        var thisCorrectedTop = (int)absPosPoint.Y + regionScaled.Top;

        var correctedRegion = regionScaled with { X = thisCorrectedLeft, Y = thisCorrectedTop };
        var bitmap = correctedRegion.GetRegionOfScreenAsBitmap();
        CloseAllScreenGrabs();

        _onImageCaptured?.Invoke(bitmap, OCRTYPE.Text);
    }

    private void PanSelection(Point movingPoint)
    {
        if (!_isShiftDown)
        {
            _shiftPoint = movingPoint;
            _selectLeft = Canvas.GetLeft(_selectBorder);
            _selectTop = Canvas.GetTop(_selectBorder);
        }

        _isShiftDown = true;
        _xShiftDelta = movingPoint.X - _shiftPoint.X;
        _yShiftDelta = movingPoint.Y - _shiftPoint.Y;

        var leftValue = _selectLeft + _xShiftDelta;
        var topValue = _selectTop + _yShiftDelta;

        if (CurrentScreen is not null && _dpiScale is not null)
        {
            double currentScreenLeft = 0;
            double currentScreenTop = 0;
            var currentScreenRight = CurrentScreen.Bounds.Width / _dpiScale.Value.DpiScaleX;
            var currentScreenBottom = CurrentScreen.Bounds.Height / _dpiScale.Value.DpiScaleY;

            leftValue = Clamp(leftValue, currentScreenLeft, currentScreenRight - _selectBorder.Width);
            topValue = Clamp(topValue, currentScreenTop, currentScreenBottom - _selectBorder.Height);
        }

        ClippingGeometry.Rect = new Rect(
            new Point(leftValue, topValue),
            new Size(_selectBorder.Width - 2, _selectBorder.Height - 2));
        Canvas.SetLeft(_selectBorder, leftValue - 1);
        Canvas.SetTop(_selectBorder, topValue - 1);
    }

    private double Clamp(double value, double min, double max)
    {
#if NETFRAMEWORK
        if (value < min) return min;
        if (value > max) return max;
        return value;
#else
        return Math.Clamp(value, min, max);
#endif
    }

    private void InputMethodOperate(bool isDisableInputMethod = true)
    {
        if (isDisableInputMethod)
        {
            // 禁用输入法编辑器
            InputMethod.SetIsInputMethodEnabled(this, false);
            // 设置输入法状态为英文
            InputMethod.SetPreferredImeState(this, InputMethodState.Off);
            // 设置为英文输入模式
            InputMethod.SetPreferredImeConversionMode(this, ImeConversionModeValues.Alphanumeric);
        }
        else
        {
            // 恢复输入法状态
            InputMethod.SetIsInputMethodEnabled(this, true);
            InputMethod.SetPreferredImeState(this, InputMethodState.DoNotCare);
        }
    }

    #endregion
}