-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainPage.xaml.cs
More file actions
504 lines (459 loc) · 17.8 KB
/
MainPage.xaml.cs
File metadata and controls
504 lines (459 loc) · 17.8 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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
using DynamicWebTWAIN.RestClient;
using Dynamsoft.DocumentViewer;
using System.Diagnostics;
using DynamicWebTWAIN.Service;
using System.Text.RegularExpressions;
namespace DWT_REST_MAUI
{
public class SelectedFile {
public byte[]? imageBytes = null;
}
public class HybridWebViewBridge : IWebViewBridge
{
private Microsoft.Maui.Controls.HybridWebView _webView;
public HybridWebViewBridge(Microsoft.Maui.Controls.HybridWebView webView)
{
_webView = webView;
}
public async Task<string?> ExecuteJavaScriptAsync(string script)
{
string? result = null;
await MainThread.InvokeOnMainThreadAsync(async () =>
{
result = await _webView.EvaluateJavaScriptAsync(script);
});
return result;
}
public void RegisterCallback(Func<string, bool> callback)
{
_webView.RawMessageReceived += (sender, args) =>
{
callback?.Invoke(args.Message);
};
}
public async Task LoadUrlAsync(Uri url)
{
var tcs = new TaskCompletionSource();
_webView.HybridRoot = "ddv";
_webView.DefaultFile = url.OriginalString;
await Task.CompletedTask;
}
}
[QueryProperty(nameof(LicenseChanged), "licenseChanged")]
public partial class MainPage : ContentPage
{
private ServiceManager _serviceManager;
private Dynamsoft.DocumentViewer.JSInterop _jsInterop;
private IScannerJobClient? scannerJob;
private Boolean isDesktop;
//use one-day trial license if you've not set the license in the settings
private string oneDayTrialLicense = "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9";
public static string defaultAddress = "https://127.0.0.1:18623";
string licenseChanged;
public string LicenseChanged
{
get => licenseChanged;
set
{
licenseChanged = value;
if (licenseChanged == "true")
{
AskWhetherToReload();
}
}
}
public MainPage()
{
#if WINDOWS
isDesktop = true;
_serviceManager = new ServiceManager(); // "dynamsoft.dwt.service"
_serviceManager.CreateService();
defaultAddress = _serviceManager.Service.BaseAddress.ToString();
#else
isDesktop = false;
#endif
InitializeComponent();
webView.SetInvokeJavaScriptTarget(this);
InitViewer();
RequestCameraPermission();
}
private async void RequestCameraPermission() {
PermissionStatus status = await Permissions.RequestAsync<Permissions.Camera>();
}
private async void AskWhetherToReload() {
bool answer = await DisplayAlert("Question?", "License is changed. Do you want to reload the page to make it effective?", "Yes", "No");
if (answer) {
Debug.WriteLine("reset viewer");
ResetViewer();
}
var currentPage = Shell.Current.CurrentState.Location.OriginalString;
try
{
Debug.WriteLine($"{currentPage}");
await Shell.Current.GoToAsync($"//{currentPage}"); //clear params
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
private async void ResetViewer() {
await webView.EvaluateJavaScriptAsync("location.reload();");
InitViewer();
}
private async void InitViewer()
{
try
{
Dynamsoft.DocumentViewer.JSInteropOptions options = new JSInteropOptions();
// because we load ddv page in the service, so we should make sure the service is running, so we need to set a long timeout
// or manual create a websocket connection in js, recommend this way.
options.ProductKey = Preferences.Get("License", oneDayTrialLicense);
if (options.ProductKey == "")
{
options.ProductKey = oneDayTrialLicense;
}
if (isDesktop)
{
options.SiteUrl = "index.html";
}
else {
options.SiteUrl = "mobile.html";
options.UIConfig = "mobile-default";
}
options.MessageType = "__RawMessage";
var bridge = new HybridWebViewBridge(webView);
if (isDesktop) {
_jsInterop = new Dynamsoft.DocumentViewer.JSInterop(options,
bridge,
_serviceManager.Service.BaseAddress);
}
else {
_jsInterop = new Dynamsoft.DocumentViewer.JSInterop(options,
bridge,
new Uri(defaultAddress));
}
await _jsInterop.EnsureInitializedAsync();
Func<string, bool> callback = (name) =>
{
if (name.Contains("loadFile"))
{
MainThread.BeginInvokeOnMainThread(() =>
{
_ = PickAndShow();
});
}
return true;
};
bridge.RegisterCallback(callback);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
if (ex.Message != null)
{
MainThread.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("Alert", ex.Message, "OK");
});
}
}
}
public async Task<SelectedFile?> PickAndShow()
{
SelectedFile? ret = null;
try
{
PickOptions options = new()
{
PickerTitle = "Please select a PDF/image file"
};
var result = await FilePicker.Default.PickAsync(options);
if (result != null)
{
using var stream = await result.OpenReadAsync();
var bytes = await StreamToBytesAsync(stream);
await _jsInterop.LoadFile(bytes);
ret = new SelectedFile();
ret.imageBytes = bytes;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return ret;
}
public static async Task<byte[]> StreamToBytesAsync(Stream stream)
{
if (stream == null) return null;
using (var memoryStream = new MemoryStream())
{
await stream.CopyToAsync(memoryStream);
return memoryStream.ToArray();
}
}
private async void OnActionItemClicked(object sender, EventArgs args)
{
string result = await DisplayActionSheet("Select an action", "Cancel", null, "Scan with scanner", "Scan with camera",
"Edit", "Settings", "Save as PDF", "Save selected as PNG",
"Open a local file");
if (result == "Scan with scanner")
{
StartDocumentScanning();
}
else if (result == "Scan with camera")
{
TakePhoto();
}
else if (result == "Edit")
{
if (isDesktop) {
await _jsInterop.WebView.ExecuteJavaScriptAsync("invokeJavaScript('showFullFeatureEditor','[]');");
}
else {
await _jsInterop.WebView.ExecuteJavaScriptAsync("showEditor();");
}
}
else if (result == "Settings")
{
await Shell.Current.GoToAsync("SettingsPage");
}
else if (result == "Save as PDF")
{
SaveAsPDF();
}
else if (result == "Save selected as PNG")
{
SaveAsPNG();
}
else if (result == "Open a local file")
{
await PickAndShow();
}
}
public async void TakePhoto()
{
if (MediaPicker.Default.IsCaptureSupported)
{
FileResult? photo = await MediaPicker.Default.CapturePhotoAsync();
if (photo != null)
{
// save the file into local storage
string localFilePath = Path.Combine(FileSystem.CacheDirectory, photo.FileName);
using Stream sourceStream = await photo.OpenReadAsync();
var bytes = await StreamToBytesAsync(sourceStream);
await _jsInterop.LoadFile(bytes);
}
}
}
private async void StartDocumentScanning() {
var canceled = false;
Func<object> cancelEvent = () =>
{
canceled = true;
Navigation.PopModalAsync();
CancelScanning();
return "";
};
var page = new ProgressPage();
page.RegisterCallback(cancelEvent);
await Navigation.PushModalAsync(page);
Debug.WriteLine("start scanning");
await ScanDocument();
if (!canceled)
{
await Navigation.PopModalAsync();
}
}
private async void SaveAsPDF() {
var canceled = false;
Func<object> cancelEvent = () =>
{
canceled = true;
Navigation.PopModalAsync();
return "";
};
var page = new ProgressPage();
page.RegisterCallback(cancelEvent);
await Navigation.PushModalAsync(page);
try
{
PageOption pageOption = PageOption.All; // Default to "Save Current Page"
PdfPageType pdfPageType = PdfPageType.PageDefault;
SaveAnnotationMode annotationMode = SaveAnnotationMode.None;
byte[] pdfContent = await _jsInterop.SaveAsPdf(pageOption,pdfPageType,annotationMode,"");
if (canceled) {
return;
}
if (pdfContent.Length > 0) {
string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "out.pdf");
await using (var fileStream = new FileStream(targetFile, FileMode.Create, FileAccess.Write))
{
await fileStream.WriteAsync(pdfContent, 0, pdfContent.Length);
if (isDesktop)
{
await Launcher.Default.OpenAsync(new OpenFileRequest("", new ReadOnlyFile(targetFile)));
}
else {
await Share.Default.RequestAsync(new ShareFileRequest
{
Title = "Share PDF file",
File = new ShareFile(targetFile)
});
}
}
}
}
catch (Exception ex)
{
if (ex.Message != null)
{
MainThread.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("Alert", ex.Message, "OK");
});
}
}
if (!canceled)
{
await Navigation.PopModalAsync();
}
}
private async void SaveAsPNG()
{
try
{
byte[] bytes = await _jsInterop.SaveAsPng(false);
if (bytes.Length > 0)
{
string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "out.png");
await using (var fileStream = new FileStream(targetFile, FileMode.Create, FileAccess.Write))
{
await fileStream.WriteAsync(bytes, 0, bytes.Length);
if (isDesktop)
{
await Launcher.Default.OpenAsync(new OpenFileRequest("", new ReadOnlyFile(targetFile)));
}
else {
await Share.Default.RequestAsync(new ShareFileRequest
{
Title = "Share PNG file",
File = new ShareFile(targetFile)
});
}
}
}
}
catch (Exception ex)
{
if (ex.Message != null)
{
MainThread.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("Alert", ex.Message, "OK");
});
}
}
}
private void CancelScanning() {
scannerJob?.DeleteJob();
}
private async Task<bool> ScanDocument()
{
Debug.WriteLine("ScanDocument");
try
{
var license = Preferences.Get("License", oneDayTrialLicense);
if (license == "") {
license = oneDayTrialLicense;
}
var IPAddress = Preferences.Get("IP", defaultAddress);
var client = new DWTClient(new Uri(IPAddress), license);
_jsInterop.DWTClient = client;
var DPI = Preferences.Get("DPI", 150);
var colorMode = Preferences.Get("ColorMode", "Color");
var scannerName = Preferences.Get("Scanner", "");
var scannerType = "";
MatchCollection matches = Regex.Matches(scannerName, @"\((.*?)\)");
if (matches.Count > 0)
{
scannerType = matches[matches.Count - 1].Groups[1].Value;
var lastMatch = matches[matches.Count - 1];
scannerName = scannerName.Remove(lastMatch.Index, lastMatch.Length).Trim();
}
var autoFeeder = Preferences.Get("AutoFeeder", false);
var duplex = Preferences.Get("Duplex", false);
CreateScanJobOptions options = new CreateScanJobOptions();
options.AutoRun = false;
options.RequireWebsocket = false;
options.Config = new ScannerConfiguration();
options.Config.Resolution = DPI;
options.Config.IfFeederEnabled = autoFeeder;
options.Config.IfDuplexEnabled = duplex;
Debug.WriteLine(colorMode);
if (colorMode == "Color")
{
Debug.WriteLine("scan in color");
options.Config.PixelType = EnumDWT_PixelType.TWPT_RGB;
}
else if (colorMode == "BlackWhite")
{
Debug.WriteLine("scan in black white");
options.Config.PixelType = EnumDWT_PixelType.TWPT_BW;
}
else if (colorMode == "Grayscale")
{
Debug.WriteLine("scan in grayscale");
options.Config.PixelType = EnumDWT_PixelType.TWPT_GRAY;
}
if (!string.IsNullOrEmpty(scannerName))
{
var scanners = await _jsInterop.DWTClient.ScannerControlClient.ScannerManager.GetScanners(EnumDeviceTypeMask.DT_TWAINSCANNER | EnumDeviceTypeMask.DT_WIASCANNER | EnumDeviceTypeMask.DT_ICASCANNER | EnumDeviceTypeMask.DT_SANESCANNER);
foreach (var scanner in scanners)
{
if (scanner.Name == scannerName)
{
if (GetTypeFromName(scannerType) == scanner.Type) {
Debug.WriteLine("Selected scanner: " + scanner.Name);
Debug.WriteLine("Selected scanner type: " + GetTypeFromName(scannerType));
options.Device = scanner.Device;
}
}
}
}
scannerJob = await _jsInterop.CreateScanToViewJob(options);
await _jsInterop.StartJob(scannerJob);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
if (ex.Message != null)
{
MainThread.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("Alert", ex.Message, "OK");
});
}
}
return true;
}
private static EnumDeviceTypeMask GetTypeFromName(string name)
{
switch (name)
{
case "TWAIN":
return EnumDeviceTypeMask.DT_TWAINSCANNER;
case "WIA":
return EnumDeviceTypeMask.DT_WIASCANNER;
case "ICA":
return EnumDeviceTypeMask.DT_ICASCANNER;
case "SANE":
return EnumDeviceTypeMask.DT_SANESCANNER;
default:
break;
}
return EnumDeviceTypeMask.DT_UNKNOWN;
}
}
}