Skip to content

Commit

Permalink
perf: 终端相关优化
Browse files Browse the repository at this point in the history
0. 终端的颜色显示模式和样式加入配置文件
1. 使得在终端不可用的情况下程序可以继续执行
  • Loading branch information
nullaqua committed Aug 4, 2024
1 parent 9e1ab7d commit 331f9d1
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 24 deletions.
17 changes: 15 additions & 2 deletions src/main/kotlin/subit/config/LoggerConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import net.mamoe.yamlkt.Comment
import subit.console.ColorDisplayMode
import subit.console.Console
import subit.logger.ForumLogger
import java.util.logging.Level
import java.util.logging.LogRecord
Expand All @@ -20,10 +22,15 @@ data class LoggerConfig(
val levelName: String,
@Comment("是否在日志中显示日志名称")
val showLoggerName: Boolean,
@Comment("日志的颜色样式, 可选值: RGB, SIMPLE, NONE")
val color: ColorDisplayMode,
@Comment("是否在日志中使用样式(加粗, 斜体, 下划线等)")
val effect: Boolean
)
{
@Transient
val level: Level = Level.parse(levelName)

@Transient
val pattern: Pattern = Pattern.compile(matchers.joinToString("|") { "($it)" })

Expand All @@ -32,6 +39,12 @@ data class LoggerConfig(

var loggerConfig: LoggerConfig by config(
"logger.yml",
LoggerConfig(listOf(), true, "INFO", false),
{ _, new -> ForumLogger.globalLogger.logger.setLevel(new.level) }
LoggerConfig(listOf(), true, "INFO", false, ColorDisplayMode.RGB, true),
{ _, new ->
ForumLogger.globalLogger.logger.setLevel(new.level)
Console.ansiEffectMode =
if (new.effect) subit.console.EffectDisplayMode.ON
else subit.console.EffectDisplayMode.OFF
Console.ansiColorMode = new.color
}
)
73 changes: 53 additions & 20 deletions src/main/kotlin/subit/console/Console.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import org.jline.widget.AutopairWidgets
import org.jline.widget.AutosuggestionWidgets
import subit.console.command.CommandSet
import subit.console.command.CommandSet.err
import subit.logger.ForumLogger
import subit.logger.ForumLogger.nativeOut
import subit.utils.FileUtils
import subit.utils.Power
import sun.misc.Signal
Expand All @@ -23,12 +23,13 @@ object Console
/**
* 终端对象
*/
private val terminal: Terminal = TerminalBuilder.builder().jansi(true).build()
private val terminal: Terminal?

/**
* 颜色显示模式
*/
var ansiColorMode: ColorDisplayMode = ColorDisplayMode.RGB

/**
* 效果显示模式
*/
Expand All @@ -37,29 +38,51 @@ object Console
/**
* 命令行读取器,命令补全为[CommandSet.CommandCompleter],命令历史保存在[historyFile]中
*/
val lineReader: LineReader = LineReaderBuilder.builder()
.terminal(terminal)
.completer(CommandSet.CommandCompleter)
.variable(LineReader.HISTORY_FILE, historyFile)
.build()
val lineReader: LineReader?

init
{
Signal.handle(Signal("INT")) { onUserInterrupt() }
var terminal: Terminal? = null
var lineReader: LineReader? = null
try
{
terminal = TerminalBuilder.builder().jansi(true).build()
if (terminal.type == "dumb")
{
terminal.close()
terminal = null
throw IllegalStateException("Unsupported terminal type: dumb")
}
lineReader = LineReaderBuilder.builder()
.terminal(terminal)
.completer(CommandSet.CommandCompleter)
.variable(LineReader.HISTORY_FILE, historyFile)
.build()

// 自动配对(小括号/中括号/大括号/引号等)
val autopairWidgets = AutopairWidgets(lineReader, true)
autopairWidgets.enable()
// 根据历史记录建议
val autosuggestionWidgets = AutosuggestionWidgets(lineReader)
autosuggestionWidgets.enable()
// 自动配对(小括号/中括号/大括号/引号等)
val autopairWidgets = AutopairWidgets(lineReader, true)
autopairWidgets.enable()
// 根据历史记录建议
val autosuggestionWidgets = AutosuggestionWidgets(lineReader)
autosuggestionWidgets.enable()
}
catch (e: Throwable)
{
terminal?.close()
err.println("Failed to initialize terminal, will use system console instead.")
}
this.terminal = terminal
this.lineReader = lineReader
}

fun onUserInterrupt()
{
err.println("You might have pressed Ctrl+C or performed another operation to stop the server.")
err.println("This method is feasible but not recommended," +
" it should only be used when a command-line system error prevents the program from closing.")
err.println(
"This method is feasible but not recommended, " +
"it should only be used when a command-line system error prevents the program from closing."
)
err.println("If you want to stop the server, please use the \"stop\" command.")
Power.shutdown(0, "User interrupt")
}
Expand All @@ -68,20 +91,30 @@ object Console
* 命令历史文件
*/
private val historyFile: File
get() = File(FileUtils.dataFolder,"command_history.txt")
get() = File(FileUtils.dataFolder, "command_history.txt")

/**
* 在终端上打印一行, 会自动换行并下移命令提升符和已经输入的命令
*/
fun println(o: Any) = if (lineReader.isReading) lineReader.printAbove("\r$o") else terminal.writer().println(o)
fun println(o: Any)
{
if (lineReader != null)
{
if (lineReader.isReading)
lineReader.printAbove("\r$o")
else
terminal!!.writer().println(o)
}
else nativeOut.println(o)
}

/**
* 清空终端
*/
fun clear()
{
ForumLogger.nativeOut.print("\u001bc")
lineReader as LineReaderImpl
if (lineReader.isReading) lineReader.redrawLine()
nativeOut.print("\u001bc")
if (lineReader is LineReaderImpl && lineReader.isReading)
lineReader.redrawLine()
}
}
3 changes: 2 additions & 1 deletion src/main/kotlin/subit/console/command/CommandSet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ object CommandSet: TreeCommand(

fun Application.startCommandThread() = CoroutineScope(Dispatchers.IO).launch()
{
if (Console.lineReader == null) return@launch
var line: String? = null
while (true) try
{
Expand Down Expand Up @@ -115,7 +116,7 @@ object CommandSet: TreeCommand(
{
if (b == '\n'.code)
{
Console.println("${SimpleAnsiColor.PURPLE.bright()}[COMMAND]$style$level$RESET $arrayOutputStream")
Console.println("${SimpleAnsiColor.PURPLE.bright()}[COMMAND]$style$level$RESET $arrayOutputStream$RESET")
arrayOutputStream.reset()
}
else
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/subit/logger/ForumLogger.kt
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ object ToFileHandler: Handler()

private fun check()
{
if ((cnt ushr 10) > 0) new()
if ((cnt ushr 10) != 0) new()
}

private fun append(lines: List<String>) = synchronized(this)
Expand Down

0 comments on commit 331f9d1

Please sign in to comment.