1use crate::client::layout_ops::LayoutOps;
2use crate::client::maestro_ops::MaestroOps;
3use crate::client::schematic_ops::SchematicOps;
4use crate::client::window_ops::WindowOps;
5use crate::error::{Result, VirtuosoError};
6use crate::models::{ExecutionStatus, VirtuosoResult};
7use crate::transport::tunnel::SSHClient;
8use std::io::{Read, Write};
9use std::net::TcpStream;
10use std::time::Instant;
11
12const STX: u8 = 0x02;
13const NAK: u8 = 0x15;
14const MAX_RESPONSE_SIZE: usize = 100 * 1024 * 1024; pub struct VirtuosoClient {
17 host: String,
18 port: u16,
19 timeout: u64,
20 tunnel: Option<SSHClient>,
21 pub layout: LayoutOps,
22 pub maestro: MaestroOps,
23 pub schematic: SchematicOps,
24 pub window: WindowOps,
25}
26
27impl VirtuosoClient {
28 pub fn new(host: &str, port: u16, timeout: u64) -> Self {
29 Self {
30 host: host.into(),
31 port,
32 timeout,
33 tunnel: None,
34 layout: LayoutOps::new(),
35 maestro: MaestroOps,
36 schematic: SchematicOps::new(),
37 window: WindowOps,
38 }
39 }
40
41 pub fn from_env() -> Result<Self> {
42 let cfg = crate::config::Config::from_env()?;
43
44 let tunnel = if cfg.is_remote() {
45 let state = crate::models::TunnelState::load().ok().flatten();
46 if let Some(ref s) = state {
47 if is_port_open(s.port) {
48 tracing::info!("reusing existing tunnel on port {}", s.port);
49 let client = SSHClient::from_env(cfg.keep_remote_files)?;
50 Some(client)
51 } else {
52 None
53 }
54 } else {
55 None
56 }
57 } else {
58 None
59 };
60
61 let port = if let Some(base_port) = tunnel.as_ref().and_then(|t| t.saved_port()) {
66 base_port
67 } else if let Ok(session_id) = std::env::var("VB_SESSION") {
68 match crate::models::SessionInfo::load(&session_id) {
72 Ok(s) => {
73 tracing::info!("connecting to session '{}' on port {}", s.id, s.port);
74 s.port
75 }
76 Err(_) => {
77 tracing::debug!(
78 "session '{}' not a bridge session (no file), using VB_PORT",
79 session_id
80 );
81 cfg.port
82 }
83 }
84 } else {
85 match crate::models::SessionInfo::list() {
87 Ok(sessions) if sessions.len() == 1 => {
88 let s = &sessions[0];
89 tracing::info!("auto-selected session '{}' on port {}", s.id, s.port);
90 s.port
91 }
92 Ok(sessions) if sessions.len() > 1 => {
93 let ids: Vec<&str> = sessions.iter().map(|s| s.id.as_str()).collect();
94 return Err(crate::error::VirtuosoError::Config(format!(
95 "multiple Virtuoso sessions active: {}. Use --session <id> to select one.",
96 ids.join(", ")
97 )));
98 }
99 _ => cfg.port, }
101 };
102
103 Ok(Self {
104 host: "127.0.0.1".into(),
105 port,
106 timeout: cfg.timeout,
107 tunnel,
108 layout: LayoutOps::new(),
109 maestro: MaestroOps,
110 schematic: SchematicOps::new(),
111 window: WindowOps,
112 })
113 }
114
115 pub fn local(host: &str, port: u16, timeout: u64) -> Self {
116 Self::new(host, port, timeout)
117 }
118
119 pub fn execute_skill(&self, skill_code: &str, timeout: Option<u64>) -> Result<VirtuosoResult> {
120 if let Some(warning) = check_blocking_skill(skill_code) {
122 return Err(VirtuosoError::Execution(warning));
123 }
124
125 let timeout = timeout.unwrap_or(self.timeout);
126 let start = Instant::now();
127
128 let addr: std::net::SocketAddr = format!("{}:{}", self.host, self.port)
129 .parse()
130 .map_err(|e| VirtuosoError::Connection(format!("invalid address: {e}")))?;
131 let mut stream = TcpStream::connect_timeout(&addr, std::time::Duration::from_secs(timeout))
132 .map_err(|e| VirtuosoError::Connection(e.to_string()))?;
133 stream
134 .set_read_timeout(Some(std::time::Duration::from_secs(timeout)))
135 .ok();
136
137 let req = serde_json::json!({
138 "skill": skill_code,
139 "timeout": timeout
140 });
141 let req_bytes = serde_json::to_string(&req).map_err(VirtuosoError::Json)?;
142 stream
143 .write_all(req_bytes.as_bytes())
144 .map_err(|e| VirtuosoError::Connection(e.to_string()))?;
145 stream
146 .shutdown(std::net::Shutdown::Write)
147 .map_err(|e| VirtuosoError::Connection(e.to_string()))?;
148
149 let mut data = Vec::new();
150 let mut buf = [0u8; 65536];
151 loop {
152 match stream.read(&mut buf) {
153 Ok(0) => break,
154 Ok(n) => {
155 if data.len() + n > MAX_RESPONSE_SIZE {
156 return Err(VirtuosoError::Execution(format!(
157 "response exceeds {}MB limit",
158 MAX_RESPONSE_SIZE / 1024 / 1024
159 )));
160 }
161 data.extend_from_slice(&buf[..n]);
162 }
163 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
164 return Err(VirtuosoError::Timeout(timeout));
165 }
166 Err(e) => return Err(VirtuosoError::Connection(e.to_string())),
167 }
168 }
169
170 let elapsed = start.elapsed().as_secs_f64();
171
172 if data.is_empty() {
173 return Err(VirtuosoError::Execution(
174 "empty response from daemon".into(),
175 ));
176 }
177
178 let status_byte = data[0];
179 let payload = String::from_utf8_lossy(&data[1..]).to_string();
180
181 let mut result = VirtuosoResult {
182 status: ExecutionStatus::Success,
183 output: String::new(),
184 errors: Vec::new(),
185 warnings: Vec::new(),
186 execution_time: Some(elapsed),
187 metadata: Default::default(),
188 };
189
190 if status_byte == STX {
195 result.output = payload;
196 } else if status_byte == NAK {
197 result.status = ExecutionStatus::Error;
198 result.errors.push(payload);
199 } else {
200 result.output = String::from_utf8_lossy(&data).to_string();
201 result.warnings.push("non-standard response marker".into());
202 }
203
204 let truncated = if skill_code.len() > 200 {
206 format!("{}...", &skill_code[..200])
207 } else {
208 skill_code.to_string()
209 };
210 crate::command_log::log_command("SKILL", &truncated, Some(start.elapsed().as_millis()));
211
212 Ok(result)
213 }
214
215 pub fn test_connection(&self, timeout: Option<u64>) -> Result<bool> {
216 let result = self.execute_skill("1+1", timeout)?;
217 Ok(result.output.trim() == "2")
218 }
219
220 pub fn open_cell_view(
221 &self,
222 lib: &str,
223 cell: &str,
224 view: &str,
225 mode: &str,
226 ) -> Result<VirtuosoResult> {
227 let lib = escape_skill_string(lib);
228 let cell = escape_skill_string(cell);
229 let view = escape_skill_string(view);
230 let mode = escape_skill_string(mode);
231 let skill = format!(
232 r#"geOpenCellView(?libName "{lib}" ?cellName "{cell}" ?viewName "{view}" ?mode "{mode}")"#
233 );
234 self.execute_skill(&skill, None)
235 }
236
237 pub fn save_current_cellview(&self) -> Result<VirtuosoResult> {
238 self.execute_skill("geSaveEdit()", None)
239 }
240
241 pub fn close_current_cellview(&self) -> Result<VirtuosoResult> {
242 self.execute_skill("geCloseEdit()", None)
243 }
244
245 pub fn get_current_design(&self) -> Result<(String, String, String)> {
246 let result = self.execute_skill(
247 r#"let((cv) cv = geGetEditCellView() list(cv~>libName cv~>cellName cv~>viewName))"#,
248 None,
249 )?;
250 let cleaned = result.output.trim().trim_matches(|c| c == '(' || c == ')');
251 let parts: Vec<&str> = cleaned.split_whitespace().collect();
252 if parts.len() >= 3 {
253 let strip = |s: &str| s.trim_matches('"').to_string();
254 Ok((strip(parts[0]), strip(parts[1]), strip(parts[2])))
255 } else {
256 Err(VirtuosoError::Execution(
257 "failed to get current design".into(),
258 ))
259 }
260 }
261
262 pub fn load_il(&self, local_path: &str) -> Result<VirtuosoResult> {
263 let remote_path = format!("/tmp/virtuoso_bridge/{}", {
264 std::path::Path::new(local_path)
265 .file_name()
266 .unwrap_or_default()
267 .to_string_lossy()
268 });
269
270 self.upload_file(local_path, &remote_path)?;
271
272 let remote_path_escaped = escape_skill_string(&remote_path);
273 let skill = format!(r#"(load "{remote_path_escaped}")"#);
274 self.execute_skill(&skill, None)
275 }
276
277 pub fn upload_file(&self, local: &str, remote: &str) -> Result<()> {
278 if let Some(ref tunnel) = self.tunnel {
279 tunnel.upload_file(local, remote)
280 } else {
281 std::fs::copy(local, remote)
282 .map(|_| ())
283 .map_err(VirtuosoError::Io)
284 }
285 }
286
287 pub fn download_file(&self, remote: &str, local: &str) -> Result<()> {
288 if let Some(ref tunnel) = self.tunnel {
289 tunnel.download_file(remote, local)
290 } else {
291 std::fs::copy(remote, local)
292 .map(|_| ())
293 .map_err(VirtuosoError::Io)
294 }
295 }
296
297 pub fn execute_operations(&self, commands: &[String]) -> Result<VirtuosoResult> {
298 if commands.is_empty() {
299 return Ok(VirtuosoResult::success(""));
300 }
301 let body = commands.join("\n");
302 let skill = format!("progn(\n{body}\n)");
303 self.execute_skill(&skill, None)
304 }
305
306 pub fn ciw_print(&self, message: &str) -> Result<VirtuosoResult> {
307 let skill = format!(
308 r#"printf("[virtuoso-cli] {}\n")"#,
309 escape_skill_string(message)
310 );
311 self.execute_skill(&skill, None)
312 }
313
314 pub fn run_shell_command(&self, cmd: &str) -> Result<VirtuosoResult> {
315 let cmd = escape_skill_string(cmd);
316 let skill = format!(r#"(csh "{cmd}")"#);
317 self.execute_skill(&skill, None)
318 }
319
320 pub fn tunnel(&self) -> Option<&SSHClient> {
321 self.tunnel.as_ref()
322 }
323}
324
325fn is_port_open(port: u16) -> bool {
326 TcpStream::connect(format!("127.0.0.1:{port}")).is_ok()
327}
328
329fn check_blocking_skill(code: &str) -> Option<String> {
330 if code.contains("system(") || code.contains("sh(") {
331 let lower = code.to_lowercase();
332 if lower.contains("find /") || lower.contains("find \"/") {
333 return Some(
334 "Blocked: system()/sh() with recursive 'find /' can hang the SKILL daemon. \
335 Use a specific directory instead (e.g., find /home/...)."
336 .into(),
337 );
338 }
339 }
340 None
341}
342
343pub fn escape_skill_string(s: &str) -> String {
344 s.replace('\\', "\\\\")
345 .replace('"', "\\\"")
346 .replace('\n', "\\n")
347}