テキストエディターで選択された英語の文章の部分を、日本語に翻訳して上書きします。
すべてのソース (Googleサイトの読み込みが失敗するようになったために再編集したました[2022/10/21])
use AppleScript version "2." use scripting additions use framework "Foundation" use framework "AppKit" global myApp global theWindow global closeFlg global textView1, webView1, button1 (*開始処理*) on run my performSelectorOnMainThread:"mainMakeObject:" withObject:(missing value) waitUntilDone:true -- log "End" end run (*主作業ルーチン(作成から終了まで)*) on mainMakeObject:inputObj set myApp to current application set closeFlg to false -- ウインドウ set aTitle to "翻訳" set aRect to {50, 50, 640, 400} set moveCenter to false set theWindow to my makeNewWindow(aTitle, aRect, moveCenter) -- オブジェクト my makeObject() theWindow's setAlphaValue:1.0 --プログラムの続行、又は終了の判断処理 repeat if closeFlg then my closeWin:theWindow exit repeat end if delay 0.2 end repeat end mainMakeObject: (*新しいWindowの作成*) on makeNewWindow(aTitle, aRect, moveCenter) set {windowX, windowY, windowW, windowH} to aRect set theRect to myApp's NSMakeRect(windowX, windowY, windowW, windowH) set aScreen to myApp's class "NSScreen"'s mainScreen() set aStyle to (myApp's NSWindowStyleMaskTitled as integer) set aStyle to aStyle + (myApp's NSWindowStyleMaskClosable as integer) set aStyle to aStyle + (myApp's NSWindowStyleMaskMiniaturizable as integer) set aStyle to aStyle + (myApp's NSWindowStyleMaskResizable as integer) set aBacking to myApp's NSBackingStoreBuffered set aWindow to myApp's class "NSWindow"'s alloc()'s initWithContentRect:theRect styleMask:aStyle backing:aBacking defer:false screen:aScreen tell aWindow setAlphaValue_(0.0) setDelegate_(me) setTitle_(aTitle) setMinSize_(myApp's NSMakeSize(420, 380)) setMaxSize_(myApp's NSMakeSize(10000, 10000)) setBackgroundColor_(myApp's class "NSColor"'s colorWithCalibratedRed:0.95 green:0.95 blue:0.95 alpha:1.0) setDisplaysWhenScreenProfileChanges_(true) setReleasedWhenClosed_(true) makeKeyAndOrderFront_(me) end tell -- if moveCenter then aWindow's |center|() -- windowをセンターに移動 return aWindow end makeNewWindow (* 各オブジェクトの配置 *) on makeObject() set mainView to theWindow's contentView set theWindowFrame to mainView's frame() set {{windowX, windowY}, {windowWidth, windowHeight}} to theWindowFrame -- --set minXMargin to (myApp's NSViewMinXMargin) as integer -- 左の余白を柔軟に set maxXMargin to (myApp's NSViewMaxXMargin) as integer -- 右の余白を柔軟に set minYMargin to (myApp's NSViewMinYMargin) as integer -- 下の余白を柔軟に --set maxYMargin to (myApp's NSViewMaxYMargin) as integer -- 上の余白を柔軟に set widthSizable to (myApp's NSViewWidthSizable) as integer -- 横方向の幅を柔軟に set heightSizable to (myApp's NSViewHeightSizable) as integer -- 縦方向の幅を柔軟に -- try -- 新しくオブジェクトを配置する部分 -------------------- -- NSButton set theRect to myApp's NSMakeRect(50, windowHeight - 52, windowWidth - 100, 50) set button1 to myApp's class "NSButton"'s alloc()'s initWithFrame:theRect tell button1 setBezelStyle_(myApp's NSBezelStyleTexturedSquare) setButtonType_(myApp's NSButtonTypeMomentaryLight) setTitle_("翻訳はここをクリック") setTarget_(me) setAction_("action1:") setAutoresizingMask_(widthSizable + minYMargin) end tell mainView's addSubview:button1 -- WebView set theRect to myApp's NSMakeRect(0, -1000, 1000, 1000) set webView1 to myApp's class "WKWebView"'s alloc()'s initWithFrame:theRect tell webView1 setAutoresizingMask_(maxXMargin + minYMargin) setAlphaValue_(0.0) end tell mainView's addSubview:webView1 set locationUrl to "https://translate.google.co.jp/" set aUrl to myApp's class "NSURL"'s URLWithString:locationUrl set aRequest to myApp's class "NSURLRequest"'s requestWithURL:aUrl webView1's loadRequest:aRequest -- TextViewセット set {x, y, w, h} to {3, 3, windowWidth - 6, windowHeight - 60} set theRect to myApp's NSMakeRect(x, y, w, h) set scrollview1 to myApp's class "NSScrollView"'s alloc()'s initWithFrame:theRect tell scrollview1 setBorderType_(0) setHasVerticalScroller_(true) setHasHorizontalScroller_(false) setAutoresizingMask_(widthSizable + heightSizable) end tell set textView1 to myApp's class "NSTextView"'s alloc()'s initWithFrame:theRect tell textView1 setMinSize_(myApp's NSMakeSize(0, h)) setMaxSize_(myApp's NSMakeSize(10000, 10000)) setVerticallyResizable_(true) setHorizontallyResizable_(false) setAutoresizingMask_(widthSizable) textContainer()'s setContainerSize:(myApp's NSMakeSize(w, 10000)) textView1's setString:"" end tell textView1's textContainer's setWidthTracksTextView:true scrollview1's setDocumentView:textView1 mainView's addSubview:scrollview1 ---------------------------------------------------------- on error errText log errText end try end makeObject on action1:sender -- テキストエディタから原文の取得 set aText to getText() if (aText as text) = "" then return -- 2度押し防止のためにボタンの停止 tell button1 setTitle_("翻訳作業中") setEnabled_(false) end tell -- 原文の末尾に改行があるかのチェック if (paragraph -1 of aText) = "" then set endCode to ASCII character 13 set aText to text from paragraph 1 to paragraph -2 of aText else set endCode to "" end if if aText = false then return -- 原文を1行づつ切り分けて翻訳作業しながらまとめる set textData to "原文:" & return & aText & return & return textView1's setString:textData set aLine to "ーーーーーーーーーー" set textData to textData & (aLine & aLine & aLine) & return & return & "訳文:" & return set allText to "" try repeat with oneLine in (paragraphs of aText) set oneLine to oneLine as text if (oneLine ≠ "") or (oneLine ≠ (character id 10)) or (oneLine ≠ (character id 13)) then set aData to (my googleTranslate:oneLine) if aData = false then set aData to "(-- Error --)" else set aData to "" end if set allText to allText & aData & return (textView1's setString:(textData & allText & "...")) end repeat on error errText log errText end try -- 翻訳終了後の結果を反映 set allText to text from paragraph 1 to paragraph -2 of allText set textData to textData & allText textView1's setString:textData if (aData = "(-- Error --)") or (aData = "false") or (aData = "") then set locationUrl to "https://translate.google.co.jp/" set aUrl to myApp's class "NSURL"'s URLWithString:locationUrl set aRequest to myApp's class "NSURLRequest"'s requestWithURL:aUrl webView1's loadRequest:aRequest else my overWriteText:(allText & endCode) end if -- ボタンの復帰 tell button1 setTitle_("翻訳はここをクリック") setEnabled_(true) end tell end action1: on googleTranslate:aText -- |原文を翻訳作業するルーチン、翻訳結果を返します| set locationUrl to my keywordDelimiter(aText) --url取得 --webViewへ set aUrl to current application's class "NSURL"'s URLWithString:locationUrl set aRequest to myApp's class "NSURLRequest"'s requestWithURL:aUrl webView1's loadRequest:aRequest -- webViewの表示の完了待ち(『翻訳結果』というテキストの有無で判断) set aData to "" repeat 6 times delay 0.5 try tell application "System Events" tell process (name of myApp) set objList to entire contents of window 1 --オブジェクト(UI Elements)を取得 end tell end tell try -- Try処理を利用してオブジェクトをテキスト化 set aText to objList as text on error errText set aText to errText end try if aText contains "翻訳結果" then exit repeat end try end repeat -- テキストから翻訳結果の部分を抽出 set aText to my setDelimiter(aText, "\", ", "\"" & return) set lineNo1 to count of paragraphs of (text 1 thru (offset in aText of " \"翻訳結果\"") of aText) set aData to "" if lineNo1 > 0 then set aText2 to text from paragraph (lineNo1 + 2) to paragraph -1 of aText set lineNo2 to count of paragraphs of (text 1 thru (offset in aText2 of "«class sttx»") of aText2) repeat with n from 1 to 100 set obj to paragraph (lineNo1 + lineNo2 + n) of aText if not (obj contains "«class sttx»") then exit repeat set output to text ((offset in obj of "\"") + 1) thru -1 of obj set aData to aData & (text 1 thru ((offset in output of "\"") - 1) of output) end repeat end if if aData = "" then return false
return aData end googleTranslate: on getText() -- |テキストエディターから選択部分を読み取り| if application "TextEdit" is not running then return false --テキストエディタが起動しているか? set the clipboard to "" --クリップボードのデータの初期化 activate application "TextEdit" --テキストエディタを最前面に移動 --クリップボードを利用して選択された文章の取得 try tell application "System Events" keystroke "c" using command down delay 0.1 keystroke "c" using command down delay 0.1 end tell set aText to (the clipboard) as text on error set aText to "" end try --表示文字(スペースやコントロール文字以外)があるかの確認 set f to true repeat with oneChara in (characters of aText) if (id of (oneChara as text)) > 32 then set f to false exit repeat end if end repeat if f then set aText to "" return aText end getText on overWriteText:aText --|翻訳終了後にテキストエディターへの上書き| activate application "TextEdit" set the clipboard to aText delay 0.2 tell application "System Events" tell process "TextEdit" keystroke "v" using command down end tell end tell end overWriteText: on keywordDelimiter(inputText) -- |Google翻訳をお願いするためのURLの取得| if (inputText contains "\"") then set inputText to my setDelimiter(inputText, "\"", "''") --動作の障害となるダブルクオート回避 set aText to run script ("encodeURIComponent(\"" & inputText & "\")") in "Javascript" set aUrl to "https://translate.google.co.jp/?hl=ja&sl=auto&tl=ja&text=" & aText & "&op=translate" return aUrl end keywordDelimiter on setDelimiter(textItem, oldText, newText) --|デリミタ| set textItem to textItem as text set lastDelimit to AppleScript's text item delimiters set AppleScript's text item delimiters to oldText set obj to every text item of textItem set AppleScript's text item delimiters to newText set textItem to obj as text set AppleScript's text item delimiters to lastDelimit return textItem end setDelimiter (* ウインドウバーの閉じるボタンアクションを受けた時 *) on windowShouldClose:sender set closeFlg to true end windowShouldClose: (* ウインドウを閉じるための実際のアクション *) on closeWin:aWindow aWindow's orderOut:me if (name of myApp) ≠ "Script Editor" then quit me end closeWin: |