JAL-629 Open Structure Viewer from cmdline
[jalview.git] / src / jalview / bin / Commands.java
1 package jalview.bin;
2
3 import java.io.File;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.Collections;
7 import java.util.HashMap;
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.Locale;
11 import java.util.Map;
12
13 import jalview.analysis.AlignmentUtils;
14 import jalview.api.AlignmentViewPanel;
15 import jalview.bin.ArgParser.Arg;
16 import jalview.bin.ArgParser.ArgValues;
17 import jalview.datamodel.AlignmentAnnotation;
18 import jalview.datamodel.SequenceI;
19 import jalview.gui.AlignFrame;
20 import jalview.gui.AlignmentPanel;
21 import jalview.gui.Desktop;
22 import jalview.gui.StructureChooser;
23 import jalview.io.AppletFormatAdapter;
24 import jalview.io.DataSourceType;
25 import jalview.io.FileFormatException;
26 import jalview.io.FileFormatI;
27 import jalview.io.FileLoader;
28 import jalview.io.IdentifyFile;
29 import jalview.util.HttpUtils;
30 import jalview.util.MessageManager;
31 import jalview.util.Platform;
32 import jalview.ws.dbsources.EBIAlfaFold;
33
34 public class Commands
35 {
36   Desktop desktop;
37
38   private static boolean headless;
39
40   private static ArgParser argParser;
41
42   private Map<String, AlignFrame> afMap;
43
44   public static void processArgs(ArgParser ap, boolean h)
45   {
46     argParser = ap;
47     headless = h;
48     if (argParser != null && argParser.linkedIds() != null)
49     {
50       for (String id : argParser.linkedIds())
51       {
52         Commands cmds = new Commands();
53         if (id == null)
54         {
55           cmds.processUnlinked(id);
56         }
57         else
58         {
59           cmds.processLinked(id);
60         }
61       }
62     }
63   }
64
65   public Commands()
66   {
67     this(Desktop.instance);
68   }
69
70   public Commands(Desktop d)
71   {
72     this.desktop = d;
73     afMap = new HashMap<String, AlignFrame>();
74   }
75
76   protected void processUnlinked(String id)
77   {
78     processLinked(id);
79   }
80
81   protected void processLinked(String id)
82   {
83     Map<Arg, ArgValues> m = argParser.linkedArgs(id);
84
85     /*
86     // script to execute after all loading is completed one way or another
87     String groovyscript = m.get(Arg.GROOVY) == null ? null
88             : m.get(Arg.GROOVY).getValue();
89     String file = m.get(Arg.OPEN) == null ? null
90             : m.get(Arg.OPEN).getValue();
91     String data = null;
92     FileFormatI format = null;
93     DataSourceType protocol = null;
94     */
95
96     if (m.get(Arg.OPEN) != null)
97     {
98       long progress = -1;
99
100       boolean first = true;
101       AlignFrame af;
102       OPEN: for (String openFile : m.get(Arg.OPEN).getValues())
103       {
104         if (openFile == null)
105           continue OPEN;
106
107         if (first)
108         {
109           first = false;
110           if (!headless)
111           {
112             desktop.setProgressBar(
113                     MessageManager.getString(
114                             "status.processing_commandline_args"),
115                     progress = System.currentTimeMillis());
116           }
117         }
118
119         if (!Platform.isJS())
120         /**
121          * ignore in JavaScript -- can't just file existence - could load it?
122          * 
123          * @j2sIgnore
124          */
125         {
126           if (!HttpUtils.startsWithHttpOrHttps(openFile))
127           {
128             if (!(new File(openFile)).exists())
129             {
130               Console.warn("Can't find file '" + openFile + "'");
131               continue OPEN;
132             }
133           }
134         }
135
136         DataSourceType protocol = AppletFormatAdapter
137                 .checkProtocol(openFile);
138
139         FileFormatI format = null;
140         try
141         {
142           format = new IdentifyFile().identify(openFile, protocol);
143         } catch (FileFormatException e1)
144         {
145           Console.error("Unknown file format for '" + openFile + "'");
146         }
147
148         af = afMap.get(id);
149         if (af == null)
150         {
151           // get kind of temperature factor annotation
152           AlignmentAnnotation.TFType tempfacType = null;
153           if ((m.get(Arg.NOTEMPFAC) == null
154                   || !m.get(Arg.NOTEMPFAC).getBoolean())
155                   && m.get(Arg.TEMPFAC) != null)
156           {
157             try
158             {
159               tempfacType = AlignmentAnnotation.TFType
160                       .valueOf(m.get(Arg.TEMPFAC).getValue()
161                               .toUpperCase(Locale.ROOT));
162               Console.debug("Obtained Temperature Factor type of '"
163                       + tempfacType + "'");
164             } catch (IllegalArgumentException e)
165             {
166               StringBuilder sb = new StringBuilder().append("Cannot set --")
167                       .append(Arg.TEMPFAC.getName()).append(" to '")
168                       .append(tempfacType)
169                       .append("', ignoring.  Valid values are: ");
170               Iterator<AlignmentAnnotation.TFType> it = Arrays
171                       .stream(AlignmentAnnotation.TFType.values())
172                       .iterator();
173               while (it.hasNext())
174               {
175                 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
176                 if (it.hasNext())
177                   sb.append(", ");
178               }
179               Console.warn(sb.toString());
180             }
181           }
182
183           Console.debug(
184                   "Opening '" + openFile + "' in new alignment frame");
185           FileLoader fileLoader = new FileLoader(!headless);
186           af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol, format,
187                   tempfacType);
188
189           // wrap alignment?
190           if (m.get(Arg.WRAP) != null && m.get(Arg.WRAP).getBoolean())
191           {
192             af.getCurrentView().setWrapAlignment(true);
193           }
194
195           // change alignment frame title
196           if (m.get(Arg.TITLE) != null)
197             af.setTitle(m.get(Arg.TITLE).getValue());
198
199           // show secondary structure annotations?
200           if (m.get(Arg.SSANNOTATION) != null
201                   && !m.get(Arg.SSANNOTATION).getBoolean())
202           {
203             // do this better (annotation types?)
204             AlignmentUtils.showOrHideSequenceAnnotations(
205                     af.getCurrentView().getAlignment(),
206                     Collections.singleton("Secondary Structure"), null,
207                     false, false);
208           }
209
210           // show temperature factor annotations?
211           if (m.get(Arg.NOTEMPFAC) != null
212                   && m.get(Arg.NOTEMPFAC).getBoolean())
213           {
214             // do this better (annotation types?)
215             List<String> hideThese = new ArrayList<>();
216             hideThese.add("Temperature Factor");
217             hideThese.add(MessageManager
218                     .getString("label.alphafold_reliability"));
219             AlignmentUtils.showOrHideSequenceAnnotations(
220                     af.getCurrentView().getAlignment(), hideThese, null,
221                     false, false);
222           }
223           else
224           {
225             if (m.get(Arg.TEMPFAC_LABEL) != null)
226             {
227               AlignmentAnnotation aa = AlignmentUtils
228                       .getFirstSequenceAnnotationOfType(
229                               af.getCurrentView().getAlignment(),
230                               AlignmentAnnotation.LINE_GRAPH);
231               if (aa != null)
232               {
233                 aa.label = m.get(Arg.TEMPFAC_LABEL).getValue();
234               }
235             }
236           }
237
238           // store the AlignFrame for this id
239           afMap.put(id, af);
240         }
241         else
242         {
243           Console.debug(
244                   "Opening '" + openFile + "' in existing alignment frame");
245           af.getCurrentView().addFile(new File(openFile), format);
246         }
247
248         System.out
249                 .println("Command " + Arg.OPEN + " executed successfully!");
250
251       }
252       if (first) // first=true means nothing opened
253       {
254         if (headless)
255         {
256           Console.error("Could not open any files in headless mode");
257           System.exit(1);
258         }
259       }
260       else
261       {
262         Console.warn("No more files to open");
263         if (desktop != null)
264           desktop.setProgressBar(null, progress);
265       }
266
267     }
268
269     // load a pAE file if given
270     if (m.get(Arg.PAEMATRIX) != null)
271     {
272       AlignFrame af = afMap.get(id);
273       if (af != null)
274       {
275         for (String val : m.get(Arg.PAEMATRIX).getValues())
276         {
277           SubId subId = new SubId(val);
278           File paeFile = new File(subId.content);
279           EBIAlfaFold.addAlphaFoldPAE(af.getCurrentView().getAlignment(),
280                   paeFile, subId.index,
281                   "id".equals(subId.keyName) ? subId.keyValue : null);
282           // required to readjust the height and position of the pAE
283           // annotation
284           for (AlignmentViewPanel ap : af.getAlignPanels())
285           {
286             ap.adjustAnnotationHeight();
287           }
288         }
289       }
290     }
291
292     // open the structure (from same PDB file or given PDBfile)
293     if (m.get(Arg.NOSTRUCTURE) == null
294             || !m.get(Arg.NOQUESTIONNAIRE).getBoolean())
295     {
296       AlignFrame af = afMap.get(id);
297       if (m.get(Arg.STRUCTURE) != null)
298       {
299         STRUCTURE: for (String val : m.get(Arg.STRUCTURE).getValues())
300         {
301           SubId subId = new SubId(val);
302           SequenceI seq = getSpecifiedSequence(af, subId);
303           if (seq == null)
304           {
305             Console.warn("Could not find sequence for argument --"
306                     + Arg.STRUCTURE + "=" + val);
307             break STRUCTURE;
308           }
309           File structureFile = null;
310           if (subId.content != null && subId.content.length() != 0)
311           {
312             structureFile = new File(subId.content);
313             Console.debug("Using structure file (from argument) '"
314                     + structureFile.getAbsolutePath() + "'");
315           }
316           /* THIS DOESN'T WORK */
317           else if (seq.getAllPDBEntries() != null
318                   && seq.getAllPDBEntries().size() > 0)
319           {
320             structureFile = new File(
321                     seq.getAllPDBEntries().elementAt(0).getFile());
322             Console.debug("Using structure file (from sequence) '"
323                     + structureFile.getAbsolutePath() + "'");
324           }
325
326           if (structureFile == null)
327           {
328             Console.warn("Not provided structure file with '" + val + "'");
329             continue STRUCTURE;
330           }
331
332           if (!structureFile.exists())
333           {
334             Console.warn("Structure file '"
335                     + structureFile.getAbsoluteFile() + "' not found.");
336             continue STRUCTURE;
337           }
338
339           Console.debug("Using structure file "
340                   + structureFile.getAbsolutePath());
341
342           // open structure view
343           AlignmentPanel ap = af.alignPanel;
344           StructureChooser.openStructureFileForSequence(ap, seq,
345                   structureFile);
346         }
347       }
348     }
349   }
350
351   private SequenceI getSpecifiedSequence(AlignFrame af, SubId subId)
352   {
353     SequenceI seq = null;
354     SequenceI[] sequences = af.getCurrentView().getAlignment()
355             .getSequencesArray();
356     if (-1 < subId.index && subId.index < sequences.length)
357     {
358       seq = sequences[subId.index];
359     }
360     else if ("id".equals(subId.keyName))
361     {
362       for (SequenceI s : sequences)
363       {
364         if (s.getDisplayId(false).equals(subId.keyValue))
365         {
366           seq = s;
367           break;
368         }
369       }
370     }
371     return seq;
372   }
373
374   /**
375    * A helper class to parse a string of the possible forms "content"
376    * "[index]content", "[keyName=keyValue]content" and return the integer index,
377    * the strings keyName and keyValue, and the content after the square brackets
378    * (if present). Values not set will be -1 or null.
379    */
380   protected class SubId
381   {
382     protected int index = 0;
383
384     protected String keyName = null;
385
386     protected String keyValue = null;
387
388     protected String content = null;
389
390     protected SubId(String item)
391     {
392       if (item.indexOf('[') == 0 && item.indexOf(']') > 1)
393       {
394         int openBracket = item.indexOf('[');
395         int closeBracket = item.indexOf(']');
396         String indexString = item.substring(openBracket + 1, closeBracket);
397         this.content = item.substring(closeBracket + 1);
398         int equals = indexString.indexOf('=');
399         if (equals > -1)
400         {
401           this.keyName = indexString.substring(0, equals);
402           this.keyValue = indexString.substring(equals + 1);
403           this.index = -1;
404         }
405         else
406         {
407           try
408           {
409             this.index = Integer.parseInt(indexString);
410           } catch (NumberFormatException e)
411           {
412             Console.warn("Failed to obtain sequenced id or index from '"
413                     + item + "'. Setting index=0 and using content='"
414                     + content + "'.");
415           }
416         }
417       }
418       else
419       {
420         this.content = item;
421       }
422     }
423   }
424 }