-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
448 lines (382 loc) · 16.4 KB
/
MainWindow.xaml.cs
File metadata and controls
448 lines (382 loc) · 16.4 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
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
using System;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using WpfControls = System.Windows.Controls;
using SW = System.Windows;
using System.Diagnostics; // <-- aggiunto per aprire il browser
namespace DeepLocal
{
public partial class MainWindow : Window
{
private const string OllamaHost = "http://127.0.0.1:11434";
private string _model = "gemma3:12b";
private static readonly HttpClient http = new();
private readonly string[] _supported = new[]
{
"Italian","English","Spanish","French","German","Russian","Hebrew","Japanese","Chinese"
};
private string _lastExplicitSourceLang = "English";
private bool _isSwapping = false;
// Hotkey ALT+T
private const int HOTKEY_ID = 9000;
private const uint MOD_ALT = 0x0001;
private const int WM_HOTKEY = 0x0312;
private const int WM_DPICHANGED = 0x02E0;
[DllImport("user32.dll")] static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")] static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private HwndSource? _source;
public MainWindow()
{
InitializeComponent();
// Quando torna visibile (es. dalla X → tray → riapri), ri-snap in basso-destra
this.IsVisibleChanged += (_, e) =>
{
if (this.IsVisible)
{
App.PlaceWindowBottomRight(this);
App.ResnapAfterFirstLayout(this);
}
};
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
// Hotkey ALT+T
var helper = new WindowInteropHelper(this);
_source = HwndSource.FromHwnd(helper.Handle);
_source?.AddHook(HwndHook);
RegisterHotKey(helper.Handle, HOTKEY_ID, MOD_ALT, (uint)KeyInterop.VirtualKeyFromKey(Key.T));
}
protected override void OnContentRendered(EventArgs e)
{
base.OnContentRendered(e);
// Modello dal combo
var selItem = ModelCombo?.SelectedItem as WpfControls.ComboBoxItem;
var tag = selItem?.Tag as string;
if (!string.IsNullOrWhiteSpace(tag)) _model = tag!;
// Init last-explicit se non Auto
var src = GetLang(SourceLang);
if (!string.Equals(src, "Auto", StringComparison.OrdinalIgnoreCase))
_lastExplicitSourceLang = src;
ApplyFlow(SourceLang, SourceBox);
ApplyFlow(TargetLang, TargetBox);
StatusModel.Text = $"Model: {_model} | Ollama: {OllamaHost}";
}
protected override void OnClosed(EventArgs e)
{
if (_source != null)
{
_source.RemoveHook(HwndHook);
UnregisterHotKey(_source.Handle, HOTKEY_ID);
}
base.OnClosed(e);
}
private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_HOTKEY && wParam.ToInt32() == HOTKEY_ID)
{
_ = TranslateClipboardAsync();
handled = true;
}
else if (msg == WM_DPICHANGED)
{
// Cambio monitor / scaling: ri-posiziona subito
App.PlaceWindowBottomRight(this);
}
return IntPtr.Zero;
}
protected override void OnStateChanged(EventArgs e)
{
base.OnStateChanged(e);
if (WindowState == WindowState.Minimized)
{
this.Hide();
this.ShowInTaskbar = false;
}
else
{
this.ShowInTaskbar = true;
}
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
base.OnClosing(e);
if (!DeepLocal.App.AllowClose)
{
// Con la X non chiudere: manda in tray
e.Cancel = true;
this.WindowState = WindowState.Minimized;
}
}
// ===== Helpers lingue & flow =====
private static string GetLang(WpfControls.ComboBox cb)
=> (cb.SelectedItem as WpfControls.ComboBoxItem)?.Content?.ToString()?.Trim() ?? "";
private static void SetLang(WpfControls.ComboBox cb, string name)
{
if (string.IsNullOrWhiteSpace(name)) return;
for (int i = 0; i < cb.Items.Count; i++)
{
var itemName = (cb.Items[i] as WpfControls.ComboBoxItem)?.Content?.ToString()?.Trim();
if (string.Equals(itemName, name, StringComparison.OrdinalIgnoreCase))
{
cb.SelectedIndex = i;
return;
}
}
}
private static bool IsRtlLanguage(string lang)
=> string.Equals(lang, "Hebrew", StringComparison.OrdinalIgnoreCase);
private static void ApplyFlow(WpfControls.ComboBox? langCombo, SW.Controls.TextBox? targetBox)
{
if (langCombo == null || targetBox == null) return;
var lang = (langCombo.SelectedItem as WpfControls.ComboBoxItem)?.Content?.ToString() ?? "";
targetBox.FlowDirection = IsRtlLanguage(lang)
? SW.FlowDirection.RightToLeft
: SW.FlowDirection.LeftToRight;
}
private bool IsSupported(string lang)
{
foreach (var s in _supported)
if (string.Equals(s, lang, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
private static string NormalizeLang(string raw)
{
var t = (raw ?? "").Trim();
if (t.Equals("Chinese (Simplified)", StringComparison.OrdinalIgnoreCase)) return "Chinese";
if (t.Equals("Chinese (Traditional)", StringComparison.OrdinalIgnoreCase)) return "Chinese";
if (t.Equals("Hebrew (Hebrew)", StringComparison.OrdinalIgnoreCase)) return "Hebrew";
return t;
}
private void SourceLang_SelectionChanged(object sender, WpfControls.SelectionChangedEventArgs e)
{
if (_isSwapping) return;
if (!IsLoaded || SourceBox == null) return;
var current = GetLang(SourceLang);
if (!string.Equals(current, "Auto", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(current))
_lastExplicitSourceLang = current;
ApplyFlow(SourceLang, SourceBox);
}
private void TargetLang_SelectionChanged(object sender, WpfControls.SelectionChangedEventArgs e)
{
if (!IsLoaded || TargetBox == null) return;
ApplyFlow(TargetLang, TargetBox);
}
// ===== Swap =====
private void Swap_Click(object sender, RoutedEventArgs e)
{
string src = GetLang(SourceLang); // può essere "Auto"
string dst = GetLang(TargetLang); // esplicito
string newSource = dst;
string newTarget = !string.Equals(src, "Auto", StringComparison.OrdinalIgnoreCase)
? src
: _lastExplicitSourceLang;
_isSwapping = true;
try
{
SetLang(SourceLang, newSource);
SetLang(TargetLang, newTarget);
ApplyFlow(SourceLang, SourceBox);
ApplyFlow(TargetLang, TargetBox);
if (!string.Equals(newSource, "Auto", StringComparison.OrdinalIgnoreCase))
_lastExplicitSourceLang = newSource;
}
finally { _isSwapping = false; }
// Scambia i testi
var txt = SourceBox?.Text ?? string.Empty;
SourceBox!.Text = TargetBox?.Text ?? string.Empty;
TargetBox!.Text = txt;
StatusText.Text = $"Swapped → Source: {newSource} | Target: {newTarget}";
}
// ===== Azioni UI =====
private async void TranslateBtn_Click(object sender, RoutedEventArgs e)
=> await TranslateAsync(SourceBox?.Text ?? string.Empty);
private async void ClipboardBtn_Click(object sender, RoutedEventArgs e)
=> await TranslateClipboardAsync();
private void ClearAll_Click(object sender, RoutedEventArgs e)
{
SourceBox?.Clear();
TargetBox?.Clear();
StatusText.Text = "Cleared.";
}
private void CopyTranslated_Click(object sender, RoutedEventArgs e)
{
try
{
var text = TargetBox?.Text ?? string.Empty;
if (!string.IsNullOrWhiteSpace(text))
{
SW.Clipboard.SetText(text);
StatusText.Text = "Translation copied to clipboard.";
}
}
catch (Exception ex) { StatusText.Text = "Copy failed: " + ex.Message; }
}
public async Task TranslateClipboardAsync()
{
try
{
if (SW.Clipboard.ContainsText())
{
var txt = SW.Clipboard.GetText();
if (!string.IsNullOrWhiteSpace(txt))
{
SourceBox!.Text = txt;
// Mostra e snappa in basso-destra, sempre.
App.PlaceWindowBottomRight(this);
this.Show();
this.Activate();
App.ResnapAfterFirstLayout(this);
await TranslateAsync(txt);
}
}
}
catch (Exception ex) { StatusText.Text = "Clipboard error: " + ex.Message; }
}
// ===== Translate con auto-detect =====
private async Task TranslateAsync(string input)
{
if (string.IsNullOrWhiteSpace(input)) return;
// Auto-detect se Source è Auto
string currentSource = GetLang(SourceLang);
if (string.Equals(currentSource, "Auto", StringComparison.OrdinalIgnoreCase))
{
string detected = await DetectLanguageAsync(input);
if (!IsSupported(detected))
{
TargetBox.Text = "Unsupported language.";
StatusText.Text = "Unsupported source language.";
return;
}
_isSwapping = true;
SetLang(SourceLang, detected);
_isSwapping = false;
_lastExplicitSourceLang = detected;
ApplyFlow(SourceLang, SourceBox);
StatusText.Text = $"Detected language: {detected}";
}
string target = GetLang(TargetLang);
StatusText.Text = $"Translating → {target}...";
TranslateBtn.IsEnabled = false;
TargetBox?.Clear();
try
{
var prompt = BuildPrompt(input, target);
var payload = new { model = _model, prompt, stream = false };
using var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
using var resp = await http.PostAsync($"{OllamaHost}/api/generate", content);
resp.EnsureSuccessStatusCode();
using var s = await resp.Content.ReadAsStreamAsync();
using var doc = await JsonDocument.ParseAsync(s);
string raw = doc.RootElement.TryGetProperty("response", out var r) ? r.GetString() ?? "" : "";
string cleaned = CleanOutput(raw);
if (TargetBox != null) TargetBox.Text = cleaned;
StatusText.Text = "Ready.";
}
catch (Exception ex) { StatusText.Text = "Error: " + ex.Message; }
finally { TranslateBtn.IsEnabled = true; }
}
private async Task<string> DetectLanguageAsync(string text)
{
// Heuristics veloci (script)
foreach (var ch in text)
{
if (ch >= 0x0590 && ch <= 0x05FF) return "Hebrew";
if (ch >= 0x0400 && ch <= 0x04FF) return "Russian";
if ((ch >= 0x3040 && ch <= 0x30FF) || (ch >= 0x31F0 && ch <= 0x31FF)) return "Japanese";
if (ch >= 0x4E00 && ch <= 0x9FFF) return "Chinese";
}
string snippet = text.Length > 500 ? text.Substring(0, 500) : text;
var detectPrompt =
$@"You are a language identifier.
From the following text, answer with ONE label only from this set:
Italian, English, Spanish, French, German, Russian, Hebrew, Japanese, Chinese, Unsupported.
Text:
""{snippet.Replace("\"", "''")}""
Answer with exactly one label from the set above.";
try
{
var payload = new { model = _model, prompt = detectPrompt, stream = false };
using var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
using var resp = await http.PostAsync($"{OllamaHost}/api/generate", content);
resp.EnsureSuccessStatusCode();
using var s = await resp.Content.ReadAsStreamAsync();
using var doc = await JsonDocument.ParseAsync(s);
var ans = (doc.RootElement.TryGetProperty("response", out var r) ? r.GetString() ?? "" : "").Trim();
ans = NormalizeLang(ans);
if (ans.Contains('\n')) ans = ans.Split('\n')[0].Trim();
if (ans.Contains(' ')) ans = ans.Split(' ')[0].Trim();
return IsSupported(ans) ? ans : "Unsupported";
}
catch
{
return "Unsupported";
}
}
private static string BuildPrompt(string input, string targetLang)
{
return $@"
You are a professional translator.
Translate the following text into {targetLang}.
Output ONLY the translation in {targetLang} (no explanations, no labels, no quotes).
Preserve line breaks and basic punctuation.
Text:
{input}";
}
private static string CleanOutput(string text)
{
if (string.IsNullOrWhiteSpace(text)) return string.Empty;
string t = text.Trim();
// rimuovi backtick/quote ai bordi
t = t.Trim().Trim('`').Trim().Trim('"').Trim();
// rimuovi prefissi comuni
if (t.StartsWith("Translation:", StringComparison.OrdinalIgnoreCase))
t = t["Translation:".Length..].TrimStart();
if (t.StartsWith("Output:", StringComparison.OrdinalIgnoreCase))
t = t["Output:".Length..].TrimStart();
// taglia "END" finali eventuali
var lines = t.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
int end = lines.Length - 1;
while (end >= 0)
{
var l = lines[end].Trim();
if (l.Equals("END", StringComparison.OrdinalIgnoreCase) ||
l.Equals("END.", StringComparison.OrdinalIgnoreCase))
{
end--;
continue;
}
break;
}
return string.Join("\n", lines, 0, end + 1).TrimEnd();
}
private void ModelCombo_SelectionChanged(object sender, WpfControls.SelectionChangedEventArgs e)
{
var item = ModelCombo?.SelectedItem as WpfControls.ComboBoxItem;
var newModel = (item?.Tag as string) ?? item?.Content?.ToString();
if (!string.IsNullOrWhiteSpace(newModel))
_model = newModel!;
if (!this.IsLoaded) return;
StatusModel.Text = $"Model: {_model} | Ollama: {OllamaHost}";
}
// ===== NUOVO: handler per il pulsante ℹ️ =====
private void InfoBtn_Click(object sender, RoutedEventArgs e)
{
try
{
Process.Start(new ProcessStartInfo("https://github.com/ShinRalexis") { UseShellExecute = true });
StatusText.Text = "Opening GitHub…";
}
catch (Exception ex)
{
StatusText.Text = "Open link failed: " + ex.Message;
}
}
}
}