77ca01880862fd5bab0cd8f213ff23b6bbf38154
[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.bin.ArgParser.SubVal;
18 import jalview.datamodel.AlignmentAnnotation;
19 import jalview.datamodel.AlignmentI;
20 import jalview.datamodel.SequenceI;
21 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
22 import jalview.gui.AlignFrame;
23 import jalview.gui.AlignmentPanel;
24 import jalview.gui.Desktop;
25 import jalview.gui.StructureChooser;
26 import jalview.io.AppletFormatAdapter;
27 import jalview.io.DataSourceType;
28 import jalview.io.FileFormatException;
29 import jalview.io.FileFormatI;
30 import jalview.io.FileLoader;
31 import jalview.io.HtmlSvgOutput;
32 import jalview.io.IdentifyFile;
33 import jalview.structure.StructureImportSettings;
34 import jalview.structure.StructureImportSettings.TFType;
35 import jalview.util.HttpUtils;
36 import jalview.util.MessageManager;
37 import jalview.util.Platform;
38 import jalview.ws.dbsources.EBIAlfaFold;
39
40 public class Commands
41 {
42   Desktop desktop;
43
44   private static boolean headless;
45
46   private static ArgParser argParser;
47
48   private Map<String, AlignFrame> afMap;
49
50   public static void processArgs(ArgParser ap, boolean h)
51   {
52     argParser = ap;
53     headless = h;
54     if (argParser != null && argParser.linkedIds() != null)
55     {
56       for (String id : argParser.linkedIds())
57       {
58         Commands cmds = new Commands();
59         if (id == null)
60         {
61           cmds.processUnlinked(id);
62         }
63         else
64         {
65           cmds.processLinked(id);
66         }
67         cmds.processImages(id);
68       }
69
70       if (argParser.getBool(Arg.QUIT))
71       {
72         Jalview.getInstance().quit();
73       }
74     }
75   }
76
77   public Commands()
78   {
79     this(Desktop.instance);
80   }
81
82   public Commands(Desktop d)
83   {
84     this.desktop = d;
85     afMap = new HashMap<String, AlignFrame>();
86   }
87
88   protected void processUnlinked(String id)
89   {
90     processLinked(id);
91   }
92
93   protected void processLinked(String id)
94   {
95     Map<Arg, ArgValues> m = argParser.linkedArgs(id);
96
97     /*
98     // script to execute after all loading is completed one way or another
99     String groovyscript = m.get(Arg.GROOVY) == null ? null
100             : m.get(Arg.GROOVY).getValue();
101     String file = m.get(Arg.OPEN) == null ? null
102             : m.get(Arg.OPEN).getValue();
103     String data = null;
104     FileFormatI format = null;
105     DataSourceType protocol = null;
106     */
107
108     if (ArgParser.getArgValues(m, Arg.OPEN) != null)
109     {
110       long progress = -1;
111
112       boolean first = true;
113       AlignFrame af;
114       OPEN: for (String openFile : ArgParser.getValues(m, Arg.OPEN))
115       {
116         if (openFile == null)
117           continue OPEN;
118
119         if (first)
120         {
121           first = false;
122           if (!headless)
123           {
124             desktop.setProgressBar(
125                     MessageManager.getString(
126                             "status.processing_commandline_args"),
127                     progress = System.currentTimeMillis());
128           }
129         }
130
131         if (!Platform.isJS())
132         /**
133          * ignore in JavaScript -- can't just file existence - could load it?
134          * 
135          * @j2sIgnore
136          */
137         {
138           if (!HttpUtils.startsWithHttpOrHttps(openFile))
139           {
140             if (!(new File(openFile)).exists())
141             {
142               Console.warn("Can't find file '" + openFile + "'");
143               continue OPEN;
144             }
145           }
146         }
147
148         DataSourceType protocol = AppletFormatAdapter
149                 .checkProtocol(openFile);
150
151         FileFormatI format = null;
152         try
153         {
154           format = new IdentifyFile().identify(openFile, protocol);
155         } catch (FileFormatException e1)
156         {
157           Console.error("Unknown file format for '" + openFile + "'");
158         }
159
160         af = afMap.get(id);
161         if (af == null)
162         {
163           /*
164            * this approach isn't working yet
165           // get default annotations before opening AlignFrame
166           if (m.get(Arg.SSANNOTATION) != null)
167           {
168             Console.debug("***** SSANNOTATION="
169                     + m.get(Arg.SSANNOTATION).getBoolean());
170           }
171           if (m.get(Arg.NOTEMPFAC) != null)
172           {
173             Console.debug(
174                     "***** NOTEMPFAC=" + m.get(Arg.NOTEMPFAC).getBoolean());
175           }
176           boolean showSecondaryStructure = (m.get(Arg.SSANNOTATION) != null)
177                   ? m.get(Arg.SSANNOTATION).getBoolean()
178                   : false;
179           boolean showTemperatureFactor = (m.get(Arg.NOTEMPFAC) != null)
180                   ? !m.get(Arg.NOTEMPFAC).getBoolean()
181                   : false;
182           Console.debug("***** tempfac=" + showTemperatureFactor
183                   + ", showSS=" + showSecondaryStructure);
184           StructureSelectionManager ssm = StructureSelectionManager
185                   .getStructureSelectionManager(Desktop.instance);
186           if (ssm != null)
187           {
188             ssm.setAddTempFacAnnot(showTemperatureFactor);
189             ssm.setProcessSecondaryStructure(showSecondaryStructure);
190           }
191            */
192
193           // get kind of temperature factor annotation
194           StructureImportSettings.TFType tempfacType = TFType.DEFAULT;
195           if ((!ArgParser.getBoolean(m, Arg.NOTEMPFAC))
196                   && ArgParser.getArgValues(m, Arg.TEMPFAC) != null)
197           {
198             try
199             {
200               tempfacType = StructureImportSettings.TFType.valueOf(ArgParser
201                       .getValue(m, Arg.TEMPFAC).toUpperCase(Locale.ROOT));
202               Console.debug("Obtained Temperature Factor type of '"
203                       + tempfacType + "'");
204             } catch (IllegalArgumentException e)
205             {
206               // Just an error message!
207               StringBuilder sb = new StringBuilder().append("Cannot set --")
208                       .append(Arg.TEMPFAC.getName()).append(" to '")
209                       .append(tempfacType)
210                       .append("', ignoring.  Valid values are: ");
211               Iterator<StructureImportSettings.TFType> it = Arrays
212                       .stream(StructureImportSettings.TFType.values())
213                       .iterator();
214               while (it.hasNext())
215               {
216                 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
217                 if (it.hasNext())
218                   sb.append(", ");
219               }
220               Console.warn(sb.toString());
221             }
222           }
223
224           Console.debug(
225                   "Opening '" + openFile + "' in new alignment frame");
226           FileLoader fileLoader = new FileLoader(!headless);
227
228           StructureImportSettings.setTemperatureFactorType(tempfacType);
229
230           af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
231                   format);
232
233           // wrap alignment?
234           if (ArgParser.getBoolean(m, Arg.WRAP))
235           {
236             af.getCurrentView().setWrapAlignment(true);
237           }
238
239           // change alignment frame title
240           if (ArgParser.getValue(m, Arg.TITLE) != null)
241             af.setTitle(ArgParser.getValue(m, Arg.TITLE));
242
243           /* hacky approach to hiding the annotations */
244           // show secondary structure annotations?
245           if (ArgParser.getBoolean(m, Arg.SSANNOTATION))
246           {
247             // do this better (annotation types?)
248             AlignmentUtils.showOrHideSequenceAnnotations(
249                     af.getCurrentView().getAlignment(),
250                     Collections.singleton("Secondary Structure"), null,
251                     false, false);
252           }
253
254           // show temperature factor annotations?
255           if (ArgParser.getBoolean(m, Arg.NOTEMPFAC))
256           {
257             // do this better (annotation types?)
258             List<String> hideThese = new ArrayList<>();
259             hideThese.add("Temperature Factor");
260             hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
261             AlignmentUtils.showOrHideSequenceAnnotations(
262                     af.getCurrentView().getAlignment(), hideThese, null,
263                     false, false);
264           }
265           else
266           /* comment out hacky approach up to here and add this line:
267            if (showTemperatureFactor)
268              */
269           {
270             if (ArgParser.getValue(m, Arg.TEMPFAC_LABEL) != null)
271             {
272               AlignmentAnnotation aa = AlignmentUtils
273                       .getFirstSequenceAnnotationOfType(
274                               af.getCurrentView().getAlignment(),
275                               AlignmentAnnotation.LINE_GRAPH);
276               String label = ArgParser.getValue(m, Arg.TEMPFAC_LABEL);
277               if (aa != null)
278               {
279                 aa.label = label;
280               }
281               else
282               {
283                 Console.info(
284                         "Could not find annotation to apply tempfac_label '"
285                                 + label);
286               }
287             }
288           }
289
290           // store the AlignFrame for this id
291           afMap.put(id, af);
292         }
293         else
294         {
295           Console.debug(
296                   "Opening '" + openFile + "' in existing alignment frame");
297           af.getCurrentView().addFile(new File(openFile), format);
298         }
299
300         System.out
301                 .println("Command " + Arg.OPEN + " executed successfully!");
302
303       }
304       if (first) // first=true means nothing opened
305       {
306         if (headless)
307         {
308           Console.error("Could not open any files in headless mode");
309           System.exit(1);
310         }
311       }
312       else
313       {
314         Console.warn("No more files to open");
315         if (desktop != null)
316           desktop.setProgressBar(null, progress);
317       }
318
319     }
320
321     // load a pAE file if given
322     if (ArgParser.getValues(m, Arg.PAEMATRIX) != null)
323     {
324       AlignFrame af = afMap.get(id);
325       if (af != null)
326       {
327         for (String val : ArgParser.getValues(m, Arg.PAEMATRIX))
328         {
329           SubVal subVal = ArgParser.getSubVal(val);
330           File paeFile = new File(subVal.content);
331           if ("structid".equals(subVal.index))
332           {
333             EBIAlfaFold.addAlphaFoldPAEToStructure(
334                     af.getCurrentView().getAlignment(), paeFile,
335                     subVal.index, subVal.keyValue);
336           }
337           else
338           {
339             EBIAlfaFold.addAlphaFoldPAEToSequence(
340                     af.getCurrentView().getAlignment(), paeFile,
341                     subVal.index,
342                     "seqid".equals(subVal.keyName) ? subVal.keyValue
343                             : null);
344             // required to readjust the height and position of the pAE
345             // annotation
346           }
347           for (AlignmentViewPanel ap : af.getAlignPanels())
348           {
349             ap.adjustAnnotationHeight();
350           }
351         }
352       }
353     }
354
355     // open the structure (from same PDB file or given PDBfile)
356     if (!ArgParser.getBoolean(m, Arg.NOSTRUCTURE))
357     {
358       AlignFrame af = afMap.get(id);
359       if (ArgParser.getArgValues(m, Arg.STRUCTURE) != null)
360       {
361         STRUCTURE: for (String val : ArgParser.getValues(m, Arg.STRUCTURE))
362         {
363           SubVal subId = new SubVal(val);
364           SequenceI seq = getSpecifiedSequence(af, subId);
365           if (seq == null)
366           {
367             Console.warn("Could not find sequence for argument --"
368                     + Arg.STRUCTURE + "=" + val);
369             break STRUCTURE;
370           }
371           File structureFile = null;
372           if (subId.content != null && subId.content.length() != 0)
373           {
374             structureFile = new File(subId.content);
375             Console.debug("Using structure file (from argument) '"
376                     + structureFile.getAbsolutePath() + "'");
377           }
378           /* THIS DOESN'T WORK */
379           else if (seq.getAllPDBEntries() != null
380                   && seq.getAllPDBEntries().size() > 0)
381           {
382             structureFile = new File(
383                     seq.getAllPDBEntries().elementAt(0).getFile());
384             Console.debug("Using structure file (from sequence) '"
385                     + structureFile.getAbsolutePath() + "'");
386           }
387
388           if (structureFile == null)
389           {
390             Console.warn("Not provided structure file with '" + val + "'");
391             continue STRUCTURE;
392           }
393
394           if (!structureFile.exists())
395           {
396             Console.warn("Structure file '"
397                     + structureFile.getAbsoluteFile() + "' not found.");
398             continue STRUCTURE;
399           }
400
401           Console.debug("Using structure file "
402                   + structureFile.getAbsolutePath());
403
404           // open structure view
405           AlignmentPanel ap = af.alignPanel;
406           StructureChooser.openStructureFileForSequence(ap, seq,
407                   structureFile);
408         }
409       }
410     }
411   }
412
413   protected void processImages(String id)
414   {
415     Map<Arg, ArgValues> m = argParser.linkedArgs(id);
416     AlignFrame af = afMap.get(id);
417
418     if (af == null)
419     {
420       Console.warn("Did not have an alignment window for id=" + id);
421       return;
422     }
423
424     if (ArgParser.getValues(m, Arg.IMAGE) != null)
425     {
426       for (String val : ArgParser.getValues(m, Arg.IMAGE))
427       {
428         SubVal subVal = new SubVal(val);
429         String type = "png"; // default
430         String fileName = subVal.content;
431         File file = new File(fileName);
432         if ("type".equals(subVal.keyName))
433         {
434           type = subVal.keyValue;
435         }
436         else if (fileName != null)
437         {
438           for (String ext : new String[] { "svg", "png", "html" })
439           {
440             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
441             {
442               type = ext;
443             }
444           }
445         }
446         switch (type)
447         {
448         case "svg":
449           Console.debug("Outputting type '" + type + "' to " + fileName);
450           af.createSVG(file);
451           break;
452         case "png":
453           Console.debug("Outputting type '" + type + "' to " + fileName);
454           af.createPNG(file);
455           break;
456         case "html":
457           Console.debug("Outputting type '" + type + "' to " + fileName);
458           HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
459           htmlSVG.exportHTML(fileName);
460           break;
461         default:
462           Console.warn("--image type '" + type + "' not known. Ignoring");
463           break;
464         }
465       }
466     }
467   }
468
469   private SequenceI getSpecifiedSequence(AlignFrame af, SubVal subId)
470   {
471     AlignmentI al = af.getCurrentView().getAlignment();
472     if (-1 < subId.index && subId.index < al.getSequences().size())
473     {
474       return al.getSequenceAt(subId.index);
475     }
476     else if ("id".equals(subId.keyName))
477     {
478       return al.findName(subId.keyValue);
479     }
480     return null;
481   }
482 }