Skip to content

Commit

Permalink
Merge branch 'next'
Browse files Browse the repository at this point in the history
# Conflicts:
#	CHANGELOG.md
  • Loading branch information
YiiGuxing committed Jul 3, 2023
2 parents 5d7f266 + d7fa5fd commit e367589
Show file tree
Hide file tree
Showing 22 changed files with 76 additions and 54 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Translation Plugin Changelog

## [Unreleased]
- Bug fixes.
- Bug 修复

## [3.5.0] (2023/06/01)
- Added OpenAI Translator engine (Experimental).
Expand Down
8 changes: 4 additions & 4 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ plugins {
// Java support
id("java")
// Kotlin support
id("org.jetbrains.kotlin.jvm") version "1.8.21"
id("org.jetbrains.kotlin.jvm") version "1.8.22"
// Gradle IntelliJ Plugin
id("org.jetbrains.intellij") version "1.13.3"
id("org.jetbrains.intellij") version "1.14.2"
// Gradle Changelog Plugin
id("org.jetbrains.changelog") version "2.0.0"
id("org.jetbrains.changelog") version "2.1.0"
// Gradle Qodana Plugin
id("org.jetbrains.qodana") version "0.1.13"
// Gradle Kover Plugin
id("org.jetbrains.kotlinx.kover") version "0.7.0"
id("org.jetbrains.kotlinx.kover") version "0.7.2"
}


Expand Down
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pluginGroup = cn.yiiguxing.plugin.translate
pluginRepositoryUrl = https://github.com/YiiGuxing/TranslationPlugin

# SemVer format -> https://semver.org
pluginMajorVersion = 3.5.0
pluginMajorVersion = 3.5.1
pluginPreReleaseVersion =
pluginBuildMetadata =
autoSnapshotVersion = true
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/cn/yiiguxing/plugin/translate/HelpTopic.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package cn.yiiguxing.plugin.translate
enum class HelpTopic(id: String, val url: String) {

/** Default help */
DEFAULT("default", WebPages.getStarted()),
DEFAULT("default", WebPages.docs()),

/** 阿里机器翻译通用版 */
ALI("ali", "https://www.aliyun.com/product/ai/base_alimt"),
Expand Down
32 changes: 20 additions & 12 deletions src/main/kotlin/cn/yiiguxing/plugin/translate/Settings.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,16 @@ import kotlin.properties.Delegates
@State(name = "Translation.Settings", storages = [(Storage(TranslationStorages.PREFERENCES_STORAGE_NAME))])
class Settings : PersistentStateComponent<Settings> {

@Volatile
@Transient
private var isInitialized = false

/**
* 翻译API
*/
var translator: TranslationEngine
by Delegates.observable(GOOGLE) { _, oldValue: TranslationEngine, newValue: TranslationEngine ->
if (oldValue != newValue) {
if (isInitialized && oldValue != newValue) {
SETTINGS_CHANGE_PUBLISHER.onTranslatorChanged(this, newValue)
}
}
Expand Down Expand Up @@ -59,7 +63,7 @@ class Settings : PersistentStateComponent<Settings> {
* 主要字体
*/
var primaryFontFamily: String? by Delegates.observable(null) { _, oldValue: String?, newValue: String? ->
if (oldValue != newValue) {
if (isInitialized && oldValue != newValue) {
SETTINGS_CHANGE_PUBLISHER.onOverrideFontChanged(this)
}
}
Expand All @@ -68,7 +72,7 @@ class Settings : PersistentStateComponent<Settings> {
* 音标字体
*/
var phoneticFontFamily: String? by Delegates.observable(null) { _, oldValue: String?, newValue: String? ->
if (oldValue != newValue) {
if (isInitialized && oldValue != newValue) {
SETTINGS_CHANGE_PUBLISHER.onOverrideFontChanged(this)
}
}
Expand All @@ -77,7 +81,7 @@ class Settings : PersistentStateComponent<Settings> {
* 翻译时需要忽略的内容
*/
var ignoreRegex: String by Delegates.observable("[\\*/#\$]") { _, oldValue: String, newValue: String ->
if (oldValue != newValue) {
if (isInitialized && oldValue != newValue) {
ignoreRegexPattern = newValue.toIgnoreRegex()
}
}
Expand Down Expand Up @@ -155,23 +159,27 @@ class Settings : PersistentStateComponent<Settings> {
* 单词本存储路径
*/
var wordbookStoragePath: String? by Delegates.observable(null) { _, oldValue: String?, newValue: String? ->
if (oldValue != newValue) {
if (isInitialized && oldValue != newValue) {
SETTINGS_CHANGE_PUBLISHER.onWordbookStoragePathChanged(this)
}
}

override fun getState(): Settings = this

override fun loadState(state: Settings) {
XmlSerializerUtil.copyBean(state, this)
try {
XmlSerializerUtil.copyBean(state, this)

val properties: PropertiesComponent = PropertiesComponent.getInstance()
val dataVersion = properties.getInt(DATA_VERSION_KEY, 0)
val properties: PropertiesComponent = PropertiesComponent.getInstance()
val dataVersion = properties.getInt(DATA_VERSION_KEY, 0)

LOG.d("===== Settings Data Version: $dataVersion =====")
if (dataVersion < CURRENT_DATA_VERSION) {
migrate()
properties.setValue(DATA_VERSION_KEY, CURRENT_DATA_VERSION, 0)
LOG.d("===== Settings Data Version: $dataVersion =====")
if (dataVersion < CURRENT_DATA_VERSION) {
migrate()
properties.setValue(DATA_VERSION_KEY, CURRENT_DATA_VERSION, 0)
}
} finally {
isInitialized = true
}
}

Expand Down
14 changes: 7 additions & 7 deletions src/main/kotlin/cn/yiiguxing/plugin/translate/WebPages.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,26 +20,26 @@ object WebPages {
Locale.KOREAN.language -> "/ko"
else -> "/en"
}
return "$baseUrl$langPath/${path.joinToString("/")}"
return "$baseUrl/#$langPath/${path.joinToString("/")}"
}

fun getStarted(locale: Locale = Locale.getDefault()): String = get("start.html", locale = locale)
fun docs(locale: Locale = Locale.getDefault()): String = get("docs", locale = locale)

fun updates(version: String = "", locale: Locale = Locale.getDefault()): String {
val query = if (version.isEmpty()) "" else "?v=$version"
return get("updates.html${query}", locale = locale)
val query = if (version.isEmpty()) "" else "?v$version"
return get("updates${query}", locale = locale)
}

fun releaseNote(version: String, dark: Boolean = false, locale: Locale = Locale.getDefault()): String {
return get(
"updates",
"v${version.replace('.', '_')}.html?editor=true&dark=$dark",
"v$version?compact=true&dark=$dark",
locale = locale
)
}

fun support(locale: Locale = Locale.getDefault()): String = get("support.html", locale = locale)
fun support(locale: Locale = Locale.getDefault()): String = get("support", locale = locale)

fun donors(locale: Locale = Locale.getDefault()): String = get("support.html#patrons", locale = locale)
fun donors(locale: Locale = Locale.getDefault()): String = get("support?id=translation-plugin-sponsors", locale = locale)

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.editor.EditorMouseHoverPopupManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.ToolWindowId
Expand All @@ -33,8 +32,7 @@ open class ToggleQuickDocTranslationAction :
{ adaptedMessage("action.ToggleQuickDocTranslationAction.text") }
),
HintManagerImpl.ActionToIgnore,
ImportantTranslationAction,
DumbAware {
ImportantTranslationAction {

init {
// Enable in hovering documentation popup
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ abstract class BaseStartupActivity(private val runOnlyOnce: Boolean = false) : S
private var veryFirstProjectOpening: Boolean = true

final override fun runActivity(project: Project) {
if (Application.isUnitTestMode || (runOnlyOnce && !veryFirstProjectOpening)) {
if (Application.isUnitTestMode || (runOnlyOnce && !veryFirstProjectOpening) || project.isDisposed) {
return
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ private fun Document.addMessage(message: String, color: Color): Document = apply
*/
private fun String.fixHtml(): String = replace(fixHtmlClassExpressionRegex, FIX_HTML_CLASS_EXPRESSION_REPLACEMENT)

private fun Element.isEmptyParagraph(): Boolean = "p".equals(tagName(), true) && html().isBlank()

private fun DocumentationTranslator.getTranslatedDocumentation(document: Document, language: Language?): Document {
val body = document.body()
val definition = body.selectFirst(CSS_QUERY_DEFINITION)
Expand All @@ -125,6 +127,12 @@ private fun DocumentationTranslator.getTranslatedDocumentation(document: Documen
forEach { it.remove() }
}

// 删除多余的 `p` 标签。
body.selectFirst(CSS_QUERY_CONTENT)
?.nextElementSibling()
?.takeIf { it.isEmptyParagraph() }
?.remove()

val preElements = body.select(TAG_PRE)
preElements.forEachIndexed { index, element ->
element.replaceWith(Element(TAG_PRE).attr("id", index.toString()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import com.intellij.openapi.components.service
import com.intellij.util.io.RequestBuilder


private const val DEFAULT_GOOGLE_API_SERVER_URL = "https://translate.googleapis.com"
const val DEFAULT_GOOGLE_API_SERVER_URL = "https://translate.googleapis.com"

private const val GOOGLE_REFERER = "https://translate.google.com/"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class GoogleSettingsDialog : DialogWrapper(true) {

private val customServerCheckBox = JBCheckBox(message("google.settings.dialog.label.server"))
private val serverUrlField = JBTextField().apply {
emptyText.text = message("google.settings.dialog.tip.enter.server.url")
emptyText.text = DEFAULT_GOOGLE_API_SERVER_URL
}
private val testButton = JButton(message("action.test.text"))

Expand All @@ -54,7 +54,7 @@ class GoogleSettingsDialog : DialogWrapper(true) {
}

private fun initListeners() {
customServerCheckBox.addChangeListener {
customServerCheckBox.addItemListener {
update()
if (customServerCheckBox.isSelected) {
IdeFocusManager.getInstance(null).requestFocus(serverUrlField, true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ data class YWebExplain(
@SerializedName(value = "key")
var key: String? = null,
@SerializedName(value = "value")
var values: Array<out String>? = null
var values: Array<out String?>? = null
)

data class YWordFormWrapper(@SerializedName(value = "wf") val wordForm: YWordForm)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,22 @@ class YoudaoWebTranslationDocument private constructor(private val webTranslatio
override fun getDocument(input: YoudaoTranslation): YoudaoWebTranslationDocument? {
val webTranslations = input.webExplains
?.mapNotNull { (key, values) ->
if (key == null || key.isBlank() || values == null || values.isEmpty()) {
val filteredValues = values
?.filterNotNull()
?.filter { it.isNotBlank() }
?.toTypedArray()
if (key.isNullOrBlank() || filteredValues.isNullOrEmpty()) {
null
} else {
WebTranslation(key.trim(), values)
WebTranslation(key.trim(), filteredValues)
}
}
?.takeIf { it.isNotEmpty() }
?: return null

// q: 请翻译为英文:修复指定非空参数为空的问题
// a: Fix the problem of specifying a non-null parameter as null

return YoudaoWebTranslationDocument(webTranslations)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ class GoogleTTSPlayer(
indicator.apply {
checkCanceled()
fraction = 0.0
isIndeterminate = false
isIndeterminate = duration <= 0
text = message("tts.progress.playing")
}

Expand All @@ -169,8 +169,10 @@ class GoogleTTSPlayer(
if (bytesRead != -1) {
write(data, 0, bytesRead)

val currentTime = properties()["mp3.position.microseconds"] as Long / 1000
indicator.fraction = currentTime.toDouble() / duration.toDouble()
if (duration > 0) {
val currentTime = properties()["mp3.position.microseconds"] as Long / 1000
indicator.fraction = currentTime.toDouble() / duration.toDouble()
}
} else {
indicator.fraction = 1.0
break
Expand Down Expand Up @@ -213,7 +215,7 @@ class GoogleTTSPlayer(
return try {
round(Bitstream(this).readFrame().total_ms(dataLength))
} catch (e: Throwable) {
LOGGER.error(e)
LOGGER.warn("Failed to get audio duration.", e)
0
} finally {
reset()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ class TranslationDialog(
private var ignoreLanguageEvent: Boolean = false
private var ignoreInputEvent: Boolean = false

// If user selects a specific target language, the value is true
// If the user selects a specific target language, the value is true
private var unequivocalTargetLang: Boolean by Delegates.observable(false) { _, _, _ ->
updateLightningLabel()
}
Expand Down Expand Up @@ -227,10 +227,11 @@ class TranslationDialog(
addMouseMotionListener(it)
}
}
val glassPane = rootPane.glassPane as IdeGlassPane

val glassPane = rootPane.glassPane as IdeGlassPane
translationPanel.minimumSize = JBDimension(MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT)
val resizeListener = object : WindowResizeListener(rootPane, JBUI.insets(6), null) {
var myCursor: Cursor? = null
private var myCursor: Cursor? = null

override fun setCursor(content: Component, cursor: Cursor) {
if (myCursor !== cursor || myCursor !== Cursor.getDefaultCursor()) {
Expand Down Expand Up @@ -831,5 +832,7 @@ class TranslationDialog(
companion object {
private const val FONT_SIZE_DEFAULT = 14
private const val FONT_SIZE_PHONETIC = 12
private const val MIN_WINDOW_WIDTH = 450
private const val MIN_WINDOW_HEIGHT = 200
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,10 @@ class TranslationDialogUiImpl(uiProvider: TranslationDialogUiProvider) : Transla

override fun initFonts(pair: UI.FontPair) {
pair.let { (primaryFont, phoneticFont) ->
val labelsFont = primaryFont.deriveFont(JBFont.label().size.toFloat())
sourceLangComboBox.font = labelsFont
targetLangComboBox.font = labelsFont
detectedLanguageLabel.font = labelsFont
val labelFont = primaryFont.deriveFont(JBFont.label().size.toFloat())
sourceLangComboBox.font = labelFont
targetLangComboBox.font = labelFont
detectedLanguageLabel.font = labelFont
inputTextArea.font = primaryFont
translationTextArea.font = primaryFont
srcTransliterationLabel.font = phoneticFont
Expand Down Expand Up @@ -177,7 +177,6 @@ class TranslationDialogUiImpl(uiProvider: TranslationDialogUiProvider) : Transla
}

private fun layoutMainPanel(): JComponent {

val centerPanel = JPanel(UI.migLayout()).apply {
val leftPanel = JPanel(UI.migLayout()).apply {
background = inputTextArea.background
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ class UpdateManager : BaseStartupActivity() {

private class GetStartedAction :
DumbAwareAction(message("action.GetStartedAction.text"), null, AllIcons.General.Web) {
override fun actionPerformed(e: AnActionEvent) = BrowserUtil.browse(WebPages.getStarted())
override fun actionPerformed(e: AnActionEvent) = BrowserUtil.browse(WebPages.docs())
}


Expand Down
3 changes: 1 addition & 2 deletions src/main/kotlin/cn/yiiguxing/plugin/translate/util/IO.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cn.yiiguxing.plugin.translate.util

import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.io.outputStream
import java.io.OutputStream
import java.math.BigInteger
import java.nio.file.AtomicMoveNotSupportedException
Expand All @@ -21,7 +20,7 @@ private fun randomToken(): String {

fun Path.writeSafe(outConsumer: (OutputStream) -> Unit): Path {
val tempFile = parent.resolve("${fileName}.${randomToken()}.tmp")
tempFile.outputStream().use(outConsumer)
Files.newOutputStream(tempFile).use(outConsumer)
try {
Files.move(tempFile, this, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
} catch (e: AtomicMoveNotSupportedException) {
Expand Down
1 change: 0 additions & 1 deletion src/main/resources/messages/TranslationBundle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,6 @@ openai.settings.dialog.hint=<html>The OpenAI API uses API keys for authenticatio
to retrieve the API key.</html>
google.settings.dialog.title=Google Translate Settings
google.settings.dialog.label.server=Server\:
google.settings.dialog.tip.enter.server.url=Enter the server URL
google.settings.dialog.error.invalid.server.url=Invalid server URL
google.settings.test.task.title=Test Google Translate Server...
google.settings.test.result.title=Google Translate Server
Expand Down
Loading

0 comments on commit e367589

Please sign in to comment.