11using Microsoft . Web . WebView2 . WinForms ;
22using System ;
33using System . ComponentModel ;
4+ using System . Reflection . Metadata ;
45using System . Threading . Tasks ;
6+ using System . Windows . Controls ;
57using System . Windows . Forms ;
68
79namespace MORT . TransAPI
@@ -55,7 +57,7 @@ public void PrepareTranslate(DateTime dateTimeout)
5557
5658 public void Init ( IDeeplAPIContract contract , string frontUrl , string urlFormat , string elementTarget )
5759 {
58- if ( _webView != null )
60+ if ( _webView != null )
5961 {
6062 return ;
6163 }
@@ -102,9 +104,9 @@ public void DoTrans(string original, string transCode, string resultCode)
102104
103105 private string ConvertHtmlToResult ( string html )
104106 {
105- if ( html . Length > 2 )
107+ if ( html . Length > 2 )
106108 {
107- if ( html [ 0 ] == '"' && html [ html . Length - 1 ] == '"' )
109+ if ( html [ 0 ] == '"' && html [ html . Length - 1 ] == '"' )
108110 {
109111 html = html . Remove ( 0 , 1 ) ;
110112 html = html . Remove ( html . Length - 1 , 1 ) ;
@@ -117,9 +119,9 @@ private string ConvertHtmlToResult(string html)
117119 html = html . TrimEnd ( ) ;
118120 //html = html.Replace(GlobalDefine.SPLITE_TOEKN_DEEPL + "\\n\\n" ,GlobalDefine.SPLITE_TOEKN_DEEPL + System.Environment.NewLine);
119121
120- if ( html . IndexOf ( GlobalDefine . SPLITE_TOEKN_DEEPL ) == 0 )
122+ if ( html . IndexOf ( GlobalDefine . SPLITE_TOEKN_DEEPL ) == 0 )
121123 {
122- // html = html.Insert(GlobalDefine.SPLITE_TOEKN_DEEPL.Length, System.Environment.NewLine);
124+ // html = html.Insert(GlobalDefine.SPLITE_TOEKN_DEEPL.Length, System.Environment.NewLine);
123125 }
124126
125127
@@ -128,14 +130,15 @@ private string ConvertHtmlToResult(string html)
128130 return html ;
129131 }
130132
133+
131134 private async Task SourceAsync ( string text , string transCode , string resultCode )
132135 {
133136 while ( ! _start )
134137 {
135138 await Task . Delay ( 100 ) ;
136139 }
137140
138- while ( DateTime . Now < _dtNextAvailableTime )
141+ while ( DateTime . Now < _dtNextAvailableTime )
139142 {
140143 await Task . Delay ( 50 ) ;
141144 Console . WriteLine ( "Wait : " + _dtNextAvailableTime . ToString ( ) ) ;
@@ -150,11 +153,89 @@ private async Task SourceAsync(string text, string transCode, string resultCode)
150153 await Task . Delay ( ( int ) ( random * 140 ) ) ;
151154 string requestText = RestSharp . Extensions . StringExtensions . UrlEncode ( text ) ;
152155
153- if ( requestText != _lastUrl )
156+ try
154157 {
155- _webView . Source = new Uri ( string . Format ( _urlFormat , transCode , resultCode , requestText ) ) ;
156- Console . WriteLine ( "ocr : " + string . Format ( _urlFormat , transCode , resultCode , requestText ) ) ;
157- await Task . Delay ( 50 ) ;
158+
159+ string scriptToClearText = @"
160+ (function() {
161+ // 'data-testid=""translator-target-input""'를 가진 요소의 하위에 있는 'div[contenteditable=""true""]'를 찾습니다.
162+ var editableDiv = document.querySelector('[data-testid=""translator-target-input""] div[contenteditable=""true""]');
163+
164+ if (editableDiv) {
165+ // 1. 요소의 내부 HTML을 빈 문자열로 설정하여 텍스트를 비웁니다.
166+ editableDiv.innerHTML = '';
167+
168+ // 2. 입력 포커스를 다시 설정하여 사용자가 바로 입력할 수 있도록 합니다.
169+ editableDiv.focus();
170+
171+ // 3. (추가된 핵심 부분) 'input' 이벤트를 수동으로 생성하고 발생시킵니다.
172+ // 이 이벤트는 웹 애플리케이션에게 내용이 사용자 입력처럼 '변경'되었음을 알립니다.
173+ var event = new Event('input', { bubbles: true });
174+ editableDiv.dispatchEvent(event);
175+
176+ // 4. C#으로 성공 메시지 전송
177+ if (window.chrome && window.chrome.webview) {
178+ window.chrome.webview.postMessage('TEXTBOX_CLEARED_SUCCESS');
179+ }
180+
181+ return '텍스트 박스 내용이 성공적으로 비워졌으며, 변경 이벤트도 발생시켰습니다.';
182+ } else {
183+ return '지정된 data-testid와 contenteditable 속성을 모두 가진 요소를 찾을 수 없습니다.';
184+ }
185+ })();
186+ " ;
187+ var test = await _webView . ExecuteScriptAsync ( scriptToClearText ) ;
188+
189+ }
190+ catch
191+ {
192+
193+ }
194+
195+ if ( requestText != _lastUrl )
196+ {
197+ if ( false )
198+ {
199+ //더이상 사용하지 않는다 추후에 문제가 생기면 사용한다
200+ _webView . Source = new Uri ( string . Format ( _urlFormat , transCode , resultCode , requestText ) ) ;
201+ Console . WriteLine ( "ocr : " + string . Format ( _urlFormat , transCode , resultCode , requestText ) ) ;
202+ await Task . Delay ( 50 ) ;
203+ }
204+ else
205+ {
206+ string safeNewText = System . Text . Json . JsonSerializer . Serialize ( text ) ;
207+
208+ string scriptToSetText = $@ "
209+ (function() {{
210+ // 소스 텍스트 박스('data-testid=""translator-source-input""')의 하위에 있는 'div[contenteditable=""true""]'를 찾습니다.
211+ var editableDiv = document.querySelector('[data-testid=""translator-source-input""] div[contenteditable=""true""]');
212+
213+ if (editableDiv) {{
214+ // 1. 요소의 내부 HTML을 지정된 새로운 텍스트로 설정하여 내용을 바꿉니다.
215+ editableDiv.innerHTML = '<p>{ safeNewText . Trim ( '"' ) } </p>';
216+
217+ // 2. 입력 포커스를 다시 설정합니다.
218+ editableDiv.focus();
219+
220+ // 3. (핵심 부분) 'input' 이벤트를 수동으로 생성하고 발생시킵니다.
221+ var event = new Event('input', {{ bubbles: true }});
222+ editableDiv.dispatchEvent(event);
223+
224+ // 4. C#으로 성공 메시지 전송
225+ if (window.chrome && window.chrome.webview) {{
226+ window.chrome.webview.postMessage('SOURCE_TEXTBOX_SET_SUCCESS');
227+ }}
228+
229+ return '소스 텍스트 박스 내용이 성공적으로 설정되었으며, 변경 이벤트도 발생시켰습니다.';
230+ }} else {{
231+ return '지정된 data-testid=""translator-source-input"" 요소를 찾을 수 없습니다.';
232+ }}
233+ }})();
234+ " ;
235+
236+ await _webView . ExecuteScriptAsync ( scriptToSetText ) ;
237+ }
238+
158239 }
159240 else
160241 {
@@ -173,9 +254,9 @@ private async Task SourceAsync(string text, string transCode, string resultCode)
173254 await Task . Delay ( 50 ) ;
174255 var html = await _webView . CoreWebView2 . ExecuteScriptAsync ( _elementTarget ) ;
175256 string origianl = html ;
176- if ( html == null || html == "null" || html == "" || html == "\" \\ n\" " || html == "\" \" " )
257+ if ( html == null || html == "null" || html == "" || html == "\" \\ n\" " || html == "\" \" " )
177258 {
178- if ( _dtTimeout < DateTime . Now )
259+ if ( _dtTimeout < DateTime . Now )
179260 {
180261 Complete = true ;
181262 IsError = true ;
@@ -195,7 +276,7 @@ private async Task SourceAsync(string text, string transCode, string resultCode)
195276
196277 result = html ;
197278
198- if ( _dtTimeout < DateTime . Now && false )
279+ if ( _dtTimeout < DateTime . Now && false )
199280 {
200281 Complete = true ;
201282 IsError = true ;
@@ -204,10 +285,10 @@ private async Task SourceAsync(string text, string transCode, string resultCode)
204285 return ;
205286 }
206287 }
207- catch ( Exception e ) { IsError = true ; Complete = true ; _lastResult = e . Message ; Console . WriteLine ( e ) ; }
288+ catch ( Exception e ) { IsError = true ; Complete = true ; _lastResult = e . Message ; Console . WriteLine ( e ) ; }
208289
209290 }
210- while ( result == _lastResult || result == _defaultKey ) ;
291+ while ( result == _lastResult || result == _defaultKey ) ;
211292
212293 //랜덤 딜레이를 준다
213294 random = _rand . NextDouble ( ) ;
@@ -221,7 +302,7 @@ private async Task SourceAsync(string text, string transCode, string resultCode)
221302
222303 private void WebView_NavigationCompleted ( object sender , Microsoft . Web . WebView2 . Core . CoreWebView2NavigationCompletedEventArgs e )
223304 {
224- if ( ! _start )
305+ if ( ! _start )
225306 {
226307 _contract . UpdateCondition ( $ "DeepL_Ready") ;
227308 _start = true ;
@@ -230,7 +311,7 @@ private void WebView_NavigationCompleted(object sender, Microsoft.Web.WebView2.C
230311
231312 private void DeeplWebView_FormClosing ( object sender , FormClosingEventArgs e )
232313 {
233- if ( e . CloseReason == CloseReason . UserClosing )
314+ if ( e . CloseReason == CloseReason . UserClosing )
234315 {
235316 Hide ( ) ;
236317 e . Cancel = true ; //종료를 취소하고
0 commit comments