This repository has been archived by the owner on Mar 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
DownloadDialog.cs
350 lines (312 loc) · 12.1 KB
/
DownloadDialog.cs
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.IO;
using VietOCR.NET.Utilities;
using System.Xml;
using System.Threading;
namespace VietOCR.NET
{
public partial class DownloadDialog : Form
{
Dictionary<string, string> availableLanguageCodes;
Dictionary<string, string> availableDictionaries;
public Dictionary<string, string> LookupISO_3_1_Codes
{
get;
set;
}
public Dictionary<string, string> LookupISO639
{
get;
set;
}
public List<string> InstalledLanguages
{
get;
set;
}
List<WebClient> clients;
Dictionary<string, long> downloadTracker;
int numberOfDownloads, numOfConcurrentTasks;
long contentLength;
string baseDir;
const string DICTIONARY_FOLDER = "dict";
const string TESS_DATA = "tessdata";
public DownloadDialog()
{
InitializeComponent();
baseDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
clients = new List<WebClient>();
downloadTracker = new Dictionary<string, long>();
}
protected override void OnLoad(EventArgs ea)
{
base.OnLoad(ea);
String xmlFilePath = Path.Combine(baseDir, "Data/Tess3DataURL.xml");
availableLanguageCodes = new Dictionary<string, string>();
Utilities.Utilities.LoadFromXML(availableLanguageCodes, xmlFilePath);
xmlFilePath = Path.Combine(baseDir, "Data/OO-SpellDictionaries.xml");
availableDictionaries = new Dictionary<string, string>();
Utilities.Utilities.LoadFromXML(availableDictionaries, xmlFilePath);
string[] available = new string[availableLanguageCodes.Count];
availableLanguageCodes.Keys.CopyTo(available, 0);
List<String> names = new List<String>();
foreach (String key in available)
{
names.Add(this.LookupISO639[key]);
}
names.Sort();
this.listBox1.Items.Clear();
this.listBox1.Items.AddRange(names.ToArray());
foreach (string installed in InstalledLanguages)
{
for (int i = 0; i < names.Count; ++i)
{
if (installed == names[i])
{
this.listBox1.DisableItem(i);
break;
}
}
}
this.ActiveControl = this.listBox1;
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (numberOfDownloads > 0)
{
string destFolder = Path.Combine(baseDir, TESS_DATA);
try
{
string downloadFolder = Path.Combine(destFolder, @"tesseract-ocr\tessdata");
if (Directory.Exists(downloadFolder))
{
//In Tesseract 3.02, data is packaged under tesseract-ocr/tessdata directory
//After extraction, move them up two levels
string[] files = Directory.GetFiles(downloadFolder);
foreach (string file in files)
{
string destFile = Path.Combine(destFolder, Path.GetFileName(file));
// Ensure that the target does not exist
if (File.Exists(destFile))
{
File.Delete(destFile);
}
File.Move(file, destFile);
}
//remove extraneous directories left by file extraction
Directory.Delete(Path.Combine(destFolder, "tesseract-ocr"), true);
}
}
catch
{
// trap and ignore
}
MessageBox.Show(this, Properties.Resources.Please_restart, GUI.strProgName);
}
}
private void buttonDownload_Click(object sender, EventArgs e)
{
if (this.listBox1.SelectedIndex == -1)
{
return;
}
bool isWriteAccess = CheckDirectoryWriteAccess(Path.Combine(baseDir, TESS_DATA));
if (!isWriteAccess)
{
string msg = String.Format(Properties.Resources.Access_denied, Path.Combine(baseDir, TESS_DATA).ToString());
MessageBox.Show(msg, GUI.strProgName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
this.buttonDownload.Enabled = false;
this.buttonCancel.Enabled = true;
this.toolStripProgressBar1.Value = 0;
this.toolStripProgressBar1.Visible = true;
this.buttonDownload.Enabled = false;
this.toolStripStatusLabel1.Text = Properties.Resources.Downloading;
this.Cursor = Cursors.WaitCursor;
clients.Clear();
downloadTracker.Clear();
contentLength = 0;
numOfConcurrentTasks = this.listBox1.SelectedIndices.Count;
foreach (object obj in this.listBox1.SelectedItems)
{
string key = FindKey(LookupISO639, obj.ToString()); // Vietnamese -> vie
if (key != null)
{
try
{
Uri uri = new Uri(availableLanguageCodes[key]);
DownloadDataFile(uri, TESS_DATA); // download language data pack. In Tesseract 3.02, data is packaged under tesseract-ocr/tessdata directory
if (LookupISO_3_1_Codes.ContainsKey(key))
{
string iso_3_1_Code = LookupISO_3_1_Codes[key]; // vie -> vi_VN
if (availableDictionaries.ContainsKey(iso_3_1_Code))
{
uri = new Uri(availableDictionaries[iso_3_1_Code]);
++numOfConcurrentTasks;
DownloadDataFile(uri, DICTIONARY_FOLDER); // download dictionary
}
}
}
catch (Exception)
{
if (--numOfConcurrentTasks <= 0)
{
this.toolStripStatusLabel1.Text = Properties.Resources.Downloaderror;
this.toolStripProgressBar1.Visible = false;
resetUI();
}
}
}
}
}
/// <summary>
/// Determines if a folder is writable by a user.
/// </summary>
/// <param name="directory"></param>
/// <returns></returns>
private bool CheckDirectoryWriteAccess(string directory)
{
bool writeAccess = false;
if (Directory.Exists(directory))
{
try
{
string tempFile = Path.Combine(directory, Path.GetRandomFileName());
using (FileStream fs = File.Create(tempFile)) { }
if (File.Exists(tempFile))
{
File.Delete(tempFile);
writeAccess = true;
}
}
catch (Exception)
{
writeAccess = false;
}
}
return writeAccess;
}
string FindKey(IDictionary<string, string> lookup, string value)
{
foreach (var pair in lookup)
{
if (pair.Value == value)
{
return pair.Key;
}
}
return null;
}
void DownloadDataFile(Uri uri, string destFolder)
{
try
{
// WebClient can only handle one download at a time.
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);
clients.Add(client);
WebRequest request = WebRequest.Create(uri);
request.Timeout = 15000;
WebResponse response = request.GetResponse();
contentLength += response.ContentLength;
response.Close();
string filePath = Path.Combine(Path.GetTempPath(), Path.GetFileName(uri.AbsolutePath));
client.DownloadFileAsync(uri, filePath, destFolder + filePath);
}
catch (Exception e)
{
if (e.Message.Contains("404"))
{
MessageBox.Show(Properties.Resources.Resource_not_exist); //url does not exist
}
else
{
MessageBox.Show(e.Message);
}
throw e;
}
}
void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
string filePath = e.UserState.ToString();
if (!downloadTracker.ContainsKey(filePath))
{
downloadTracker.Add(filePath, e.BytesReceived);
}
else
{
downloadTracker[filePath] = e.BytesReceived;
}
long totalBytesReceived = 0;
foreach (int bytesReceived in downloadTracker.Values)
{
totalBytesReceived += bytesReceived;
}
if (contentLength != 0)
{
this.toolStripProgressBar1.Value = (int)(100 * totalBytesReceived / contentLength);
}
}
void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
{
this.toolStripStatusLabel1.Text = Properties.Resources.Downloadcanceled;
resetUI();
}
else if (e.Error != null)
{
this.toolStripProgressBar1.Visible = false;
this.toolStripStatusLabel1.Text = e.Error.Message;
resetUI();
}
else
{
string fileName = e.UserState.ToString();
if (fileName.StartsWith(DICTIONARY_FOLDER))
{
FileExtractor.ExtractCompressedFile(fileName.Substring(DICTIONARY_FOLDER.Length), Path.Combine(baseDir, DICTIONARY_FOLDER));
}
else
{
FileExtractor.ExtractCompressedFile(fileName.Substring(TESS_DATA.Length), Path.Combine(baseDir, TESS_DATA));
numberOfDownloads++;
}
if (--numOfConcurrentTasks <= 0)
{
this.toolStripStatusLabel1.Text = Properties.Resources.Downloadcompleted;
this.toolStripProgressBar1.Visible = false;
resetUI();
}
}
}
void resetUI()
{
this.buttonDownload.Enabled = true;
this.buttonCancel.Enabled = false;
this.Cursor = Cursors.Default;
}
private void buttonCancel_Click(object sender, EventArgs e)
{
foreach (WebClient client in clients)
{
if (client != null && client.IsBusy)
{
client.CancelAsync();
client.Dispose();
}
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.buttonDownload.Enabled = this.listBox1.SelectedIndex != -1;
}
}
}