Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix UTF-8 console input/output on Windows #11557

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/crystal/system/win32/file_descriptor.cr
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
require "c/io"
require "c/consoleapi"
require "c/consoleapi2"
require "c/winnls"

module Crystal::System::FileDescriptor
@volatile_fd : Atomic(LibC::Int)
Expand Down Expand Up @@ -184,3 +186,16 @@ module Crystal::System::FileDescriptor
io
end
end

# Enable UTF-8 console I/O for the duration of program execution
if LibC.IsValidCodePage(LibC::CP_UTF8) != 0
old_input_cp = LibC.GetConsoleCP
if LibC.SetConsoleCP(LibC::CP_UTF8) != 0
at_exit { LibC.SetConsoleCP(old_input_cp) }
end

old_output_cp = LibC.GetConsoleOutputCP
if LibC.SetConsoleOutputCP(LibC::CP_UTF8) != 0
at_exit { LibC.SetConsoleOutputCP(old_output_cp) }
end
end
3 changes: 3 additions & 0 deletions src/lib_c/x86_64-windows-msvc/c/consoleapi.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ require "c/winnt"

lib LibC
fun GetConsoleMode(hConsoleHandle : HANDLE, lpMode : DWORD*) : BOOL

fun GetConsoleCP : DWORD
fun GetConsoleOutputCP : DWORD
end
4 changes: 4 additions & 0 deletions src/lib_c/x86_64-windows-msvc/c/consoleapi2.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
lib LibC
fun SetConsoleCP(wCodePageID : DWORD) : BOOL
fun SetConsoleOutputCP(wCodePageID : DWORD) : BOOL
end
5 changes: 5 additions & 0 deletions src/lib_c/x86_64-windows-msvc/c/winnls.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
lib LibC
CP_UTF8 = 65001

fun IsValidCodePage(codePage : DWORD) : BOOL
end