-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormBrowser.cs
More file actions
1309 lines (1020 loc) · 33.4 KB
/
FormBrowser.cs
File metadata and controls
1309 lines (1020 loc) · 33.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
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.ServiceModel;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using BrowserLib;
using Gecko;
using Gecko.DOM;
using Gecko.Events;
namespace GeckoBrowser
{
/// <summary>
/// ブラウザを表示するフォームです。
/// </summary>
/// <remarks>thx KanColleViewer!</remarks>
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single/*, IncludeExceptionDetailInFaults = true*/)]
public partial class FormBrowser : Form, BrowserLib.IBrowser
{
private readonly Size KanColleSize = new Size(1200, 720);
private readonly string BrowserCachePath = "BrowserCache";
private readonly string StyleClassID = Guid.NewGuid().ToString().Substring(0, 8);
private bool RestoreStyleSheet = false;
// FormBrowserHostの通信サーバ
private string ServerUri;
// FormBrowserの通信サーバ
private PipeCommunicator<BrowserLib.IBrowserHost> BrowserHost;
private BrowserLib.BrowserConfiguration Configuration;
// 親プロセスが生きているか定期的に確認するためのタイマー
private Timer HeartbeatTimer = new Timer();
private IntPtr HostWindow;
private GeckoWebBrowser Browser = null;
//private string ProxySettings = null;
private string HttpProxyHost = null;
private int HttpProxyPort = 0;
private string SslProxyHost = null;
private int SslProxyPort = 0;
private bool _styleSheetApplied;
/// <summary>
/// スタイルシートの変更が適用されているか
/// </summary>
private bool StyleSheetApplied
{
get { return _styleSheetApplied; }
set
{
if (value)
{
//Browser.Anchor = AnchorStyles.None;
ApplyZoom();
SizeAdjuster_SizeChanged(null, new EventArgs());
}
else
{
SizeAdjuster.SuspendLayout();
if (IsBrowserInitialized)
{
//Browser.Anchor = AnchorStyles.Top | AnchorStyles.Left;
Browser.Location = new Point(0, 0);
Browser.MinimumSize = new Size(0, 0);
Browser.Size = SizeAdjuster.Size;
}
SizeAdjuster.ResumeLayout();
}
_styleSheetApplied = value;
}
}
/// <summary>
/// 艦これが読み込まれているかどうか
/// </summary>
private bool IsKanColleLoaded { get; set; }
private VolumeManager _volumeManager;
private string _lastScreenShotPath;
private NumericUpDown ToolMenu_Other_Volume_VolumeControl
{
get { return (NumericUpDown)((ToolStripControlHost)ToolMenu_Other_Volume.DropDownItems["ToolMenu_Other_Volume_VolumeControlHost"]).Control; }
}
private PictureBox ToolMenu_Other_LastScreenShot_Control
{
get { return (PictureBox)((ToolStripControlHost)ToolMenu_Other_LastScreenShot.DropDownItems["ToolMenu_Other_LastScreenShot_ImageHost"]).Control; }
}
/// <summary>
/// </summary>
/// <param name="serverUri">ホストプロセスとの通信用URL</param>
public FormBrowser(string serverUri)
{
InitializeComponent();
ServerUri = serverUri;
StyleSheetApplied = false;
_volumeManager = new VolumeManager((uint)Process.GetCurrentProcess().Id);
// 音量設定用コントロールの追加
{
var control = new NumericUpDown();
control.Name = "ToolMenu_Other_Volume_VolumeControl";
control.Maximum = 100;
control.TextAlign = HorizontalAlignment.Right;
control.Font = ToolMenu_Other_Volume.Font;
control.ValueChanged += ToolMenu_Other_Volume_ValueChanged;
control.Tag = false;
var host = new ToolStripControlHost(control, "ToolMenu_Other_Volume_VolumeControlHost");
control.Size = new Size(host.Width - control.Margin.Horizontal, host.Height - control.Margin.Vertical);
control.Location = new Point(control.Margin.Left, control.Margin.Top);
ToolMenu_Other_Volume.DropDownItems.Add(host);
}
// スクリーンショットプレビューコントロールの追加
{
double zoomrate = 0.5;
var control = new PictureBox();
control.Name = "ToolMenu_Other_LastScreenShot_Image";
control.SizeMode = PictureBoxSizeMode.Zoom;
control.Size = new Size((int)(KanColleSize.Width * zoomrate), (int)(KanColleSize.Height * zoomrate));
control.Margin = new Padding();
control.Image = new Bitmap((int)(KanColleSize.Width * zoomrate), (int)(KanColleSize.Height * zoomrate), PixelFormat.Format24bppRgb);
using (var g = Graphics.FromImage(control.Image))
{
g.Clear(SystemColors.Control);
g.DrawString("スクリーンショットをまだ撮影していません。\r\n", Font, Brushes.Black, new Point(4, 4));
}
var host = new ToolStripControlHost(control, "ToolMenu_Other_LastScreenShot_ImageHost");
host.Size = new Size(control.Width + control.Margin.Horizontal, control.Height + control.Margin.Vertical);
host.AutoSize = false;
control.Location = new Point(control.Margin.Left, control.Margin.Top);
host.Click += ToolMenu_Other_LastScreenShot_ImageHost_Click;
ToolMenu_Other_LastScreenShot.DropDownItems.Insert(0, host);
}
}
private void FormBrowser_Load(object sender, EventArgs e)
{
SetWindowLong(this.Handle, GWL_STYLE, WS_CHILD);
// ホストプロセスに接続
BrowserHost = new PipeCommunicator<BrowserLib.IBrowserHost>(
this, typeof(BrowserLib.IBrowser), ServerUri + "Browser", "Browser");
BrowserHost.Connect(ServerUri + "/BrowserHost");
BrowserHost.Faulted += BrowserHostChannel_Faulted;
ConfigurationChanged(BrowserHost.Proxy.Configuration);
// ウィンドウの親子設定&ホストプロセスから接続してもらう
BrowserHost.Proxy.ConnectToBrowser(this.Handle);
// 親ウィンドウが生きているか確認
HeartbeatTimer.Tick += (EventHandler)((sender2, e2) =>
{
BrowserHost.AsyncRemoteRun(() => { HostWindow = BrowserHost.Proxy.HWND; });
});
HeartbeatTimer.Interval = 2000; // 2秒ごと
HeartbeatTimer.Start();
BrowserHost.AsyncRemoteRun(() => BrowserHost.Proxy.GetIconResource());
InitializeBrowser();
}
/// <summary>
/// ブラウザを初期化します。
/// 最初の呼び出しのみ有効です。二回目以降は何もしません。
/// </summary>
void InitializeBrowser()
{
if (Browser != null)
return;
if (HttpProxyPort == 0)
return;
//var settings = new CefSettings()
//{
// BrowserSubprocessPath = Path.Combine(
// AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
// Environment.Is64BitProcess ? "x64" : "x86",
// "CefSharp.BrowserSubprocess.exe"),
// CachePath = BrowserCachePath,
// Locale = "ja",
// AcceptLanguageList = "ja,en-US,en", // todo: いる?
// LogSeverity = LogSeverity.Error,
// LogFile = "BrowserLog.log",
//};
//if (!Configuration.HardwareAccelerationEnabled)
// settings.DisableGpuAcceleration();
//settings.CefCommandLineArgs.Add("proxy-server", ProxySettings);
//if (Configuration.ForceColorProfile)
// settings.CefCommandLineArgs.Add("force-color-profile", "srgb");
//CefSharpSettings.SubprocessExitIfParentProcessClosed = true;
//Cef.Initialize(settings, false, null);
//var requestHandler = new RequestHandler(pixiSettingEnabled: Configuration.PreserveDrawingBuffer);
//requestHandler.RenderProcessTerminated += (mes) => AddLog(3, mes);
Xpcom.Initialize("Firefox");
GeckoPreferences.Default["network.proxy.type"] = 1;
GeckoPreferences.Default["network.proxy.http"] = HttpProxyHost;
GeckoPreferences.Default["network.proxy.http_port"] = HttpProxyPort;
if (SslProxyPort != 0)
{
GeckoPreferences.Default["network.proxy.ssl"] = SslProxyHost;
GeckoPreferences.Default["network.proxy.ssl_port"] = SslProxyPort;
}
if (!Configuration.HardwareAccelerationEnabled)
{
GeckoPreferences.Default["gfx.direct2d.disabled"] = true;
GeckoPreferences.Default["layers.acceleration.disabled"] = true;
}
GeckoPreferences.Default["devtools.debugger.remote-enabled"] = true;
Browser = new GeckoWebBrowser()
{
Dock = DockStyle.None,
Size = SizeAdjuster.Size,
//RequestHandler = requestHandler,
//MenuHandler = new MenuHandler(),
//KeyboardHandler = new KeyboardHandler(),
//DragHandler = new DragHandler(),
};
Browser.DocumentCompleted += Browser_DocumentCompleted;
//Browser.LoadingStateChanged += Browser_LoadingStateChanged;
SizeAdjuster.Controls.Add(Browser);
}
void Exit()
{
if (!BrowserHost.Closed)
{
BrowserHost.Close();
HeartbeatTimer.Stop();
Xpcom.Shutdown();
Application.Exit();
}
}
void BrowserHostChannel_Faulted(Exception e)
{
// 親と通信できなくなったら終了する
Exit();
}
public void CloseBrowser()
{
HeartbeatTimer.Stop();
// リモートコールでClose()呼ぶのばヤバそうなので非同期にしておく
BeginInvoke((Action)(() => Exit()));
}
public void ConfigurationChanged(BrowserLib.BrowserConfiguration conf)
{
Configuration = conf;
SizeAdjuster.AutoScroll = Configuration.IsScrollable;
ToolMenu_Other_Zoom_Fit.Checked = Configuration.ZoomFit;
ApplyZoom();
ToolMenu_Other_AppliesStyleSheet.Checked = Configuration.AppliesStyleSheet;
ToolMenu.Dock = (DockStyle)Configuration.ToolMenuDockStyle;
ToolMenu.Visible = Configuration.IsToolMenuVisible;
}
private void ConfigurationUpdated()
{
BrowserHost.AsyncRemoteRun(() => BrowserHost.Proxy.ConfigurationUpdated(Configuration));
}
private void AddLog(int priority, string message)
{
BrowserHost.AsyncRemoteRun(() => BrowserHost.Proxy.AddLog(priority, message));
}
private void SendErrorReport(string exceptionName, string message)
{
BrowserHost.AsyncRemoteRun(() => BrowserHost.Proxy.SendErrorReport(exceptionName, message));
}
public void InitialAPIReceived()
{
IsKanColleLoaded = true;
//ロード直後の適用ではレイアウトがなぜか崩れるのでこのタイミングでも適用
ApplyStyleSheet();
ApplyZoom();
DestroyDMMreloadDialog();
//起動直後はまだ音声が鳴っていないのでミュートできないため、この時点で有効化
SetVolumeState();
}
private void SizeAdjuster_SizeChanged(object sender, EventArgs e)
{
if (!StyleSheetApplied)
{
if (Browser != null)
{
Browser.Location = new Point(0, 0);
Browser.Size = SizeAdjuster.Size;
}
return;
}
ApplyZoom();
}
private void CenteringBrowser()
{
if (SizeAdjuster.Width == 0 || SizeAdjuster.Height == 0) return;
int x = Browser.Location.X, y = Browser.Location.Y;
bool isScrollable = Configuration.IsScrollable;
if (!isScrollable || Browser.Width <= SizeAdjuster.Width)
{
x = (SizeAdjuster.Width - Browser.Width) / 2;
}
if (!isScrollable || Browser.Height <= SizeAdjuster.Height)
{
y = (SizeAdjuster.Height - Browser.Height) / 2;
}
//if ( x != Browser.Location.X || y != Browser.Location.Y )
Browser.Location = new Point(x, y);
}
private void Browser_DocumentCompleted(object sender, GeckoDocumentCompletedEventArgs e)
{
// DocumentCompleted に相当?
// note: 非 UI thread からコールされるので、何かしら UI に触る場合は適切な処置が必要
BeginInvoke((Action)(() =>
{
ApplyStyleSheet();
ApplyZoom();
DestroyDMMreloadDialog();
}));
}
private bool IsBrowserInitialized =>
Browser != null;
private GeckoWindow GetMainFrame()
{
if (!IsBrowserInitialized)
return null;
if (Browser.Document?.Url?.AbsoluteUri.Contains(@"http://www.dmm.com/netgame/social/") ?? false)
return Browser.Window;
return null;
}
private GeckoIFrameElement GetGameFrame()
{
if (!IsBrowserInitialized)
return null;
var frames = Browser.Document?.GetElementsByTagName("iframe");
return frames.Select(f => f as Gecko.DOM.GeckoIFrameElement)
.FirstOrDefault(f => f?.Src.Contains(@"http://osapi.dmm.com/gadgets/") ?? false) ;
}
private GeckoDocument GetKanColleFrame()
{
if (!IsBrowserInitialized)
return null;
var frames = Browser.Document?.GetElementsByTagName("iframe");
return frames.Select(f => f as Gecko.DOM.GeckoIFrameElement)
.FirstOrDefault(f => f.Src?.Contains(@"/kcs2/index.php") ?? false)?.ContentDocument;
}
/// <summary>
/// スタイルシートを適用します。
/// </summary>
public void ApplyStyleSheet()
{
if (!IsBrowserInitialized)
return;
if (!Configuration.AppliesStyleSheet && !RestoreStyleSheet)
return;
try
{
var mainframe = GetMainFrame();
var gameframe = GetGameFrame();
if (mainframe == null || gameframe == null)
return;
var context = new AutoJSContext(mainframe);
if (RestoreStyleSheet)
{
context.EvaluateScript(string.Format(GeckoBrowser.Properties.Resources.RestoreScript, StyleClassID));
//context.EvaluateScript(string.Format(GeckoBrowser.Properties.Resources.RestoreScript, StyleClassID));
StyleSheetApplied = false;
RestoreStyleSheet = false;
}
else
{
context.EvaluateScript(string.Format(GeckoBrowser.Properties.Resources.PageScript, StyleClassID));
//context.EvaluateScript(string.Format(GeckoBrowser.Properties.Resources.FrameScript, StyleClassID));
}
StyleSheetApplied = true;
}
catch (Exception ex)
{
SendErrorReport(ex.ToString(), "スタイルシートの適用に失敗しました。");
}
}
/// <summary>
/// DMMによるページ更新ダイアログを非表示にします。
/// </summary>
public void DestroyDMMreloadDialog()
{
if (!IsBrowserInitialized)
return;
if (!Configuration.IsDMMreloadDialogDestroyable)
return;
try
{
var mainframe = GetMainFrame();
if (mainframe == null)
return;
var mainJs = new AutoJSContext(mainframe);
mainJs.EvaluateScript(GeckoBrowser.Properties.Resources.DMMScript);
}
catch (Exception ex)
{
SendErrorReport(ex.ToString(), "DMMによるページ更新ダイアログの非表示に失敗しました。");
}
}
/// <summary>
/// 指定した URL のページを開きます。
/// </summary>
public void Navigate(string url)
{
if (url != Configuration.LogInPageURL || !Configuration.AppliesStyleSheet)
StyleSheetApplied = false;
Browser.Navigate(url);
}
/// <summary>
/// ブラウザを再読み込みします。
/// </summary>
public void RefreshBrowser() => RefreshBrowser(false);
/// <summary>
/// ブラウザを再読み込みします。
/// </summary>
/// <param name="ignoreCache">キャッシュを無視するか。</param>
public void RefreshBrowser(bool ignoreCache)
{
if (!Configuration.AppliesStyleSheet)
StyleSheetApplied = false;
if (ignoreCache)
{
Browser.Reload(GeckoLoadFlags.BypassCache);
}
else
{
Browser.Reload();
}
}
/// <summary>
/// ズームを適用します。
/// </summary>
public void ApplyZoom()
{
if (!IsBrowserInitialized)
return;
double zoomRate = Configuration.ZoomRate;
bool fit = Configuration.ZoomFit && StyleSheetApplied;
double zoomFactor;
if (fit)
{
double rateX = (double)SizeAdjuster.Width / KanColleSize.Width;
double rateY = (double)SizeAdjuster.Height / KanColleSize.Height;
zoomFactor = Math.Min(rateX, rateY);
}
else
{
if (zoomRate < 0.1)
zoomRate = 0.1;
if (zoomRate > 10)
zoomRate = 10;
zoomFactor = zoomRate;
}
Browser.GetDocShellAttribute().GetContentViewerAttribute().SetFullZoomAttribute((float) zoomFactor);
if (StyleSheetApplied)
{
Browser.Size = Browser.MinimumSize = new Size(
(int)(KanColleSize.Width * zoomFactor),
(int)(KanColleSize.Height * zoomFactor)
);
CenteringBrowser();
}
if (fit)
{
ToolMenu_Other_Zoom_Current.Text = "現在: ぴったり";
}
else
{
ToolMenu_Other_Zoom_Current.Text = $"現在: {zoomRate:p1}";
}
}
/// <summary>
/// スクリーンショットを撮影します。
/// </summary>
private async Task<Bitmap> TakeScreenShot()
{
return null;
// var kancolleFrame = GetKanColleFrame();
// if (kancolleFrame == null)
// {
// AddLog(3, string.Format("艦これが読み込まれていないため、スクリーンショットを撮ることはできません。"));
// System.Media.SystemSounds.Beep.Play();
// return null;
// }
// Task<ScreenShotPacket> InternalTakeScreenShot()
// {
// var request = new ScreenShotPacket();
// if (Browser == null || !Browser.IsBrowserInitialized)
// return request.TaskSource.Task;
// string script = $@"
//(async function()
//{{
// await CefSharp.BindObjectAsync('{request.ID}');
// let canvas = document.querySelector('canvas');
// requestAnimationFrame(() =>
// {{
// let dataurl = canvas.toDataURL('image/png');
// {request.ID}.complete(dataurl);
// }});
//}})();
//";
// Browser.JavascriptObjectRepository.Register(request.ID, request, true);
// kancolleFrame.ExecuteJavaScriptAsync(script);
// return request.TaskSource.Task;
// }
// var result = await InternalTakeScreenShot();
// // ごみ掃除
// Browser.JavascriptObjectRepository.UnRegister(result.ID);
// kancolleFrame.ExecuteJavaScriptAsync($@"delete {result.ID}");
// return result.GetImage();
}
/// <summary>
/// スクリーンショットを撮影し、設定で指定された保存先に保存します。
/// </summary>
public async Task SaveScreenShot()
{
int savemode = Configuration.ScreenShotSaveMode;
int format = Configuration.ScreenShotFormat;
string folderPath = Configuration.ScreenShotPath;
bool is32bpp = format != 1 && Configuration.AvoidTwitterDeterioration;
Bitmap image = null;
try
{
image = await TakeScreenShot();
if (image == null)
return;
if (is32bpp)
{
if (image.PixelFormat != PixelFormat.Format32bppArgb)
{
var imgalt = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);
using (var g = Graphics.FromImage(imgalt))
{
g.DrawImage(image, new Rectangle(0, 0, imgalt.Width, imgalt.Height));
}
image.Dispose();
image = imgalt;
}
// 不透明ピクセルのみだと jpeg 化されてしまうため、1px だけわずかに透明にする
Color temp = image.GetPixel(image.Width - 1, image.Height - 1);
image.SetPixel(image.Width - 1, image.Height - 1, Color.FromArgb(252, temp.R, temp.G, temp.B));
}
else
{
if (image.PixelFormat != PixelFormat.Format24bppRgb)
{
var imgalt = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb);
using (var g = Graphics.FromImage(imgalt))
{
g.DrawImage(image, new Rectangle(0, 0, imgalt.Width, imgalt.Height));
}
image.Dispose();
image = imgalt;
}
}
// to file
if ((savemode & 1) != 0)
{
try
{
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
string ext;
ImageFormat imgFormat;
switch (format)
{
case 1:
ext = "jpg";
imgFormat = ImageFormat.Jpeg;
break;
case 2:
default:
ext = "png";
imgFormat = ImageFormat.Png;
break;
}
string path = $"{folderPath}\\{DateTime.Now:yyyyMMdd_HHmmssff}.{ext}";
image.Save(path, imgFormat);
_lastScreenShotPath = path;
AddLog(2, $"スクリーンショットを {path} に保存しました。");
}
catch (Exception ex)
{
SendErrorReport(ex.ToString(), "スクリーンショットの保存に失敗しました。");
}
}
// to clipboard
if ((savemode & 2) != 0)
{
try
{
Clipboard.SetImage(image);
if ((savemode & 3) != 3)
AddLog(2, "スクリーンショットをクリップボードにコピーしました。");
}
catch (Exception ex)
{
SendErrorReport(ex.ToString(), "スクリーンショットのクリップボードへのコピーに失敗しました。");
}
}
}
catch (Exception ex)
{
SendErrorReport(ex.ToString(), "スクリーンショットの撮影に失敗しました。");
}
finally
{
image?.Dispose();
}
}
public void SetProxy(string proxy)
{
ushort port;
if (ushort.TryParse(proxy, out port))
{
//WinInetUtil.SetProxyInProcessForNekoxy(port);
HttpProxyHost = "127.0.0.1";
HttpProxyPort = port;
//ProxySettings = "http=127.0.0.1:" + port; // todo: 動くには動くが正しいかわからない
}
else
{
//WinInetUtil.SetProxyInProcess(proxy, "local");
Regex regexWithUpstream = new Regex(@"^http=127\.0\.0\.1\:(\d+);https=(.+)\:(\d+)$");
var match = regexWithUpstream.Match(proxy);
if (match.Success)
{
HttpProxyHost = "127.0.0.1";
HttpProxyPort = Convert.ToInt32(match.Groups[1].Value);
SslProxyHost = match.Groups[2].Value;
SslProxyPort = Convert.ToInt32(match.Groups[3].Value);
}
Regex regexWithoutUpstream = new Regex(@"^http=127\.0\.0\.1\:(\d+)$");
var match2 = regexWithoutUpstream.Match(proxy);
if (match2.Success)
{
HttpProxyHost = "127.0.0.1";
HttpProxyPort = Convert.ToInt32(match2.Groups[1].Value);
}
//ProxySettings = proxy;
}
InitializeBrowser();
BrowserHost.AsyncRemoteRun(() => BrowserHost.Proxy.SetProxyCompleted());
}
/// <summary>
/// キャッシュを削除します。
/// </summary>
private bool ClearCache(long timeoutMilliseconds = 5000)
{
// note: Cef が起動している状態では削除できない X(
// 今のところ手動でやってもらうことにする
return true;
}
public void SetIconResource(byte[] canvas)
{
string[] keys = new string[] {
"Browser_ScreenShot",
"Browser_Zoom",
"Browser_ZoomIn",
"Browser_ZoomOut",
"Browser_Unmute",
"Browser_Mute",
"Browser_Refresh",
"Browser_Navigate",
"Browser_Other",
};
int unitsize = 16 * 16 * 4;
for (int i = 0; i < keys.Length; i++)
{
Bitmap bmp = new Bitmap(16, 16, PixelFormat.Format32bppArgb);
if (canvas != null)
{
BitmapData bmpdata = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
Marshal.Copy(canvas, unitsize * i, bmpdata.Scan0, unitsize);
bmp.UnlockBits(bmpdata);
}
Icons.Images.Add(keys[i], bmp);
}
ToolMenu_ScreenShot.Image = ToolMenu_Other_ScreenShot.Image =
Icons.Images["Browser_ScreenShot"];
ToolMenu_Zoom.Image = ToolMenu_Other_Zoom.Image =
Icons.Images["Browser_Zoom"];
ToolMenu_Other_Zoom_Increment.Image =
Icons.Images["Browser_ZoomIn"];
ToolMenu_Other_Zoom_Decrement.Image =
Icons.Images["Browser_ZoomOut"];
ToolMenu_Refresh.Image = ToolMenu_Other_Refresh.Image =
Icons.Images["Browser_Refresh"];
ToolMenu_NavigateToLogInPage.Image = ToolMenu_Other_NavigateToLogInPage.Image =
Icons.Images["Browser_Navigate"];
ToolMenu_Other.Image =
Icons.Images["Browser_Other"];
SetVolumeState();
}
public void SendMouseEvent(string type, double x, double y)
{
}
public byte[] TakeScreenShotAsPngBytes()
{
return new byte[] { };
}
private void SetVolumeState()
{
bool mute;
float volume;
try
{
mute = _volumeManager.IsMute;
volume = _volumeManager.Volume * 100;
}
catch (Exception)
{
// 音量データ取得不能時
mute = false;
volume = 100;
}
ToolMenu_Mute.Image = ToolMenu_Other_Mute.Image =
Icons.Images[mute ? "Browser_Mute" : "Browser_Unmute"];
{
var control = ToolMenu_Other_Volume_VolumeControl;
control.Tag = false;
control.Value = (decimal)volume;
control.Tag = true;
}
Configuration.Volume = volume;
Configuration.IsMute = mute;
ConfigurationUpdated();
}
private async void ToolMenu_Other_ScreenShot_Click(object sender, EventArgs e)
{
await SaveScreenShot();
}
private void ToolMenu_Other_Zoom_Decrement_Click(object sender, EventArgs e)
{
Configuration.ZoomRate = Math.Max(Configuration.ZoomRate - 0.2, 0.1);
Configuration.ZoomFit = ToolMenu_Other_Zoom_Fit.Checked = false;
ApplyZoom();
ConfigurationUpdated();
}
private void ToolMenu_Other_Zoom_Increment_Click(object sender, EventArgs e)
{
Configuration.ZoomRate = Math.Min(Configuration.ZoomRate + 0.2, 10);
Configuration.ZoomFit = ToolMenu_Other_Zoom_Fit.Checked = false;
ApplyZoom();
ConfigurationUpdated();
}
private void ToolMenu_Other_Zoom_Click(object sender, EventArgs e)
{
double zoom;
if (sender == ToolMenu_Other_Zoom_25)
zoom = 0.25;
else if (sender == ToolMenu_Other_Zoom_50)
zoom = 0.50;
else if (sender == ToolMenu_Other_Zoom_Classic)
zoom = 0.667; // 2/3 ジャストだと 799x479 になる
else if (sender == ToolMenu_Other_Zoom_75)
zoom = 0.75;
else if (sender == ToolMenu_Other_Zoom_100)
zoom = 1;
else if (sender == ToolMenu_Other_Zoom_150)
zoom = 1.5;
else if (sender == ToolMenu_Other_Zoom_200)
zoom = 2;
else if (sender == ToolMenu_Other_Zoom_250)
zoom = 2.5;
else if (sender == ToolMenu_Other_Zoom_300)
zoom = 3;
else if (sender == ToolMenu_Other_Zoom_400)
zoom = 4;
else
zoom = 1;
Configuration.ZoomRate = zoom;
Configuration.ZoomFit = ToolMenu_Other_Zoom_Fit.Checked = false;
ApplyZoom();
ConfigurationUpdated();
}
private void ToolMenu_Other_Zoom_Fit_Click(object sender, EventArgs e)
{
Configuration.ZoomFit = ToolMenu_Other_Zoom_Fit.Checked;
ApplyZoom();
ConfigurationUpdated();
}
//ズームUIの使いまわし
private void ToolMenu_Other_DropDownOpening(object sender, EventArgs e)
{
var list = ToolMenu_Zoom.DropDownItems.Cast<ToolStripItem>().ToArray();
ToolMenu_Other_Zoom.DropDownItems.AddRange(list);
}
private void ToolMenu_Zoom_DropDownOpening(object sender, EventArgs e)
{
var list = ToolMenu_Other_Zoom.DropDownItems.Cast<ToolStripItem>().ToArray();
ToolMenu_Zoom.DropDownItems.AddRange(list);
}
private void ToolMenu_Other_Mute_Click(object sender, EventArgs e)
{
try
{
_volumeManager.ToggleMute();
}
catch (Exception)