Repository navigation
Expand file tree
/
Copy pathTranslationWindow.xaml.cs
More file actions
415 lines (352 loc) · 15.1 KB
/
Copy pathTranslationWindow.xaml.cs
File metadata and controls
415 lines (352 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.UI;
using Microsoft.UI.Composition.SystemBackdrops;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Windows.ApplicationModel.DataTransfer;
using Windows.Graphics;
using WinRT.Interop;
namespace TapLingo
{
public sealed partial class TranslationWindow : Window
{
private readonly AppSettings _settings;
private string _sourceText;
private bool _comboInitializing = true;
private MicaController? _micaController;
private DesktopAcrylicController? _acrylicController;
private SystemBackdropConfiguration? _backdropConfiguration;
private static readonly List<LanguageOption> SupportedLanguages = new()
{
new("he", "עברית"), new("en", "אנגלית"), new("ar", "ערבית"),
new("ru", "רוסית"), new("es", "ספרדית"), new("fr", "צרפתית"),
new("de", "גרמנית"), new("it", "איטלקית"), new("pt", "פורטוגזית"),
new("nl", "הולנדית"), new("pl", "פולנית"), new("tr", "טורקית"),
new("uk", "אוקראינית"), new("zh", "סינית"), new("ja", "יפנית"),
new("ko", "קוריאנית"), new("hi", "הינדית"), new("th", "תאית"),
new("vi", "ויאטנמית"), new("id", "אינדונזית")
};
public TranslationWindow(string text, AppSettings settings)
{
InitializeComponent();
_settings = settings;
_sourceText = text;
// 1. הגדרות החלון הבסיסיות
Title = "תרגום מהיר - TapLingo";
SourceTextBox.Text = text;
EngineLabel.Text = _settings.Engine == TranslationEngine.DeepL ? "DeepL" : "Google";
// 2. RTL ברמת הרכיב השורש (WinUI מצריך הגדרה נפרדת)
RootGrid.FlowDirection = FlowDirection.RightToLeft;
// 2.5 מעביר את כפתור הסגירה לצד שמאל (RTL)
ThemeHelper.EnableRtlCaptionButtons(this);
// 3. TitleBar מותאם אישית (נראה חלק עם Mica)
SetupCustomTitleBar();
// 4. הפעלת Mica/Acrylic (Fluent background)
TrySetSystemBackdrop();
// 4.5 החלת ערכת הנושא הנבחרת (בהיר/כהה/מערכת)
ThemeHelper.Apply(this, _settings.Theme, _backdropConfiguration);
// 5. מילוי קומבו השפות
PopulateLanguageCombo();
// 6. גודל ומיקום החלון
SetupWindowAppearance();
// 7. topmost (חלונית צפה)
SetTopmost(true);
// 8. תרגום ראשוני ברגע שהחלון נטען (או מיקוד בתיבת המקור אם ריק)
Activated += async (_, _) =>
{
if (LoadingPanel.Visibility != Visibility.Visible || !string.IsNullOrEmpty(TranslatedTextBox.Text))
return;
if (string.IsNullOrWhiteSpace(_sourceText))
{
// מצב הזנה ידנית - ממתינים שהמשתמש יקליד ויבקש תרגום
LoadingPanel.Visibility = Visibility.Collapsed;
SourceTextBox.Focus(FocusState.Programmatic);
}
else
{
await TranslateAsync();
}
};
Closed += (_, _) =>
{
_micaController?.Dispose();
_acrylicController?.Dispose();
_backdropConfiguration = null;
// יציאה מהאפליקציה כולה
Application.Current.Exit();
};
}
#region Custom TitleBar
private void SetupCustomTitleBar()
{
var appWindow = GetAppWindow();
if (appWindow == null) return;
// טעינת האייקון של האפליקציה עבור TitleBar + Taskbar + Alt+Tab
try
{
var iconPath = System.IO.Path.Combine(AppContext.BaseDirectory, "Assets", "AppIcon.ico");
if (System.IO.File.Exists(iconPath))
{
appWindow.SetIcon(iconPath);
}
}
catch { /* אייקון אופציונלי - לא קריטי */ }
if (AppWindowTitleBar.IsCustomizationSupported())
{
var titleBar = appWindow.TitleBar;
titleBar.ExtendsContentIntoTitleBar = true;
titleBar.ButtonBackgroundColor = Microsoft.UI.Colors.Transparent;
titleBar.ButtonInactiveBackgroundColor = Microsoft.UI.Colors.Transparent;
SetTitleBar(AppTitleBar); // הפיכת ה-Grid שלנו לאזור גרירה
}
else
{
// Fallback למערכות ישנות
ExtendsContentIntoTitleBar = true;
SetTitleBar(AppTitleBar);
}
}
#endregion
#region Mica / Acrylic Backdrop
private void TrySetSystemBackdrop()
{
if (MicaController.IsSupported())
{
_backdropConfiguration = new SystemBackdropConfiguration
{
Theme = SystemBackdropTheme.Default,
IsInputActive = true
};
_micaController = new MicaController();
_micaController.AddSystemBackdropTarget(
WinRT.CastExtensions.As<Microsoft.UI.Composition.ICompositionSupportsSystemBackdrop>(this));
_micaController.SetSystemBackdropConfiguration(_backdropConfiguration);
}
else if (DesktopAcrylicController.IsSupported())
{
_backdropConfiguration = new SystemBackdropConfiguration
{
Theme = SystemBackdropTheme.Default,
IsInputActive = true
};
_acrylicController = new DesktopAcrylicController();
_acrylicController.AddSystemBackdropTarget(
WinRT.CastExtensions.As<Microsoft.UI.Composition.ICompositionSupportsSystemBackdrop>(this));
_acrylicController.SetSystemBackdropConfiguration(_backdropConfiguration);
}
// אם אף אחד לא נתמך - פשוט משתמשים ברקע default של המערכת
}
#endregion
#region Window Sizing & Positioning
private AppWindow? GetAppWindow()
{
var hWnd = WindowNative.GetWindowHandle(this);
var windowId = Win32Interop.GetWindowIdFromWindow(hWnd);
return AppWindow.GetFromWindowId(windowId);
}
private void SetupWindowAppearance()
{
var appWindow = GetAppWindow();
if (appWindow == null) return;
// גודל חלון - ב-WinUI 3 הגודל הוא בפיקסלים פיזיים
var dpi = GetDpiForWindow(WindowNative.GetWindowHandle(this));
var scale = dpi / 96.0;
appWindow.Resize(new SizeInt32((int)(480 * scale), (int)(420 * scale)));
// מיקום לפי הגדרות
switch (_settings.WindowPosition?.ToLowerInvariant())
{
case "center":
CenterOnScreen(appWindow);
break;
case "top-right":
PositionCorner(appWindow, horizontalRight: true, verticalBottom: false);
break;
case "top-left":
PositionCorner(appWindow, horizontalRight: false, verticalBottom: false);
break;
case "bottom-right":
PositionCorner(appWindow, horizontalRight: true, verticalBottom: true);
break;
case "bottom-left":
PositionCorner(appWindow, horizontalRight: false, verticalBottom: true);
break;
case "cursor":
default:
PositionNearCursor(appWindow);
break;
}
// הסרת החצים של resize (WinUI 3 מאפשר זאת דרך presenter)
if (appWindow.Presenter is OverlappedPresenter op)
{
op.IsResizable = true;
op.IsMaximizable = false;
op.IsMinimizable = false;
}
}
private void CenterOnScreen(AppWindow appWindow)
{
var area = DisplayArea.GetFromWindowId(appWindow.Id, DisplayAreaFallback.Primary);
if (area == null) return;
var center = new PointInt32(
area.WorkArea.X + (area.WorkArea.Width - appWindow.Size.Width) / 2,
area.WorkArea.Y + (area.WorkArea.Height - appWindow.Size.Height) / 2);
appWindow.Move(center);
}
private void PositionCorner(AppWindow appWindow, bool horizontalRight, bool verticalBottom)
{
var area = DisplayArea.GetFromWindowId(appWindow.Id, DisplayAreaFallback.Primary);
if (area == null) return;
const int margin = 20;
int x = horizontalRight
? area.WorkArea.X + area.WorkArea.Width - appWindow.Size.Width - margin
: area.WorkArea.X + margin;
int y = verticalBottom
? area.WorkArea.Y + area.WorkArea.Height - appWindow.Size.Height - margin
: area.WorkArea.Y + margin;
appWindow.Move(new PointInt32(x, y));
}
private void PositionNearCursor(AppWindow appWindow)
{
if (!GetCursorPos(out var pt)) { CenterOnScreen(appWindow); return; }
var area = DisplayArea.GetFromPoint(new PointInt32(pt.X, pt.Y), DisplayAreaFallback.Primary);
if (area == null) { CenterOnScreen(appWindow); return; }
int x = pt.X + 15;
int y = pt.Y + 15;
if (x + appWindow.Size.Width > area.WorkArea.X + area.WorkArea.Width)
x = area.WorkArea.X + area.WorkArea.Width - appWindow.Size.Width - 10;
if (y + appWindow.Size.Height > area.WorkArea.Y + area.WorkArea.Height)
y = area.WorkArea.Y + area.WorkArea.Height - appWindow.Size.Height - 10;
appWindow.Move(new PointInt32(x, y));
}
private void SetTopmost(bool topmost)
{
var appWindow = GetAppWindow();
if (appWindow?.Presenter is OverlappedPresenter op)
{
op.IsAlwaysOnTop = topmost;
}
}
#endregion
#region Language Combo + Translation
private void PopulateLanguageCombo()
{
foreach (var lang in SupportedLanguages)
{
TargetLangCombo.Items.Add(new ComboBoxItem { Content = lang.Display, Tag = lang.Code });
}
// סימון הברירת מחדל
for (int i = 0; i < TargetLangCombo.Items.Count; i++)
{
if (TargetLangCombo.Items[i] is ComboBoxItem cbi && (string)cbi.Tag! == _settings.TargetLanguage)
{
TargetLangCombo.SelectedIndex = i;
break;
}
}
if (TargetLangCombo.SelectedIndex < 0) TargetLangCombo.SelectedIndex = 0;
_comboInitializing = false;
}
private async void TargetLangCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_comboInitializing) return;
if (TargetLangCombo.SelectedItem is ComboBoxItem cbi && cbi.Tag is string code)
{
_settings.TargetLanguage = code;
await TranslateAsync();
}
}
private async Task TranslateAsync()
{
try
{
LoadingPanel.Visibility = Visibility.Visible;
TranslatedTextBox.Text = "";
DetectedLangLabel.Text = "";
_sourceText = SourceTextBox.Text;
if (string.IsNullOrWhiteSpace(_sourceText))
{
TranslatedTextBox.Text = "(אין טקסט לתרגום)";
return;
}
var result = await TranslationService.TranslateAsync(_sourceText, _settings);
TranslatedTextBox.Text = result.TranslatedText;
if (!string.IsNullOrEmpty(result.DetectedSourceLanguage))
DetectedLangLabel.Text = $"זוהה: {result.DetectedSourceLanguage}";
if (_settings.AutoCopyToClipboard && !string.IsNullOrEmpty(result.TranslatedText))
CopyToClipboard(result.TranslatedText);
}
catch (Exception ex)
{
TranslatedTextBox.Text = $"⚠️ שגיאה בתרגום:\n{ex.Message}";
}
finally
{
LoadingPanel.Visibility = Visibility.Collapsed;
}
}
#endregion
#region Button Handlers
private void CopyButton_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(TranslatedTextBox.Text))
{
CopyToClipboard(TranslatedTextBox.Text);
ShowCopiedFeedback();
}
}
private async void RetranslateButton_Click(object sender, RoutedEventArgs e)
{
await TranslateAsync();
}
private void SettingsButton_Click(object sender, RoutedEventArgs e)
{
var win = new SettingsWindow(_settings);
win.Activate();
}
private void AboutButton_Click(object sender, RoutedEventArgs e)
{
var win = new SettingsWindow(_settings, focusAbout: true);
win.Activate();
}
private static void CopyToClipboard(string text)
{
try
{
var dp = new DataPackage();
dp.SetText(text);
Clipboard.SetContent(dp);
}
catch { /* clipboard may be busy */ }
}
private async void ShowCopiedFeedback()
{
var original = TitleText.Text;
TitleText.Text = "✓ הועתק!";
await Task.Delay(1200);
TitleText.Text = original;
}
#endregion
#region Win32 interop
[StructLayout(LayoutKind.Sequential)]
private struct POINT { public int X, Y; }
[DllImport("user32.dll")]
private static extern bool GetCursorPos(out POINT p);
[DllImport("user32.dll")]
private static extern uint GetDpiForWindow(IntPtr hWnd);
#endregion
private class LanguageOption
{
public string Code { get; }
public string Display { get; }
public LanguageOption(string code, string name)
{
Code = code;
Display = $"{name} ({code})";
}
}
}
}