forked from wmjordan/PDFPatcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainForm.cs
573 lines (532 loc) · 17.2 KB
/
MainForm.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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using PDFPatcher.Common;
using PDFPatcher.Functions;
namespace PDFPatcher
{
public partial class MainForm : Form
{
static readonly Dictionary<Function, FunctionControl> __FunctionControls = new Dictionary<Function, FunctionControl>();
ReportControl _LogControl;
#region 公共功能
BackgroundWorker _Worker;
readonly FormState _formState = new FormState();
bool _FullScreen;
///<summary>获取或指定全屏显示的值。</summary>
[Browsable(false)]
public bool FullScreen {
get => _FullScreen;
set {
if (value == _FullScreen) {
return;
}
_FullScreen = value;
if (value) {
_MainMenu.Visible = _GeneralToolbar.Visible = false;
_formState.Maximize(this);
}
else {
_MainMenu.Visible = true;
_GeneralToolbar.Visible = AppContext.Toolbar.ShowGeneralToolbar;
_formState.Restore(this);
}
}
}
/// <summary>
/// 设置控件的提示信息。
/// </summary>
internal void SetTooltip(Control control, string text) {
_ToolTip.SetToolTip(control, text);
}
/// <summary>
/// 获取或设置状态栏文本。
/// </summary>
internal string StatusText {
get => _MainStatusLabel.Text;
set => _MainStatusLabel.Text = value;
}
#region Worker
///<summary>获取或指定后台进程。</summary>
internal BackgroundWorker GetWorker() {
if (_Worker == null) {
_Worker = new BackgroundWorker {
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
_Worker.DoWork += Worker_DoWork;
_Worker.ProgressChanged += Worker_ProgressChanged;
_Worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
Tracker.SetWorker(_Worker);
}
return _Worker;
}
internal bool IsWorkerBusy => _Worker?.IsBusy == true;
void Worker_DoWork(object sender, DoWorkEventArgs e) {
_Worker.ReportProgress(0);
FileHelper.ResetOverwriteMode();
AppContext.Abort = false;
}
void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
_MainMenu.Enabled = _GeneralToolbar.Enabled = _FunctionContainer.Enabled = true;
foreach (TabPage item in _FunctionContainer.TabPages) {
item.Enabled = true;
}
if (e.Error == null || e.Cancelled == false) {
_LogControl.Complete();
}
}
public void ResetWorker() {
if (_Worker != null) {
if (_Worker.IsBusy) {
throw new InvalidOperationException("Worker is busy. Can't be reset.");
}
_Worker.Dispose();
_Worker = null;
}
}
void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
var s = e.UserState as string;
if (s == "INC") {
_LogControl.IncrementProgress(e.ProgressPercentage);
return;
}
else if (s == "GOAL") {
_LogControl.SetGoal(e.ProgressPercentage);
return;
}
else if (s == "TINC") {
_LogControl.IncrementTotalProgress();
}
else if (s == "TGOAL") {
_LogControl.SetTotalGoal(e.ProgressPercentage);
}
if (e.ProgressPercentage > 0) {
_LogControl.SetProgress(e.ProgressPercentage);
}
else if (e.ProgressPercentage == 0) {
_MainMenu.Enabled = _GeneralToolbar.Enabled = _FunctionContainer.Enabled = false;
foreach (TabPage item in _FunctionContainer.TabPages) {
item.Enabled = false;
}
_LogControl.Reset();
ShowLogControl();
}
else if (s != null) {
_LogControl.PrintMessage(s, (Tracker.Category)e.ProgressPercentage);
}
}
#endregion
internal FunctionControl GetFunctionControl(Function functionName) {
if (__FunctionControls.TryGetValue(functionName, out FunctionControl f) && f.IsDisposed == false) {
return f;
}
switch (functionName) {
case Function.FrontPage:
return __FunctionControls[functionName] = new FrontPageControl();
case Function.Patcher:
return __FunctionControls[functionName] = new PatcherControl();
case Function.Merger:
return __FunctionControls[functionName] = new MergerControl();
case Function.BookmarkGenerator:
return __FunctionControls[functionName] = new AutoBookmarkControl();
case Function.InfoExchanger:
return __FunctionControls[functionName] = new InfoExchangerControl();
case Function.ExtractPages:
return __FunctionControls[functionName] = new ExtractPageControl();
case Function.ExtractImages:
return __FunctionControls[functionName] = new ExtractImageControl();
case Function.Editor:
var b = new EditorControl();
b.DocumentChanged += OnDocumentChanged;
return b;
case Function.Ocr:
return __FunctionControls[functionName] = new OcrControl();
case Function.RenderPages:
return __FunctionControls[functionName] = new RenderImageControl();
case Function.About:
return __FunctionControls[functionName] = new AboutControl();
case Function.Inspector:
var d = new DocumentInspectorControl();
d.DocumentChanged += OnDocumentChanged;
return d;
case Function.Rename:
return __FunctionControls[functionName] = new RenameControl();
default:
return null;
}
}
void OnDocumentChanged(object sender, DocumentChangedEventArgs args) {
var p = args.Path;
_MainStatusLabel.Text = p ?? String.Empty;
if (!FileHelper.IsPathValid(p)) {
return;
}
p = System.IO.Path.GetFileNameWithoutExtension(p);
if (p.Length > 20) {
p = p.Substring(0, 17) + "...";
}
if (sender is Control f) {
f = f.Parent;
if (f == null) {
return;
}
f.Text = p;
}
}
#endregion
public MainForm() {
InitializeComponent();
this.OnFirstLoad(OnLoad);
}
protected override void WndProc(ref Message m) {
base.WndProc(ref m);
if (m.Msg == FormHelper.ProcMsg) {
OpenFiles(FormHelper.GetCopyDataContent(ref m).Split('\n'));
Activate();
}
}
void OnLoad() {
Processor.PdfHelper.ToggleReaderDebugMode(true); // 打开容错模式
Processor.PdfHelper.ToggleUnethicalMode(true); // 打开强制读取加密文档模式
bool firstLoad;
try {
firstLoad = AppContext.Load(null) == false;
}
catch (Exception) {
// ignore loading exception
firstLoad = true;
}
_MainMenu.ScaleIcons(16);
Text = Constants.AppName + " [" + Application.ProductVersion + "]";
MinimumSize = Size;
StartPosition = FormStartPosition.CenterScreen;
AllowDrop = true;
DragEnter += (s, args) => args.FeedbackDragFileOver(Constants.FileExtensions.Pdf);
DragDrop += (s, args) => OpenFiles(args.DropFileOver(Constants.FileExtensions.Pdf));
SetupCustomizeToolbar();
if (_GeneralToolbar.Visible = AppContext.Toolbar.ShowGeneralToolbar) {
ScaleToolbar();
}
_OpenPdfDialog.DefaultExt = Constants.FileExtensions.Pdf;
_OpenPdfDialog.Filter = Constants.FileExtensions.PdfFilter;
_LogControl = new ReportControl {
Location = _FunctionContainer.Location,
Size = _FunctionContainer.Size,
Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right
};
Controls.Add(_LogControl);
HideLogControl();
_LogControl.VisibleChanged += (s, args) => _FunctionContainer.Visible = !_LogControl.Visible;
_OpenConfigDialog.FileName = _SaveConfigDialog.FileName = Constants.AppName + "配置文件" + Constants.FileExtensions.Json;
_OpenConfigDialog.Filter = _SaveConfigDialog.Filter = Constants.FileExtensions.JsonFilter;
_FunctionContainer.Font = new Font(SystemFonts.CaptionFont.FontFamily.Name, 9);
_FunctionContainer.ImageList = new ImageList();
_FunctionContainer.DisplayStyleProvider.SelectedTextStyle = FontStyle.Bold;
_FunctionContainer.AllowDrop = true;
_FunctionContainer.MouseClick += (s, args) => {
if (args.Button == MouseButtons.Middle) { ClickCloseTab(args); }
};
_FunctionContainer.MouseDoubleClick += (s, args) => { ClickCloseTab(args); };
_FunctionContainer.TabClosing += (s, args) => {
var t = _FunctionContainer.SelectedTab;
Tracker.DebugMessage(args.Action.ToString());
if (t.Tag.CastOrDefault<Function>() == Function.FrontPage) {
args.Cancel = true;
return;
}
var i = args.TabPageIndex;
var c = _FunctionContainer.TabCount;
if (i == 0 && c > 1) {
_FunctionContainer.SelectedIndex = 1;
}
else if (i < c) {
_FunctionContainer.SelectedIndex = i - 1;
}
_FunctionContainer.TabPages.RemoveAt(i);
t.Dispose();
_MainStatusLabel.Text = String.Empty;
};
_FunctionContainer.Selected += SelectedFunctionChanged;
_FunctionContainer.Deselected += FunctionDeselected;
// 关闭启动屏幕窗口
using (var closeSplashEvent = new System.Threading.EventWaitHandle(false,
System.Threading.EventResetMode.ManualReset, "CloseSplashScreenEvent" + Constants.AppEngName)) {
closeSplashEvent.Set();
}
SelectFunctionList(Function.FrontPage);
if (firstLoad) {
SelectFunctionList(Function.About);
}
_GeneralToolbar.ItemClicked += MenuCommand;
if (AppContext.CheckUpdateDate < DateTime.Today) {
CheckUpdate();
if (AppContext.CheckUpdateInterval != Int32.MaxValue) {
AppContext.CheckUpdateDate = DateTime.Today + TimeSpan.FromDays(AppContext.CheckUpdateInterval);
}
}
var ca = Environment.GetCommandLineArgs();
if (ca.HasContent()) {
OpenFiles(ca);
}
#if DEBUG
iTextSharp.text.io.StreamUtil.AddToResourceSearch("iTextAsian.dll");
#endif
}
void OpenFiles(string[] files) {
foreach (var item in files) {
var p = new FilePath(item);
if (p.ExistsFile && p.HasExtension(Constants.FileExtensions.Pdf)) {
OpenFileWithEditor(p.ToFullPath());
}
}
}
void CheckUpdate() {
var client = new System.Net.WebClient();
client.DownloadDataCompleted += (s, args) => {
if (args.Error != null) {
goto Exit;
}
try {
var x = new System.Xml.XmlDocument();
x.Load(new System.IO.MemoryStream(args.Result));
var r = x.DocumentElement;
var u = r.GetAttribute("url");
if (String.IsNullOrEmpty(u) == false
&& new Version(ProductVersion) < new Version(r.GetAttribute("version"))
&& this.ConfirmOKBox("发现新版本,是否前往下载?")) {
ShowDialogWindow(new UpdateForm());
}
}
catch (Exception) {
FormHelper.ErrorBox("版本信息文件格式错误,请稍候重试。");
}
Exit:
client.Dispose();
client = null;
};
client.DownloadDataAsync(new Uri(Constants.AppUpdateFile));
}
void ClickCloseTab(MouseEventArgs args) {
for (int i = _FunctionContainer.TabCount - 1; i >= 0; i--) {
if (_FunctionContainer.GetTabRect(i).Contains(args.Location) == false) {
continue;
}
if (_FunctionContainer.TabPages[i].Tag.CastOrDefault<Function>() != Function.FrontPage) {
_FunctionContainer.TabPages[i].Dispose();
}
}
}
void MenuCommand(object sender, ToolStripItemClickedEventArgs e) {
var ci = e.ClickedItem;
var t = ci.Tag as string;
if (String.IsNullOrEmpty(t) == false) {
SelectFunctionList((Function)Enum.Parse(typeof(Function), t));
return;
}
ci.HidePopupMenu();
if (ci.OwnerItem == _RecentFiles) {
var f = GetActiveFunctionControl() as FunctionControl;
f.RecentFileItemClicked?.Invoke(_MainMenu, e);
}
else {
ExecuteCommand(ci.Name);
}
}
internal void ExecuteCommand(string commandName) {
if (commandName == Commands.ResetOptions) {
if (GetActiveFunctionControl() is IResettableControl f
&& FormHelper.YesNoBox("是否将当前功能恢复为默认设置?") == DialogResult.Yes) {
f.Reset();
}
}
else if (commandName == Commands.RestoreOptions && _OpenConfigDialog.ShowDialog() == DialogResult.OK) {
if (AppContext.Load(_OpenConfigDialog.FileName) == false) {
FormHelper.ErrorBox("无法加载指定的配置文件。");
return;
}
foreach (Control item in __FunctionControls.Values) {
(item as IResettableControl)?.Reload();
}
SetupCustomizeToolbar();
}
else if (commandName == Commands.SaveOptions && _SaveConfigDialog.ShowDialog() == DialogResult.OK) {
AppContext.Save(_SaveConfigDialog.FileName, false);
}
else if (commandName == Commands.LogWindow) {
ShowLogControl();
}
else if (commandName == Commands.CreateShortcut) {
CommonCommands.CreateShortcut();
}
else if (commandName == Commands.VisitHomePage) {
CommonCommands.VisitHomePage();
}
else if (commandName == Commands.CheckUpdate) {
ShowDialogWindow(new UpdateForm());
}
else if (commandName == Commands.Close) {
if (_FunctionContainer.SelectedTab.Tag.CastOrDefault<Function>() == Function.FrontPage) {
return;
}
_FunctionContainer.SelectedTab.Dispose();
}
else if (commandName == Commands.CustomizeToolbar || commandName == "_CustomizeToolbarCommand") {
ShowDialogWindow(new CustomizeToolbarForm());
SetupCustomizeToolbar();
}
else if (commandName == Commands.ShowGeneralToolbar) {
_FunctionContainer.SuspendLayout();
if (_GeneralToolbar.Visible = AppContext.Toolbar.ShowGeneralToolbar = !AppContext.Toolbar.ShowGeneralToolbar) {
ScaleToolbar();
}
_FunctionContainer.PerformLayout();
}
else if (commandName == Commands.Exit) {
Close();
}
else if (GetActiveFunctionControl() is FunctionControl f) {
if (commandName == Commands.Action && f.DefaultButton != null) {
f.DefaultButton.PerformClick();
}
else {
f.ExecuteCommand(commandName);
}
}
}
void SetupCustomizeToolbar() {
AppContext.Toolbar.RemoveInvalidButtons();
for (int i = _GeneralToolbar.Items.Count - 1; i > 0; i--) {
_GeneralToolbar.Items[i].Dispose();
}
foreach (var item in AppContext.Toolbar.Buttons) {
if (item.Visible == false) {
continue;
}
_GeneralToolbar.Items.Add(item.CreateButton());
}
}
void ScaleToolbar() {
_GeneralToolbar.ScaleIcons(16);
}
DialogResult ShowDialogWindow(Form window) {
using (var f = window) {
f.StartPosition = FormStartPosition.CenterParent;
return f.ShowDialog(this);
}
}
Control GetActiveFunctionControl() {
var t = _FunctionContainer.SelectedTab;
return t == null || t.HasChildren == false ? null : t.Controls[0];
}
internal void OpenFileWithEditor(string path) {
SelectFunctionList(Function.Editor);
var c = GetActiveFunctionControl() as EditorControl;
if (String.IsNullOrEmpty(path)) {
c.ExecuteCommand(Commands.Open);
}
else {
c.ExecuteCommand(Commands.OpenFile, path);
}
}
internal void SelectFunctionList(Function func) {
if (func == Function.PatcherOptions) {
ShowDialogWindow(new PatcherOptionForm(false) { Options = AppContext.Patcher });
}
else if (func == Function.MergerOptions) {
ShowDialogWindow(new MergerOptionForm());
}
else if (func == Function.InfoFileOptions) {
ShowDialogWindow(new InfoFileOptionControl());
}
else if (func == Function.EditorOptions) {
ShowDialogWindow(new PatcherOptionForm(true) { Options = AppContext.Editor });
}
else if (func == Function.Options) {
ShowDialogWindow(new AppOptionForm());
}
else {
HideLogControl();
var p = (GetActiveFunctionControl() as IDocumentEditor)?.DocumentPath;
var c = GetFunctionControl(func);
foreach (TabPage item in _FunctionContainer.TabPages) {
if (item.Controls.Count > 0 && item.Controls[0] == c) {
_FunctionContainer.SelectedTab = item;
if (String.IsNullOrEmpty(p) == false) {
c.ExecuteCommand(Commands.OpenFile, p);
}
return;
}
}
var t = new TabPage(c.FunctionName) {
Font = SystemFonts.SmallCaptionFont
};
var im = _FunctionContainer.ImageList.Images;
for (int i = im.Count - 1; i >= 0; i--) {
if (im[i] == c.IconImage) {
t.ImageIndex = i;
break;
}
}
if (t.ImageIndex < 0) {
im.Add(c.IconImage);
t.ImageIndex = im.Count - 1;
}
t.Tag = func;
_FunctionContainer.TabPages.Add(t);
c.Size = t.ClientSize;
c.Dock = DockStyle.Fill;
t.Controls.Add(c);
_FunctionContainer.SelectedTab = t;
if (String.IsNullOrEmpty(p) == false) {
c.ExecuteCommand(Commands.OpenFile, p);
}
AcceptButton = c.DefaultButton;
}
}
void FunctionDeselected(object sender, TabControlEventArgs args) {
if (GetActiveFunctionControl() is FunctionControl c) {
c.OnDeselected();
}
}
void SelectedFunctionChanged(object sender, TabControlEventArgs args) {
if (GetActiveFunctionControl() is FunctionControl c) {
//foreach (ToolStripMenuItem item in _MainMenu.Items) {
// c.SetupMenu (item);
//}
c.OnSelected();
_MainStatusLabel.Text = c is IDocumentEditor b ? b.DocumentPath : Messages.Welcome;
AcceptButton = c.DefaultButton;
}
}
internal string ShowPdfFileDialog() {
return _OpenPdfDialog.ShowDialog() == DialogResult.OK ? _OpenPdfDialog.FileName : null;
}
void MainForm_FormClosed(object sender, FormClosedEventArgs e) {
try {
AppContext.Save(null, true);
}
catch (Exception) {
// ignore error
}
}
void HideLogControl() {
_LogControl.Hide();
}
void ShowLogControl() {
_LogControl.Show();
}
void MenuOpening(object sender, EventArgs e) {
if (GetActiveFunctionControl() is FunctionControl f) {
f.SetupMenu(sender as ToolStripMenuItem);
}
}
void RecentFileMenuOpening(object sender, EventArgs e) {
if (GetActiveFunctionControl() is FunctionControl f && f.ListRecentFiles != null) {
f.ListRecentFiles(sender, e);
}
}
}
}