Translation of game comments
When a game's comments are in another language, ChessPenguin offers to translate them into the reader's: with the ChatGPT Plus/Pro subscription (Sign in with ChatGPT: OAuth with PKCE in the browser, a loopback callback, tokens refreshed one at a time), or an OpenAI-compatible API key (DeepSeek, OpenAI, Gemini, a model on this computer with Ollama or LM Studio, another address). After the first consent, games in other languages are translated as they are opened; [Original | Translation] (Ctrl+Shift+T) switches back. Only comment text is sent; the model gets strict instructions and a glossary, and every answer must keep the moves and squares of the original, or the comment stays in the original with a mark. Translations are never written to the PGN; a cache keeps them per language. Keys and tokens live in a 0600 file apart from the settings. Settings › Translation holds the target language, when to translate, the connection, permissions and the cache. Also: the monospace font and three glyphs of Noto Sans Math are text fallbacks, so arrows and the evaluation signs ⩲ ⩱ ⌓ no longer show as boxes. Reviewed by the designer and the tester agents (two rounds). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
cbf76d6909
commit
1d901b61ff
21 changed files with 7353 additions and 19 deletions
|
|
@ -33,6 +33,10 @@ zip = { version = "9.0.5", default-features = false, features = ["deflate-flate2
|
|||
|
||||
# The system language for the first start.
|
||||
sys-locale = "0.3"
|
||||
whatlang = "0.18.0"
|
||||
getrandom = "0.3"
|
||||
base64 = "0.22"
|
||||
form_urlencoded = "1"
|
||||
|
||||
[build-dependencies]
|
||||
winresource = "0.1"
|
||||
|
|
|
|||
BIN
apps/desktop/assets/fonts/NotoSansMath-nag.ttf
Normal file
BIN
apps/desktop/assets/fonts/NotoSansMath-nag.ttf
Normal file
Binary file not shown.
95
apps/desktop/assets/fonts/OFL.txt
Normal file
95
apps/desktop/assets/fonts/OFL.txt
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
NotoSansMath-nag.ttf: Noto Sans Math (https://github.com/notofonts/math), Copyright 2022 Google LLC,
|
||||
cut down by ChessPenguin to three glyphs (U+2313, U+2A71, U+2A72) used for move evaluations.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License,
|
||||
Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font
|
||||
creation efforts of academic and linguistic communities, and to
|
||||
provide a free and open framework in which fonts may be shared and
|
||||
improved in partnership with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply to
|
||||
any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software
|
||||
components as distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to,
|
||||
deleting, or substituting -- in part or in whole -- any of the
|
||||
components of the Original Version, by changing formats or by porting
|
||||
the Font Software to a new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed,
|
||||
modify, redistribute, and sell modified and unmodified copies of the
|
||||
Font Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components, in
|
||||
Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the
|
||||
corresponding Copyright Holder. This restriction only applies to the
|
||||
primary font name as presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created using
|
||||
the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
|
|
@ -55,6 +55,8 @@ pub struct App {
|
|||
/// Lichess / Chess.com: which answered at start, and the download window.
|
||||
online_probe: crate::online::Probe,
|
||||
online: crate::online_ui::OnlineDialog,
|
||||
/// Translating comments: the setup and consent windows, the ChatGPT sign-in.
|
||||
translation: crate::translate_ui::Hub,
|
||||
/// A position to find in a database once the game is closed.
|
||||
find_after_close: Option<(PathBuf, shakmaty::Chess, Vec<shakmaty::Move>, bool)>,
|
||||
/// Games left for one opened from the reference tab ("⬅ Back to …"), kept as they
|
||||
|
|
@ -180,6 +182,7 @@ impl App {
|
|||
offer_hook_done: false,
|
||||
online_probe: crate::online::Probe::start(ctx),
|
||||
online: crate::online_ui::OnlineDialog::from_env(),
|
||||
translation: Default::default(),
|
||||
allow_quit: false,
|
||||
applied_dark: None,
|
||||
debug: DebugStartup::from_env(),
|
||||
|
|
@ -202,9 +205,15 @@ impl App {
|
|||
match tab.as_str() {
|
||||
"board" => self.settings_ui.tab = Tab::Board,
|
||||
"about" => self.settings_ui.tab = Tab::About,
|
||||
"translation" => self.settings_ui.tab = Tab::Translation,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// `CP_TRANSLATE_SETUP=1`: the "How to translate?" window (`=key`: with an API key chosen).
|
||||
if let Ok(v) = std::env::var("CP_TRANSLATE_SETUP") {
|
||||
self.translation
|
||||
.debug_open_setup(&self.settings.translation, v == "key");
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
|
|
@ -811,6 +820,7 @@ impl eframe::App for App {
|
|||
&mut self.settings,
|
||||
&mut self.analysis,
|
||||
&mut self.reference,
|
||||
&mut self.translation,
|
||||
input_enabled,
|
||||
);
|
||||
self.reference_tab = game.reference_tab();
|
||||
|
|
@ -824,8 +834,9 @@ impl eframe::App for App {
|
|||
}
|
||||
GameAction::ReferenceLoad(p) => self.library.load(&p, &ctx),
|
||||
GameAction::OpenGame(path, index, at) => {
|
||||
if let Some(prev) = self.game.take() {
|
||||
if let Some(mut prev) = self.game.take() {
|
||||
let title = prev.title();
|
||||
prev.suspend();
|
||||
self.previous_games.push(prev);
|
||||
self.open_game(&ctx, path, index, Some(at));
|
||||
match &mut self.game {
|
||||
|
|
@ -875,6 +886,10 @@ impl eframe::App for App {
|
|||
self.settings_ui.tab = Tab::Engines;
|
||||
}
|
||||
GameAction::OpenSettings => self.settings_ui.open = !self.settings_ui.open,
|
||||
GameAction::OpenTranslationSettings => {
|
||||
self.settings_ui.open = true;
|
||||
self.settings_ui.tab = Tab::Translation;
|
||||
}
|
||||
GameAction::Toast(m) => self.toast(&ctx, m),
|
||||
GameAction::PauseLive => {
|
||||
if self.analysis.is_on() {
|
||||
|
|
@ -995,7 +1010,15 @@ impl eframe::App for App {
|
|||
};
|
||||
|
||||
self.settings_ui.download = self.engine_offer.stage();
|
||||
let (actions, changed) = self.settings_ui.show(&ctx, &mut self.settings);
|
||||
self.settings_dirty |= self.translation.poll(&ctx, &mut self.settings);
|
||||
self.settings_dirty |= self.translation.windows(&ctx, &mut self.settings);
|
||||
if std::mem::take(&mut self.translation.open_settings) {
|
||||
self.settings_ui.open = true;
|
||||
self.settings_ui.tab = Tab::Translation;
|
||||
}
|
||||
let (actions, changed) =
|
||||
self.settings_ui
|
||||
.show(&ctx, &mut self.settings, &mut self.translation);
|
||||
self.settings_dirty |= changed;
|
||||
for a in actions {
|
||||
match a {
|
||||
|
|
|
|||
|
|
@ -153,6 +153,31 @@ pub fn install(ctx: &egui::Context) {
|
|||
for (name, bytes) in TEXTURES {
|
||||
ctx.include_bytes(format!("bytes://boards/{name}"), *bytes);
|
||||
}
|
||||
// Arrows (→ ⇄ ↔) are only in egui's monospace font, and three evaluation signs
|
||||
// (⩲ ⩱ ⌓) in none: the last fallbacks of the text.
|
||||
let mut fonts = egui::FontDefinitions::default();
|
||||
fonts.font_data.insert(
|
||||
"nag-symbols".into(),
|
||||
std::sync::Arc::new(egui::FontData::from_static(include_bytes!(
|
||||
"../assets/fonts/NotoSansMath-nag.ttf"
|
||||
))),
|
||||
);
|
||||
let mono = fonts
|
||||
.families
|
||||
.get(&egui::FontFamily::Monospace)
|
||||
.and_then(|f| f.first())
|
||||
.cloned();
|
||||
for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] {
|
||||
if let Some(list) = fonts.families.get_mut(&family) {
|
||||
if let Some(m) = &mono
|
||||
&& !list.contains(m)
|
||||
{
|
||||
list.push(m.clone());
|
||||
}
|
||||
list.push("nag-symbols".into());
|
||||
}
|
||||
}
|
||||
ctx.set_fonts(fonts);
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
|
|
|
|||
765
apps/desktop/src/chatgpt.rs
Normal file
765
apps/desktop/src/chatgpt.rs
Normal file
|
|
@ -0,0 +1,765 @@
|
|||
//! Sign in with ChatGPT: requests paid from the user's ChatGPT plan
|
||||
//! (https://developers.openai.com/siwc/token-sharing-open-source).
|
||||
//!
|
||||
//! OAuth with PKCE in the system browser and a loopback listener on 127.0.0.1; the
|
||||
//! client is registered on the first sign-in (`dynamic_agent_client`), the issued client
|
||||
//! id and this installation's host id are kept in the settings, the tokens beside them
|
||||
//! in `credentials.json`. Inference: the Responses API, streamed, not stored.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write as _};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::translate::{Failure, agent, update_credentials, with_waits};
|
||||
|
||||
const AUTHORIZE: &str = "https://auth.openai.com/api/accounts/authorize";
|
||||
const TOKEN: &str = "https://auth.openai.com/api/accounts/oauth/token";
|
||||
const DISCOVERY: &str = "https://auth.openai.com/.well-known/openid-configuration";
|
||||
const API: &str = "https://api.openai.com/v1";
|
||||
const RESOURCE: &str = "https://api.openai.com/v1";
|
||||
const SCOPES: &str =
|
||||
"openid profile email offline_access resource.invoke chatgpt.tokens.use.direct";
|
||||
/// The scope that lets requests use the plan.
|
||||
const PLAN_SCOPE: &str = "chatgpt.tokens.use.direct";
|
||||
const CALLBACK_PATH: &str = "/auth/callback";
|
||||
/// Ports tried for the callback (any port works; the path must stay the same).
|
||||
const PORTS: [u16; 4] = [1455, 1456, 1457, 0];
|
||||
/// How long the browser has for the sign-in.
|
||||
const SIGN_IN_TIME: Duration = Duration::from_secs(10 * 60);
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
|
||||
pub struct Tokens {
|
||||
pub access: String,
|
||||
pub refresh: String,
|
||||
/// Unix seconds.
|
||||
pub expires: u64,
|
||||
pub scope: String,
|
||||
pub client_id: String,
|
||||
}
|
||||
|
||||
impl Tokens {
|
||||
/// The plan may be used (the user granted it at consent).
|
||||
pub fn plan(&self) -> bool {
|
||||
self.scope.split_whitespace().any(|s| s == PLAN_SCOPE)
|
||||
}
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs())
|
||||
}
|
||||
|
||||
fn random_bytes<const N: usize>() -> [u8; N] {
|
||||
let mut b = [0u8; N];
|
||||
// No randomness is a broken system; a weaker fallback still differs per attempt.
|
||||
if getrandom::fill(&mut b).is_err() {
|
||||
let t = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_nanos());
|
||||
let h = Sha256::digest(t.to_le_bytes());
|
||||
for (i, x) in b.iter_mut().enumerate() {
|
||||
*x = h[i % h.len()];
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn random_text() -> String {
|
||||
URL_SAFE_NO_PAD.encode(random_bytes::<32>())
|
||||
}
|
||||
|
||||
/// A new installation id (`urn:uuid:` with a random UUID v4).
|
||||
pub fn new_host_id() -> String {
|
||||
let mut b = random_bytes::<16>();
|
||||
b[6] = (b[6] & 0x0f) | 0x40;
|
||||
b[8] = (b[8] & 0x3f) | 0x80;
|
||||
let h: String = b.iter().map(|x| format!("{x:02x}")).collect();
|
||||
format!(
|
||||
"urn:uuid:{}-{}-{}-{}-{}",
|
||||
&h[0..8],
|
||||
&h[8..12],
|
||||
&h[12..16],
|
||||
&h[16..20],
|
||||
&h[20..32]
|
||||
)
|
||||
}
|
||||
|
||||
fn form(pairs: &[(&str, &str)]) -> String {
|
||||
let mut s = form_urlencoded::Serializer::new(String::new());
|
||||
for (k, v) in pairs {
|
||||
s.append_pair(k, v);
|
||||
}
|
||||
s.finish()
|
||||
}
|
||||
|
||||
/// The `email` claim of an ID token (not verified: shown only, never trusted).
|
||||
fn email_of(id_token: &str) -> Option<String> {
|
||||
let payload = id_token.split('.').nth(1)?;
|
||||
let bytes = URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?;
|
||||
let v: Value = serde_json::from_slice(&bytes).ok()?;
|
||||
v.get("email").and_then(Value::as_str).map(str::to_owned)
|
||||
}
|
||||
|
||||
fn nonce_of(id_token: &str) -> Option<String> {
|
||||
let payload = id_token.split('.').nth(1)?;
|
||||
let bytes = URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?;
|
||||
let v: Value = serde_json::from_slice(&bytes).ok()?;
|
||||
v.get("nonce").and_then(Value::as_str).map(str::to_owned)
|
||||
}
|
||||
|
||||
// --- Sign-in -------------------------------------------------------------------------------
|
||||
|
||||
/// How a sign-in ended.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum SignedIn {
|
||||
/// Signed in with the plan usable: the account, the issued client id.
|
||||
Ok {
|
||||
account: String,
|
||||
client_id: String,
|
||||
},
|
||||
/// Signed in, but the plan usage was not granted at consent.
|
||||
NoPlan {
|
||||
account: String,
|
||||
client_id: String,
|
||||
},
|
||||
/// The user declined in the browser.
|
||||
Declined,
|
||||
/// The browser did not come back in time.
|
||||
TimedOut,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
pub struct SignIn {
|
||||
/// The address to open (also offered for copying when no browser opens).
|
||||
pub url: String,
|
||||
rx: Receiver<SignedIn>,
|
||||
cancel: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl SignIn {
|
||||
/// Starts listening for the callback and returns the address to open in the browser.
|
||||
pub fn start(ctx: &egui::Context, host_id: &str, client_id: &str) -> Result<SignIn, String> {
|
||||
let listener = PORTS
|
||||
.iter()
|
||||
.find_map(|p| TcpListener::bind(("127.0.0.1", *p)).ok())
|
||||
.ok_or_else(|| "no free port on 127.0.0.1".to_owned())?;
|
||||
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
|
||||
listener.set_nonblocking(true).map_err(|e| e.to_string())?;
|
||||
let redirect = format!("http://127.0.0.1:{port}{CALLBACK_PATH}");
|
||||
let verifier = random_text();
|
||||
let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
|
||||
let state = random_text();
|
||||
let nonce = random_text();
|
||||
let first = client_id.is_empty();
|
||||
let client = if first {
|
||||
"dynamic_agent_client"
|
||||
} else {
|
||||
client_id
|
||||
};
|
||||
let mut params = vec![
|
||||
("client_id", client),
|
||||
("ext_agent_host_id", host_id),
|
||||
("response_type", "code"),
|
||||
("redirect_uri", redirect.as_str()),
|
||||
("scope", SCOPES),
|
||||
("resource", RESOURCE),
|
||||
("state", state.as_str()),
|
||||
("nonce", nonce.as_str()),
|
||||
("code_challenge_method", "S256"),
|
||||
("code_challenge", challenge.as_str()),
|
||||
];
|
||||
if first {
|
||||
params.push(("agent_name_hint", "ChessPenguin"));
|
||||
}
|
||||
let url = format!("{AUTHORIZE}?{}", form(¶ms));
|
||||
let (tx, rx) = channel();
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let c = cancel.clone();
|
||||
let ctx = ctx.clone();
|
||||
let client = client.to_owned();
|
||||
std::thread::Builder::new()
|
||||
.name("chatgpt-sign-in".into())
|
||||
.spawn(move || {
|
||||
let r = wait_for_callback(&listener, &c, &state).and_then(|(code, issued)| {
|
||||
let client = issued.unwrap_or(client);
|
||||
exchange(&code, &verifier, &redirect, &client, &nonce)
|
||||
});
|
||||
let _ = tx.send(r.unwrap_or_else(|e| e));
|
||||
ctx.request_repaint();
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(SignIn { url, rx, cancel })
|
||||
}
|
||||
|
||||
pub fn poll(&self) -> Option<SignedIn> {
|
||||
self.rx.try_recv().ok()
|
||||
}
|
||||
|
||||
pub fn cancel(&self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SignIn {
|
||||
fn drop(&mut self) {
|
||||
self.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// The page the browser tab shows after the sign-in.
|
||||
fn page(ok: bool) -> String {
|
||||
let (title, text) = if ok {
|
||||
(
|
||||
crate::i18n::tr("✓ You are signed in to ChatGPT"),
|
||||
crate::i18n::tr(
|
||||
"Go back to ChessPenguin — the translation goes on there. You can close this tab.",
|
||||
),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
crate::i18n::tr("Sign-in could not be finished"),
|
||||
crate::i18n::tr("Go back to ChessPenguin and try again."),
|
||||
)
|
||||
};
|
||||
format!(
|
||||
"<!doctype html><html><head><meta charset=\"utf-8\"><title>ChessPenguin</title>\
|
||||
<style>body{{font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem;color:#222}}\
|
||||
@media (prefers-color-scheme:dark){{body{{background:#1b1b1b;color:#ddd}}}}</style></head>\
|
||||
<body><h1>{title}</h1><p>{text}</p></body></html>"
|
||||
)
|
||||
}
|
||||
|
||||
fn reply(stream: &mut TcpStream, status: &str, body: &str) {
|
||||
let _ = write!(
|
||||
stream,
|
||||
"HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
}
|
||||
|
||||
/// Waits for the browser to come back to the callback: (code, issued client id).
|
||||
fn wait_for_callback(
|
||||
listener: &TcpListener,
|
||||
cancel: &AtomicBool,
|
||||
state: &str,
|
||||
) -> Result<(String, Option<String>), SignedIn> {
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err(SignedIn::Failed("cancelled".into()));
|
||||
}
|
||||
if start.elapsed() > SIGN_IN_TIME {
|
||||
return Err(SignedIn::TimedOut);
|
||||
}
|
||||
let mut stream = match listener.accept() {
|
||||
Ok((s, _)) => s,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(SignedIn::Failed(e.to_string())),
|
||||
};
|
||||
let _ = stream.set_nonblocking(false);
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
|
||||
let mut line = String::new();
|
||||
if BufReader::new(&stream).read_line(&mut line).is_err() {
|
||||
continue;
|
||||
}
|
||||
// "GET /auth/callback?code=…&state=… HTTP/1.1"
|
||||
let target = line.split_whitespace().nth(1).unwrap_or("");
|
||||
let (path, query) = target.split_once('?').unwrap_or((target, ""));
|
||||
if path != CALLBACK_PATH {
|
||||
reply(&mut stream, "404 Not Found", "");
|
||||
continue;
|
||||
}
|
||||
let q: std::collections::HashMap<String, String> = form_urlencoded::parse(query.as_bytes())
|
||||
.into_owned()
|
||||
.collect();
|
||||
if q.get("state").map(String::as_str) != Some(state) {
|
||||
reply(&mut stream, "400 Bad Request", &page(false));
|
||||
continue;
|
||||
}
|
||||
if let Some(err) = q.get("error") {
|
||||
reply(&mut stream, "200 OK", &page(false));
|
||||
return Err(if err == "access_denied" {
|
||||
SignedIn::Declined
|
||||
} else {
|
||||
SignedIn::Failed(format!(
|
||||
"{err}: {}",
|
||||
q.get("error_description").map_or("", |s| s.as_str())
|
||||
))
|
||||
});
|
||||
}
|
||||
let Some(code) = q.get("code").cloned() else {
|
||||
reply(&mut stream, "200 OK", &page(false));
|
||||
return Err(SignedIn::Failed("no code in the callback".into()));
|
||||
};
|
||||
reply(&mut stream, "200 OK", &page(true));
|
||||
return Ok((code, q.get("client_id").cloned()));
|
||||
}
|
||||
}
|
||||
|
||||
fn token_request(body: &str) -> Result<Value, (u16, String)> {
|
||||
let mut resp = agent(Duration::from_secs(30))
|
||||
.post(TOKEN)
|
||||
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.send(body)
|
||||
.map_err(|e| (0, e.to_string()))?;
|
||||
let status = resp.status().as_u16();
|
||||
let text = resp.body_mut().read_to_string().unwrap_or_default();
|
||||
if status != 200 {
|
||||
return Err((status, text));
|
||||
}
|
||||
serde_json::from_str(&text).map_err(|e| (status, e.to_string()))
|
||||
}
|
||||
|
||||
fn tokens_from(v: &Value, client_id: &str, old_refresh: &str) -> Tokens {
|
||||
let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_owned();
|
||||
let refresh = s("refresh_token");
|
||||
Tokens {
|
||||
access: s("access_token"),
|
||||
refresh: if refresh.is_empty() {
|
||||
old_refresh.to_owned()
|
||||
} else {
|
||||
refresh
|
||||
},
|
||||
expires: now() + v.get("expires_in").and_then(Value::as_u64).unwrap_or(3600),
|
||||
scope: s("scope"),
|
||||
client_id: client_id.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn exchange(
|
||||
code: &str,
|
||||
verifier: &str,
|
||||
redirect: &str,
|
||||
client_id: &str,
|
||||
nonce: &str,
|
||||
) -> Result<SignedIn, SignedIn> {
|
||||
let body = form(&[
|
||||
("grant_type", "authorization_code"),
|
||||
("client_id", client_id),
|
||||
("code", code),
|
||||
("code_verifier", verifier),
|
||||
("redirect_uri", redirect),
|
||||
("resource", RESOURCE),
|
||||
]);
|
||||
let v = token_request(&body)
|
||||
.map_err(|(status, e)| SignedIn::Failed(format!("token exchange: {status} {e}")))?;
|
||||
let id_token = v.get("id_token").and_then(Value::as_str).unwrap_or("");
|
||||
if let Some(n) = nonce_of(id_token)
|
||||
&& n != nonce
|
||||
{
|
||||
return Err(SignedIn::Failed(
|
||||
"the sign-in answer is not for this request".into(),
|
||||
));
|
||||
}
|
||||
let tokens = tokens_from(&v, client_id, "");
|
||||
if tokens.access.is_empty() {
|
||||
return Err(SignedIn::Failed("no access token".into()));
|
||||
}
|
||||
let account = email_of(id_token).unwrap_or_default();
|
||||
let plan = tokens.plan();
|
||||
update_credentials(|c| c.chatgpt = Some(tokens));
|
||||
let client_id = client_id.to_owned();
|
||||
Ok(if plan {
|
||||
SignedIn::Ok { account, client_id }
|
||||
} else {
|
||||
SignedIn::NoPlan { account, client_id }
|
||||
})
|
||||
}
|
||||
|
||||
/// Refreshes are one at a time: the refresh token rotates.
|
||||
static REFRESH: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// A valid access token, refreshed when it is about to expire.
|
||||
fn access_token() -> Result<String, Failure> {
|
||||
let _one = REFRESH.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(t) = crate::translate::credentials().chatgpt else {
|
||||
return Err(Failure::SignedOut);
|
||||
};
|
||||
if !t.plan() {
|
||||
return Err(Failure::NotEligible("plan usage not granted".into()));
|
||||
}
|
||||
if t.expires > now() + 120 {
|
||||
return Ok(t.access);
|
||||
}
|
||||
refresh(&t)
|
||||
}
|
||||
|
||||
fn refresh(t: &Tokens) -> Result<String, Failure> {
|
||||
let body = form(&[
|
||||
("grant_type", "refresh_token"),
|
||||
("client_id", &t.client_id),
|
||||
("refresh_token", &t.refresh),
|
||||
("resource", RESOURCE),
|
||||
]);
|
||||
match token_request(&body) {
|
||||
Ok(v) => {
|
||||
let new = tokens_from(&v, &t.client_id, &t.refresh);
|
||||
let access = new.access.clone();
|
||||
// The scope may be omitted on refresh: the grant stays.
|
||||
let new = Tokens {
|
||||
scope: if new.scope.is_empty() {
|
||||
t.scope.clone()
|
||||
} else {
|
||||
new.scope
|
||||
},
|
||||
..new
|
||||
};
|
||||
// Signed out meanwhile: the new tokens are not kept.
|
||||
update_credentials(|c| {
|
||||
if c.chatgpt.as_ref().is_some_and(|x| x.refresh == t.refresh) {
|
||||
c.chatgpt = Some(new);
|
||||
}
|
||||
});
|
||||
Ok(access)
|
||||
}
|
||||
Err((0, e)) => Err(Failure::Offline(e)),
|
||||
Err((status, body)) => {
|
||||
let terminal = [
|
||||
"invalid_grant",
|
||||
"invalid_refresh_token",
|
||||
"token_expired",
|
||||
"refresh_token_expired",
|
||||
"refresh_token_invalidated",
|
||||
"refresh_token_reused",
|
||||
];
|
||||
if (400..500).contains(&status) && terminal.iter().any(|c| body.contains(c)) {
|
||||
// Only this sign-in is over (not a newer one made meanwhile).
|
||||
update_credentials(|c| {
|
||||
if c.chatgpt.as_ref().is_some_and(|x| x.refresh == t.refresh) {
|
||||
c.chatgpt = None;
|
||||
}
|
||||
});
|
||||
Err(Failure::SignedOut)
|
||||
} else {
|
||||
Err(Failure::Service(status, body.chars().take(300).collect()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Signs out: the tokens are forgotten at once, the refresh token is revoked at OpenAI
|
||||
/// in the background (if that fails, the user can disconnect the app in ChatGPT's
|
||||
/// settings — the link is beside the button).
|
||||
pub fn sign_out() {
|
||||
let Some(t) = crate::translate::credentials().chatgpt else {
|
||||
return;
|
||||
};
|
||||
update_credentials(|c| c.chatgpt = None);
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("chatgpt-sign-out".into())
|
||||
.spawn(move || revoke(&t));
|
||||
}
|
||||
|
||||
fn revoke(t: &Tokens) -> bool {
|
||||
let body = form(&[
|
||||
("token", &t.refresh),
|
||||
("token_type_hint", "refresh_token"),
|
||||
("client_id", &t.client_id),
|
||||
]);
|
||||
// The revocation address is published in the OpenID configuration.
|
||||
let revoke = agent(Duration::from_secs(20))
|
||||
.get(DISCOVERY)
|
||||
.call()
|
||||
.ok()
|
||||
.and_then(|mut r| r.body_mut().read_to_string().ok())
|
||||
.and_then(|t| serde_json::from_str::<Value>(&t).ok())
|
||||
.and_then(|v| v.get("revocation_endpoint")?.as_str().map(str::to_owned));
|
||||
revoke.is_some_and(|url| {
|
||||
agent(Duration::from_secs(20))
|
||||
.post(&url)
|
||||
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.send(&body)
|
||||
.is_ok_and(|r| r.status().as_u16() == 200)
|
||||
})
|
||||
}
|
||||
|
||||
// --- Requests ------------------------------------------------------------------------------
|
||||
|
||||
/// The models this account may use (`visibility: list`).
|
||||
pub fn models() -> Result<Vec<String>, Failure> {
|
||||
let token = access_token()?;
|
||||
let mut resp = agent(Duration::from_secs(30))
|
||||
.get(format!("{API}/models"))
|
||||
.header("Authorization", format!("Bearer {token}"))
|
||||
.call()
|
||||
.map_err(|e| Failure::Offline(e.to_string()))?;
|
||||
let status = resp.status().as_u16();
|
||||
let body = resp.body_mut().read_to_string().unwrap_or_default();
|
||||
if status != 200 {
|
||||
return Err(failure(status, &body));
|
||||
}
|
||||
let v: Value =
|
||||
serde_json::from_str(&body).map_err(|e| Failure::Service(status, e.to_string()))?;
|
||||
let mut ids: Vec<String> = v
|
||||
.get("data")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|m| {
|
||||
m.get("visibility")
|
||||
.and_then(Value::as_str)
|
||||
.is_none_or(|s| s == "list")
|
||||
})
|
||||
.filter_map(|m| m.get("id").and_then(Value::as_str).map(str::to_owned))
|
||||
.collect();
|
||||
ids.sort();
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The model to start with: a small fast one if listed (translation needs no more).
|
||||
pub fn default_model(models: &[String]) -> Option<String> {
|
||||
["mini", "fast", "flash"]
|
||||
.iter()
|
||||
.find_map(|w| models.iter().find(|m| m.contains(w)))
|
||||
.or_else(|| models.first())
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn failure(status: u16, body: &str) -> Failure {
|
||||
let v: Option<Value> = serde_json::from_str(body).ok();
|
||||
let code = v
|
||||
.as_ref()
|
||||
.and_then(|v| v.pointer("/error/code"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
let message = v
|
||||
.as_ref()
|
||||
.and_then(|v| v.pointer("/error/message").or_else(|| v.get("detail")))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(body)
|
||||
.chars()
|
||||
.take(300)
|
||||
.collect::<String>();
|
||||
match code {
|
||||
"subscription_sharing_usage_limit_exceeded" => Failure::PlanLimit,
|
||||
"subscription_sharing_user_not_eligible" => Failure::NotEligible(message),
|
||||
"subscription_sharing_invalid_user" => Failure::SignedOut,
|
||||
"subscription_sharing_usage_unavailable" | "subscription_sharing_user_unavailable" => {
|
||||
Failure::Service(503, message)
|
||||
}
|
||||
_ => match status {
|
||||
401 => Failure::SignedOut,
|
||||
403 => Failure::NotEligible(message),
|
||||
429 => Failure::RateLimited,
|
||||
_ => Failure::Service(status, message),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// One answer of the model, read from the event stream.
|
||||
pub fn respond(
|
||||
model: &str,
|
||||
system: &str,
|
||||
user: &str,
|
||||
cancel: &AtomicBool,
|
||||
) -> Result<String, Failure> {
|
||||
let body = json!({
|
||||
"model": model,
|
||||
"instructions": system,
|
||||
"input": [{"role": "user", "content": [{"type": "input_text", "text": user}]}],
|
||||
"store": false,
|
||||
"stream": true,
|
||||
})
|
||||
.to_string();
|
||||
let mut refreshed = false;
|
||||
with_waits(cancel, || {
|
||||
loop {
|
||||
let token = access_token()?;
|
||||
let resp = agent(Duration::from_secs(300))
|
||||
.post(format!("{API}/responses"))
|
||||
.header("Authorization", format!("Bearer {token}"))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Accept", "text/event-stream")
|
||||
.send(&body)
|
||||
.map_err(|e| Failure::Offline(e.to_string()))?;
|
||||
let status = resp.status().as_u16();
|
||||
if status == 401 && !refreshed {
|
||||
// The token may have been revoked or expired early: refresh once.
|
||||
refreshed = true;
|
||||
let _one = REFRESH.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// Read under the lock: another request may have refreshed already.
|
||||
if let Some(t) = crate::translate::credentials().chatgpt
|
||||
&& t.access == token
|
||||
{
|
||||
refresh(&t)?;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if status != 200 {
|
||||
let mut resp = resp;
|
||||
let text = resp.body_mut().read_to_string().unwrap_or_default();
|
||||
return Err(failure(status, &text));
|
||||
}
|
||||
return read_stream(BufReader::new(resp.into_body().into_reader()), cancel);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The text of a Responses event stream: the deltas until `response.completed`.
|
||||
fn read_stream(reader: impl BufRead, cancel: &AtomicBool) -> Result<String, Failure> {
|
||||
let mut text = String::new();
|
||||
for line in reader.lines() {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err(Failure::Offline("cancelled".into()));
|
||||
}
|
||||
let line = line.map_err(|e| Failure::Offline(e.to_string()))?;
|
||||
let Some(data) = line.strip_prefix("data:") else {
|
||||
continue;
|
||||
};
|
||||
let data = data.trim();
|
||||
if data == "[DONE]" {
|
||||
break;
|
||||
}
|
||||
let Ok(v) = serde_json::from_str::<Value>(data) else {
|
||||
continue;
|
||||
};
|
||||
match v.get("type").and_then(Value::as_str).unwrap_or("") {
|
||||
"response.output_text.delta" => {
|
||||
if let Some(d) = v.get("delta").and_then(Value::as_str) {
|
||||
text.push_str(d);
|
||||
}
|
||||
}
|
||||
"response.completed" => return Ok(text),
|
||||
"response.failed" | "error" => {
|
||||
let err = v
|
||||
.pointer("/response/error")
|
||||
.or_else(|| v.get("error"))
|
||||
.cloned()
|
||||
.unwrap_or(Value::Null);
|
||||
return Err(failure(0, &json!({ "error": err }).to_string()));
|
||||
}
|
||||
"response.incomplete" => {
|
||||
return Err(Failure::Service(0, "the answer was cut short".into()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err(Failure::Offline("the answer stream ended early".into()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Read as _;
|
||||
|
||||
#[test]
|
||||
fn host_ids_are_uuid_urns() {
|
||||
let id = new_host_id();
|
||||
assert!(id.starts_with("urn:uuid:"), "{id}");
|
||||
let u = &id[9..];
|
||||
assert_eq!(u.len(), 36);
|
||||
assert_eq!(&u[14..15], "4");
|
||||
assert_ne!(new_host_id(), id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_gives_its_text() {
|
||||
let s = "event: response.created\ndata: {\"type\":\"response.created\"}\n\n\
|
||||
data: {\"type\":\"response.output_text.delta\",\"delta\":\"{\\\"translations\\\"\"}\n\n\
|
||||
data: {\"type\":\"response.output_text.delta\",\"delta\":\": []}\"}\n\n\
|
||||
data: {\"type\":\"response.completed\",\"response\":{}}\n\n";
|
||||
let never = AtomicBool::new(false);
|
||||
assert_eq!(
|
||||
read_stream(s.as_bytes(), &never).unwrap(),
|
||||
"{\"translations\": []}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_used_up_limit_is_told_apart() {
|
||||
let s = "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"subscription_sharing_usage_limit_exceeded\",\"message\":\"limit\"}}}\n\n";
|
||||
let never = AtomicBool::new(false);
|
||||
assert_eq!(read_stream(s.as_bytes(), &never), Err(Failure::PlanLimit));
|
||||
assert_eq!(
|
||||
failure(
|
||||
403,
|
||||
r#"{"error":{"code":"subscription_sharing_user_not_eligible","message":"free plan"}}"#
|
||||
),
|
||||
Failure::NotEligible("free plan".into())
|
||||
);
|
||||
assert_eq!(failure(401, r#"{"detail":"bad"}"#), Failure::SignedOut);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_stream_is_not_an_answer() {
|
||||
let s = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"half\"}\n\n";
|
||||
let never = AtomicBool::new(false);
|
||||
assert!(read_stream(s.as_bytes(), &never).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_email_is_read_from_the_id_token() {
|
||||
let payload = URL_SAFE_NO_PAD.encode(br#"{"email":"a@b.c","nonce":"n1"}"#);
|
||||
let t = format!("x.{payload}.y");
|
||||
assert_eq!(email_of(&t).as_deref(), Some("a@b.c"));
|
||||
assert_eq!(nonce_of(&t).as_deref(), Some("n1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plan_scope_is_checked() {
|
||||
let t = Tokens {
|
||||
scope: "openid email chatgpt.tokens.use.direct".into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(t.plan());
|
||||
assert!(!Tokens::default().plan());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_callback_brings_the_code() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let browser = std::thread::spawn(move || {
|
||||
let mut s = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
write!(
|
||||
s,
|
||||
"GET /auth/callback?code=abc&state=st&client_id=oaiapp_1 HTTP/1.1\r\nHost: x\r\n\r\n"
|
||||
)
|
||||
.unwrap();
|
||||
let mut answer = String::new();
|
||||
let _ = s.read_to_string(&mut answer);
|
||||
answer
|
||||
});
|
||||
let never = AtomicBool::new(false);
|
||||
let got = wait_for_callback(&listener, &never, "st").unwrap();
|
||||
assert_eq!(got, ("abc".to_string(), Some("oaiapp_1".to_string())));
|
||||
assert!(browser.join().unwrap().starts_with("HTTP/1.1 200"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declined_consent_is_told_apart() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
std::thread::spawn(move || {
|
||||
let mut s = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
write!(
|
||||
s,
|
||||
"GET /auth/callback?error=access_denied&state=st HTTP/1.1\r\n\r\n"
|
||||
)
|
||||
.unwrap();
|
||||
let mut a = String::new();
|
||||
let _ = s.read_to_string(&mut a);
|
||||
});
|
||||
let never = AtomicBool::new(false);
|
||||
assert_eq!(
|
||||
wait_for_callback(&listener, &never, "st"),
|
||||
Err(SignedIn::Declined)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -61,6 +61,10 @@ pub struct GameView {
|
|||
pub previous: Option<String>,
|
||||
/// A newer version to offer (its number), next to Settings.
|
||||
pub update: Option<String>,
|
||||
/// Comments in another language, translated for reading (never into the PGN).
|
||||
translation: crate::translate_ui::GameTranslation,
|
||||
/// "Translate comments" was chosen (menu, Ctrl+Shift+T): done once the settings are at hand.
|
||||
translate_now: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
|
|
@ -100,6 +104,8 @@ pub enum GameAction {
|
|||
ReturnToPrevious,
|
||||
/// The window offering a newer version.
|
||||
OpenUpdate,
|
||||
/// Settings → Translation.
|
||||
OpenTranslationSettings,
|
||||
}
|
||||
|
||||
impl GameView {
|
||||
|
|
@ -126,9 +132,26 @@ impl GameView {
|
|||
},
|
||||
previous: None,
|
||||
update: None,
|
||||
translation: Default::default(),
|
||||
translate_now: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The game is put aside (another one opened): its translation stops.
|
||||
pub fn suspend(&mut self) {
|
||||
self.translation.suspend();
|
||||
}
|
||||
|
||||
/// Copying the PGN always copies the original comments; say so when the translation is shown.
|
||||
fn copy_pgn(&self) -> GameAction {
|
||||
let note = if self.translation.shown().is_some() {
|
||||
tr("PGN copied (comments in the original)")
|
||||
} else {
|
||||
tr("PGN copied")
|
||||
};
|
||||
GameAction::CopyText(self.game.to_pgn(), note)
|
||||
}
|
||||
|
||||
pub fn title(&self) -> String {
|
||||
let g = &self.game;
|
||||
let white = g.tag("White").filter(|s| *s != "?").unwrap_or(tr("White"));
|
||||
|
|
@ -229,9 +252,11 @@ impl GameView {
|
|||
settings: &mut Settings,
|
||||
analysis: &mut Analysis,
|
||||
reference: &mut crate::reference::Reference,
|
||||
hub: &mut crate::translate_ui::Hub,
|
||||
input_enabled: bool,
|
||||
) -> Vec<GameAction> {
|
||||
let mut actions = Vec::new();
|
||||
self.translation.update(ui.ctx(), &self.game, settings, hub);
|
||||
if self.review.poll() {
|
||||
actions.push(GameAction::ResumeLive);
|
||||
if let Some(e) = &self.review.error {
|
||||
|
|
@ -281,7 +306,7 @@ impl GameView {
|
|||
.default_size(side_width)
|
||||
.size_range(least.min(width * 0.5).min(max)..=max)
|
||||
.show(ui, |ui| {
|
||||
self.side_panel(ui, settings, analysis, reference, &mut actions)
|
||||
self.side_panel(ui, settings, analysis, reference, hub, &mut actions)
|
||||
});
|
||||
self.sync_analysis(analysis);
|
||||
let hover = (self.side_tab == SideTab::Reference)
|
||||
|
|
@ -734,6 +759,7 @@ impl GameView {
|
|||
settings: &mut Settings,
|
||||
analysis: &mut Analysis,
|
||||
reference: &mut crate::reference::Reference,
|
||||
hub: &mut crate::translate_ui::Hub,
|
||||
actions: &mut Vec<GameAction>,
|
||||
) {
|
||||
egui::Panel::bottom("game_toolbar").show(ui, |ui| self.toolbar(ui, actions));
|
||||
|
|
@ -804,6 +830,18 @@ impl GameView {
|
|||
}
|
||||
return;
|
||||
}
|
||||
match self.translation.strip(ui, settings, hub) {
|
||||
Some(crate::translate_ui::StripAction::OpenSettings) => {
|
||||
actions.push(GameAction::OpenTranslationSettings)
|
||||
}
|
||||
Some(crate::translate_ui::StripAction::Toast(t)) => {
|
||||
actions.push(GameAction::Toast(t))
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if std::mem::take(&mut self.translate_now) {
|
||||
self.translation.translate(ui.ctx(), settings, hub);
|
||||
}
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink(false)
|
||||
.show(ui, |ui| {
|
||||
|
|
@ -816,6 +854,7 @@ impl GameView {
|
|||
.preview
|
||||
.as_ref()
|
||||
.map(|p| (p.base, p.san.as_slice(), p.shown)),
|
||||
translations: self.translation.shown(),
|
||||
}
|
||||
.show(ui);
|
||||
if let Some(id) = resp.clicked {
|
||||
|
|
@ -1121,7 +1160,7 @@ impl GameView {
|
|||
ui.separator();
|
||||
ui.menu_button(big("☰"), |ui| {
|
||||
if ui.button(tr("Copy PGN")).clicked() {
|
||||
actions.push(GameAction::CopyText(self.game.to_pgn(), tr("PGN copied")));
|
||||
actions.push(self.copy_pgn());
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tr("Copy FEN")).clicked() {
|
||||
|
|
@ -1138,13 +1177,35 @@ impl GameView {
|
|||
self.show_diagnostics = true;
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if self.translation.can_translate() && ui.button(tr("Translate comments")).clicked()
|
||||
{
|
||||
self.translate_now = true;
|
||||
self.side_tab = SideTab::Notation;
|
||||
ui.close();
|
||||
}
|
||||
if self.translation.has_translation() {
|
||||
let label = if self.translation.original {
|
||||
tr("Show the translation (Ctrl+Shift+T)")
|
||||
} else {
|
||||
tr("Show the original (Ctrl+Shift+T)")
|
||||
};
|
||||
if ui.button(label).clicked() {
|
||||
self.translation.toggle();
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if ui.button(tr("Translation settings…")).clicked() {
|
||||
actions.push(GameAction::OpenTranslationSettings);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
if ui
|
||||
.button(big("📋"))
|
||||
.on_hover_text(tr("Copy PGN (Ctrl+Shift+C)"))
|
||||
.clicked()
|
||||
{
|
||||
actions.push(GameAction::CopyText(self.game.to_pgn(), tr("PGN copied")));
|
||||
actions.push(self.copy_pgn());
|
||||
}
|
||||
ui.separator();
|
||||
self.review_button(ui, actions);
|
||||
|
|
@ -1332,6 +1393,9 @@ impl GameView {
|
|||
if i.consume_shortcut(&ctrl_shift(Key::F)) {
|
||||
cmds.push("find");
|
||||
}
|
||||
if i.consume_shortcut(&ctrl_shift(Key::T)) {
|
||||
cmds.push("translate");
|
||||
}
|
||||
if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) {
|
||||
cmds.push("review");
|
||||
}
|
||||
|
|
@ -1357,7 +1421,7 @@ impl GameView {
|
|||
match cmd {
|
||||
"undo" => self.undo(),
|
||||
"redo" => self.redo(),
|
||||
"copy" => actions.push(GameAction::CopyText(self.game.to_pgn(), tr("PGN copied"))),
|
||||
"copy" => actions.push(self.copy_pgn()),
|
||||
"save" => actions.push(GameAction::SaveAs),
|
||||
"back" => actions.push(GameAction::Back),
|
||||
"find" if self.search_line().is_some() => {
|
||||
|
|
@ -1385,6 +1449,14 @@ impl GameView {
|
|||
self.goto(end);
|
||||
}
|
||||
"flip" => self.flipped = !self.flipped,
|
||||
"translate" => {
|
||||
if self.translation.has_translation() {
|
||||
self.translation.toggle();
|
||||
} else if self.translation.can_translate() {
|
||||
self.translate_now = true;
|
||||
self.side_tab = SideTab::Notation;
|
||||
}
|
||||
}
|
||||
"engine" => actions.push(GameAction::ToggleEngine),
|
||||
"review" => {
|
||||
if self.review.has_data() || self.review.running() {
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -6,6 +6,7 @@ mod app;
|
|||
mod assets;
|
||||
mod board;
|
||||
mod board_search;
|
||||
mod chatgpt;
|
||||
mod engine_download;
|
||||
mod engine_offer;
|
||||
mod engines;
|
||||
|
|
@ -24,6 +25,8 @@ mod review;
|
|||
mod settings;
|
||||
mod settings_ui;
|
||||
mod sound;
|
||||
mod translate;
|
||||
mod translate_ui;
|
||||
mod update;
|
||||
mod update_ui;
|
||||
mod viewed;
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ use std::collections::HashMap;
|
|||
|
||||
use crate::i18n::tr;
|
||||
use crate::review::{Mark, judgement_color, judgement_name, judgement_symbol};
|
||||
use crate::translate_ui::Mark as Translated;
|
||||
use chess_core::shakmaty::{Color, Position};
|
||||
use chess_core::{CommentPart, Game, Nag, NodeId, parse_comment};
|
||||
use egui::{Align2, Color32, FontId, RichText, Sense, Stroke, Ui, vec2};
|
||||
|
|
@ -17,6 +18,8 @@ pub struct Notation<'a> {
|
|||
pub marks: Option<&'a HashMap<NodeId, Mark>>,
|
||||
/// Engine line shown on the board: (start node, SAN moves, moves played so far).
|
||||
pub preview: Option<(NodeId, &'a [String], usize)>,
|
||||
/// Translated comments by their original text (none: the original is shown).
|
||||
pub translations: Option<&'a HashMap<String, Translated>>,
|
||||
}
|
||||
|
||||
/// Result of a frame of the notation panel.
|
||||
|
|
@ -49,7 +52,7 @@ impl Notation<'_> {
|
|||
.unwrap_or(&[]),
|
||||
);
|
||||
if !root_comments.is_empty() {
|
||||
comment_block(ui, &root_comments);
|
||||
comment_block(ui, &self, &root_comments);
|
||||
}
|
||||
|
||||
let mut row = Row::default();
|
||||
|
|
@ -59,7 +62,7 @@ impl Notation<'_> {
|
|||
let before = comment_text(n.comments_before());
|
||||
if !before.is_empty() {
|
||||
row.flush(ui, &self, &mut out);
|
||||
comment_block(ui, &before);
|
||||
comment_block(ui, &self, &before);
|
||||
}
|
||||
let (num, color) = game.move_number(child).unwrap_or((0, Color::White));
|
||||
if color == Color::White {
|
||||
|
|
@ -83,7 +86,7 @@ impl Notation<'_> {
|
|||
mark_block(ui, &self, child, mark, &mut out);
|
||||
}
|
||||
if !after.is_empty() {
|
||||
comment_block(ui, &after);
|
||||
comment_block(ui, &self, &after);
|
||||
}
|
||||
for u in n.unparsed() {
|
||||
unparsed_block(ui, u);
|
||||
|
|
@ -357,7 +360,7 @@ fn move_glyph(nags: &[Nag]) -> (String, Option<Color32>) {
|
|||
(s, color)
|
||||
}
|
||||
|
||||
fn comment_text(comments: &[String]) -> String {
|
||||
pub fn comment_text(comments: &[String]) -> String {
|
||||
let mut out = String::new();
|
||||
for c in comments {
|
||||
for part in parse_comment(c) {
|
||||
|
|
@ -397,10 +400,79 @@ fn block_frame(ui: &Ui) -> egui::Frame {
|
|||
))
|
||||
}
|
||||
|
||||
fn comment_block(ui: &mut Ui, text: &str) {
|
||||
/// The text to show for a comment and its translation mark.
|
||||
fn translated<'a>(n: &'a Notation, text: &'a str) -> (&'a str, Option<&'a Translated>) {
|
||||
match n.translations.and_then(|t| t.get(text)) {
|
||||
Some(m @ Translated::Translated(t)) => (t.as_str(), Some(m)),
|
||||
m => (text, m),
|
||||
}
|
||||
}
|
||||
|
||||
/// "⇄" (machine translation, the original in the tooltip), "⋯" (on its way), "⚠" (failed).
|
||||
fn translation_mark(ui: &mut Ui, mark: &Translated, original: &str) {
|
||||
let (sym, color, tip, name) = match mark {
|
||||
Translated::Translated(_) => {
|
||||
let mut o: String = original.chars().take(1000).collect();
|
||||
if original.chars().count() > 1000 {
|
||||
o.push('…');
|
||||
}
|
||||
(
|
||||
"⇄",
|
||||
ui.visuals().weak_text_color(),
|
||||
format!("{}\n{o}", tr("Machine translation. Original:")),
|
||||
tr("Machine translation"),
|
||||
)
|
||||
}
|
||||
Translated::Pending => (
|
||||
"⋯",
|
||||
ui.visuals().weak_text_color(),
|
||||
tr("Translating…").to_owned(),
|
||||
tr("Translating…"),
|
||||
),
|
||||
Translated::Bad => (
|
||||
"⚠",
|
||||
ui.visuals().warn_fg_color,
|
||||
tr("This comment could not be translated — the original is shown. Press “Retry” in the line above the notation.").to_owned(),
|
||||
tr("Not translated"),
|
||||
),
|
||||
};
|
||||
let r =
|
||||
ui.add(egui::Label::new(RichText::new(sym).size(13.0).color(color)).sense(Sense::hover()));
|
||||
r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, name));
|
||||
r.on_hover_ui(|ui| {
|
||||
ui.set_max_width(360.0);
|
||||
ui.label(tip);
|
||||
});
|
||||
}
|
||||
|
||||
fn comment_block(ui: &mut Ui, n: &Notation, text: &str) {
|
||||
let (shown, mark) = translated(n, text);
|
||||
block_frame(ui).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.label(RichText::new(text).color(comment_color(ui)).size(14.5));
|
||||
match mark {
|
||||
Some(m) => {
|
||||
ui.horizontal_top(|ui| {
|
||||
// A slot of its own for the mark: ⚠ is wider than ⇄.
|
||||
let w = ui.available_width() - 16.0 - ui.spacing().item_spacing.x;
|
||||
ui.allocate_ui_with_layout(
|
||||
vec2(w, 0.0),
|
||||
egui::Layout::top_down(egui::Align::Min),
|
||||
|ui| {
|
||||
ui.set_width(w);
|
||||
ui.label(RichText::new(shown).color(comment_color(ui)).size(14.5));
|
||||
},
|
||||
);
|
||||
ui.allocate_ui_with_layout(
|
||||
vec2(16.0, 18.0),
|
||||
egui::Layout::top_down(egui::Align::Center),
|
||||
|ui| translation_mark(ui, m, text),
|
||||
);
|
||||
});
|
||||
}
|
||||
None => {
|
||||
ui.label(RichText::new(shown).color(comment_color(ui)).size(14.5));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -443,7 +515,11 @@ fn inline_line(ui: &mut Ui, n: &Notation, first: NodeId, out: &mut NotationRespo
|
|||
let Some(nd) = game.node(node) else { return };
|
||||
let before = comment_text(nd.comments_before());
|
||||
if !before.is_empty() {
|
||||
ui.label(RichText::new(before).color(comment_color(ui)));
|
||||
let (shown, mark) = translated(n, &before);
|
||||
ui.label(RichText::new(shown).color(comment_color(ui)));
|
||||
if let Some(m) = mark {
|
||||
translation_mark(ui, m, &before);
|
||||
}
|
||||
need_number = true;
|
||||
}
|
||||
let (num, color) = game.move_number(node).unwrap_or((0, Color::White));
|
||||
|
|
@ -476,7 +552,11 @@ fn inline_line(ui: &mut Ui, n: &Notation, first: NodeId, out: &mut NotationRespo
|
|||
|
||||
let after = comment_text(nd.comments_after());
|
||||
if !after.is_empty() {
|
||||
ui.label(RichText::new(after).color(comment_color(ui)));
|
||||
let (shown, mark) = translated(n, &after);
|
||||
ui.label(RichText::new(shown).color(comment_color(ui)));
|
||||
if let Some(m) = mark {
|
||||
translation_mark(ui, m, &after);
|
||||
}
|
||||
need_number = true;
|
||||
}
|
||||
for u in nd.unparsed() {
|
||||
|
|
|
|||
|
|
@ -102,6 +102,8 @@ pub struct Settings {
|
|||
pub show_coords: bool,
|
||||
/// How fast moves slide on the board.
|
||||
pub animation: Animation,
|
||||
/// Translating game comments (docs/design/translation.md).
|
||||
pub translation: crate::translate::TranslationSettings,
|
||||
pub sound_enabled: bool,
|
||||
pub sound_set: SoundSet,
|
||||
pub volume: f32,
|
||||
|
|
@ -168,6 +170,7 @@ impl Default for Settings {
|
|||
board_theme: BoardThemeId::default(),
|
||||
show_coords: true,
|
||||
animation: Animation::default(),
|
||||
translation: Default::default(),
|
||||
sound_enabled: true,
|
||||
sound_set: SoundSet::default(),
|
||||
volume: 0.7,
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ pub enum Tab {
|
|||
Board,
|
||||
Sound,
|
||||
Interface,
|
||||
Translation,
|
||||
About,
|
||||
}
|
||||
|
||||
|
|
@ -61,7 +62,12 @@ impl SettingsWindow {
|
|||
}
|
||||
|
||||
/// Returns actions and whether settings changed (to be saved).
|
||||
pub fn show(&mut self, ctx: &egui::Context, s: &mut Settings) -> (Vec<SettingsAction>, bool) {
|
||||
pub fn show(
|
||||
&mut self,
|
||||
ctx: &egui::Context,
|
||||
s: &mut Settings,
|
||||
translation: &mut crate::translate_ui::Hub,
|
||||
) -> (Vec<SettingsAction>, bool) {
|
||||
let mut actions = Vec::new();
|
||||
let mut changed = false;
|
||||
let mut open = self.open;
|
||||
|
|
@ -78,12 +84,14 @@ impl SettingsWindow {
|
|||
ui.selectable_value(&mut self.tab, Tab::Board, tr("Board & pieces"));
|
||||
ui.selectable_value(&mut self.tab, Tab::Sound, tr("Sound"));
|
||||
ui.selectable_value(&mut self.tab, Tab::Interface, tr("Interface"));
|
||||
ui.selectable_value(&mut self.tab, Tab::Translation, tr("Translation"));
|
||||
ui.selectable_value(&mut self.tab, Tab::About, tr("About"));
|
||||
});
|
||||
ui.separator();
|
||||
egui::ScrollArea::vertical().show(ui, |ui| match self.tab {
|
||||
Tab::Engines => self.engines(ui, s, &mut actions, &mut changed),
|
||||
Tab::Board => board_tab(ui, s, &mut changed),
|
||||
Tab::Translation => changed |= translation.settings_tab(ui, s),
|
||||
Tab::Sound => sound_tab(ui, s, &mut actions, &mut changed),
|
||||
Tab::About => {
|
||||
let (status, available) =
|
||||
|
|
|
|||
1517
apps/desktop/src/translate.rs
Normal file
1517
apps/desktop/src/translate.rs
Normal file
File diff suppressed because it is too large
Load diff
1993
apps/desktop/src/translate_ui.rs
Normal file
1993
apps/desktop/src/translate_ui.rs
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue