JAL-2422 JAL-3551 viewer text/variables generalised, Pymol paths added
[jalview.git] / src / jalview / ext / pymol / PymolManager.java
1 package jalview.ext.pymol;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.io.PrintWriter;
9 import java.net.HttpURLConnection;
10 import java.net.SocketException;
11 import java.net.URL;
12 import java.nio.file.Paths;
13 import java.util.ArrayList;
14 import java.util.List;
15
16 import jalview.bin.Cache;
17 import jalview.gui.Preferences;
18 import jalview.structure.StructureCommand;
19 import jalview.structure.StructureCommandI;
20
21 public class PymolManager
22 {
23   private static final int RPC_REPLY_TIMEOUT_MS = 15000;
24
25   private static final int CONNECTION_TIMEOUT_MS = 100;
26
27   private static final String POST1 = "<methodCall><methodName>";
28
29   private static final String POST2 = "</methodName><params>";
30
31   private static final String POST3 = "</params></methodCall>";
32
33   private Process pymolProcess;
34
35   private int pymolXmlRpcPort;
36
37   /**
38    * Returns a list of paths to try for the PyMOL executable. Any user
39    * preference is placed first, otherwise 'standard' paths depending on the
40    * operating system.
41    * 
42    * @return
43    */
44   public static List<String> getPymolPaths()
45   {
46     return getPymolPaths(System.getProperty("os.name"));
47   }
48
49   /**
50    * Returns a list of paths to try for the PyMOL executable. Any user
51    * preference is placed first, otherwise 'standard' paths depending on the
52    * operating system.
53    * 
54    * @param os
55    *          operating system as reported by environment variable
56    *          {@code os.name}
57    * @return
58    */
59   protected static List<String> getPymolPaths(String os)
60   {
61     List<String> pathList = new ArrayList<>();
62   
63     String userPath = Cache
64             .getDefault(Preferences.PYMOL_PATH, null);
65     if (userPath != null)
66     {
67       pathList.add(userPath);
68     }
69   
70     /*
71      * add default installation paths
72      */
73     String pymol = "PyMOL";
74     if (os.startsWith("Linux"))
75     {
76       pathList.add("/usr/local/pymol/bin/" + pymol);
77       pathList.add("/usr/local/bin/" + pymol);
78       pathList.add("/usr/bin/" + pymol);
79       pathList.add(System.getProperty("user.home") + "/opt/bin/" + pymol);
80     }
81     else if (os.startsWith("Windows"))
82     {
83       // todo Windows installation path(s)
84     }
85     else if (os.startsWith("Mac"))
86     {
87       pathList.add("/Applications/PyMOL.app/Contents/MacOS/" + pymol);
88     }
89     return pathList;
90   }
91
92   public boolean isPymolLaunched()
93   {
94     // TODO pull up generic methods for external viewer processes
95     boolean launched = false;
96     if (pymolProcess != null)
97     {
98       try
99       {
100         pymolProcess.exitValue();
101         // if we get here, process has ended
102       } catch (IllegalThreadStateException e)
103       {
104         // ok - not yet terminated
105         launched = true;
106       }
107     }
108     return launched;
109   }
110
111   public void exitPymol()
112   {
113     if (isPymolLaunched() && pymolProcess != null)
114     {
115       sendCommand(new StructureCommand("quit"), false);
116     }
117     pymolProcess = null;
118     // currentModelsMap.clear();
119     this.pymolXmlRpcPort = 0;
120   }
121
122   /**
123    * Sends the command to Pymol; if requested, tries to get and return any
124    * replies, else returns null
125    * 
126    * @param command
127    * @param getReply
128    * @return
129    */
130   public List<String> sendCommand(StructureCommandI command,
131           boolean getReply)
132   {
133     String postBody = getPostRequest(command);
134     // System.out.println(postBody);// debug
135     String rpcUrl = "http://127.0.0.1:" + this.pymolXmlRpcPort;
136     PrintWriter out = null;
137     BufferedReader in = null;
138     List<String> result = getReply ? new ArrayList<>() : null;
139
140     try
141     {
142       URL realUrl = new URL(rpcUrl);
143       HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
144       conn.setRequestProperty("accept", "*/*");
145       conn.setRequestProperty("content-type", "text/xml");
146       conn.setDoOutput(true);
147       conn.setDoInput(true);
148       out = new PrintWriter(conn.getOutputStream());
149       out.print(postBody);
150       out.flush();
151       int rc = conn.getResponseCode();
152       if (rc != HttpURLConnection.HTTP_OK)
153       {
154         Cache.log.error(
155                 String.format("Error status from %s: %d", rpcUrl, rc));
156         return result;
157       }
158
159       InputStream inputStream = conn.getInputStream();
160       if (getReply)
161       {
162         in = new BufferedReader(new InputStreamReader(inputStream));
163         String line;
164         while ((line = in.readLine()) != null)
165         {
166           result.add(line);
167         }
168       }
169     } catch (SocketException e)
170     {
171       // thrown when 'quit' command is sent to PyMol
172       Cache.log.warn(String.format("Request to %s returned %s", rpcUrl,
173               e.toString()));
174     } catch (Exception e)
175     {
176       e.printStackTrace();
177     } finally
178     {
179       if (out != null)
180       {
181         out.close();
182       }
183     }
184     return result;
185   }
186
187   /**
188    * Builds the body of the XML-RPC format POST request to execute the command
189    * 
190    * @param command
191    * @return
192    */
193   static String getPostRequest(StructureCommandI command)
194   {
195     StringBuilder sb = new StringBuilder(64);
196     sb.append(POST1).append(command.getCommand()).append(POST2);
197     if (command.hasParameters())
198     {
199       for (String p : command.getParameters())
200       {
201         /*
202          * for now assuming all are string - <string> element is optional
203          * refactor in future if other data types needed
204          * https://www.tutorialspoint.com/xml-rpc/xml_rpc_data_model.htm
205          */
206         sb.append("<parameter><value>").append(p)
207                 .append("</value></parameter>");
208       }
209     }
210     sb.append(POST3);
211     return sb.toString();
212   }
213
214   public boolean launchPymol()
215   {
216     // todo pull up much of this
217     // Do nothing if already launched
218     if (isPymolLaunched())
219     {
220       return true;
221     }
222
223     String error = "Error message: ";
224     for (String pymolPath : getPymolPaths())
225     {
226       try
227       {
228         // ensure symbolic links are resolved
229         pymolPath = Paths.get(pymolPath).toRealPath().toString();
230         File path = new File(pymolPath);
231         // uncomment the next line to simulate Pymol not installed
232         // path = new File(pymolPath + "x");
233         if (!path.canExecute())
234         {
235           error += "File '" + path + "' does not exist.\n";
236           continue;
237         }
238         List<String> args = new ArrayList<>();
239         args.add(pymolPath);
240         args.add("-R"); // https://pymolwiki.org/index.php/RPC
241         ProcessBuilder pb = new ProcessBuilder(args);
242         pymolProcess = pb.start();
243         error = "";
244         break;
245       } catch (Exception e)
246       {
247         // pPymol could not be started using this path
248         error += e.getMessage();
249       }
250     }
251     if (error.length() == 0)
252     {
253       this.pymolXmlRpcPort = getPortNumber();
254       System.out.println(
255               "PyMOL XMLRPC started on port " + pymolXmlRpcPort);
256       return (pymolXmlRpcPort > 0);
257     }
258
259     // logger.warn(error);
260     return false;
261   }
262
263   private int getPortNumber()
264   {
265     // TODO pull up most of this!
266     int port = 0;
267     InputStream readChan = pymolProcess.getInputStream();
268     BufferedReader lineReader = new BufferedReader(
269             new InputStreamReader(readChan));
270     StringBuilder responses = new StringBuilder();
271     try
272     {
273       String response = lineReader.readLine();
274       while (response != null)
275       {
276         responses.append("\n" + response);
277         // expect: xml-rpc server running on host localhost, port 9123
278         if (response.contains("xml-rpc"))
279         {
280           String[] tokens = response.split(" ");
281           for (int i = 0; i < tokens.length - 1; i++)
282           {
283             if ("port".equals(tokens[i]))
284             {
285               port = Integer.parseInt(tokens[i + 1]);
286               break;
287             }
288           }
289         }
290         if (port > 0)
291         {
292           break; // hack for hanging readLine()
293         }
294         response = lineReader.readLine();
295       }
296     } catch (Exception e)
297     {
298       System.err.println(
299               "Failed to get REST port number from " + responses + ": "
300               + e.getMessage());
301       // logger.error("Failed to get REST port number from " + responses + ": "
302       // + e.getMessage());
303     } finally
304     {
305       try
306       {
307         lineReader.close();
308       } catch (IOException e2)
309       {
310       }
311     }
312     if (port == 0)
313     {
314       System.err.println("Failed to start PyMOL with XMLRPC, response was: "
315               + responses);
316     }
317     System.err.println("PyMOL started with XMLRPC on port " + port);
318     return port;
319   }
320
321 }