JAL-629 refactoring TFType. Remove i18n identification of annotation.
[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(af.getCurrentView().getAlignment(),
340                     paeFile, subVal.index,
341                     "id".equals(subVal.keyName) ? subVal.keyValue : null);
342             // required to readjust the height and position of the pAE
343             // annotation
344           }
345           for (AlignmentViewPanel ap : af.getAlignPanels())
346           {
347             ap.adjustAnnotationHeight();
348           }
349         }
350       }
351     }
352
353     // open the structure (from same PDB file or given PDBfile)
354     if (!ArgParser.getBoolean(m, Arg.NOSTRUCTURE))
355     {
356       AlignFrame af = afMap.get(id);
357       if (ArgParser.getArgValues(m, Arg.STRUCTURE) != null)
358       {
359         STRUCTURE: for (String val : ArgParser.getValues(m, Arg.STRUCTURE))
360         {
361           SubVal subId = new SubVal(val);
362           SequenceI seq = getSpecifiedSequence(af, subId);
363           if (seq == null)
364           {
365             Console.warn("Could not find sequence for argument --"
366                     + Arg.STRUCTURE + "=" + val);
367             break STRUCTURE;
368           }
369           File structureFile = null;
370           if (subId.content != null && subId.content.length() != 0)
371           {
372             structureFile = new File(subId.content);
373             Console.debug("Using structure file (from argument) '"
374                     + structureFile.getAbsolutePath() + "'");
375           }
376           /* THIS DOESN'T WORK */
377           else if (seq.getAllPDBEntries() != null
378                   && seq.getAllPDBEntries().size() > 0)
379           {
380             structureFile = new File(
381                     seq.getAllPDBEntries().elementAt(0).getFile());
382             Console.debug("Using structure file (from sequence) '"
383                     + structureFile.getAbsolutePath() + "'");
384           }
385
386           if (structureFile == null)
387           {
388             Console.warn("Not provided structure file with '" + val + "'");
389             continue STRUCTURE;
390           }
391
392           if (!structureFile.exists())
393           {
394             Console.warn("Structure file '"
395                     + structureFile.getAbsoluteFile() + "' not found.");
396             continue STRUCTURE;
397           }
398
399           Console.debug("Using structure file "
400                   + structureFile.getAbsolutePath());
401
402           // open structure view
403           AlignmentPanel ap = af.alignPanel;
404           StructureChooser.openStructureFileForSequence(ap, seq,
405                   structureFile);
406         }
407       }
408     }
409   }
410
411   protected void processImages(String id)
412   {
413     Map<Arg, ArgValues> m = argParser.linkedArgs(id);
414     AlignFrame af = afMap.get(id);
415
416     if (af == null)
417     {
418       Console.warn("Did not have an alignment window for id=" + id);
419       return;
420     }
421
422     if (ArgParser.getValues(m, Arg.IMAGE) != null)
423     {
424       for (String val : ArgParser.getValues(m, Arg.IMAGE))
425       {
426         SubVal subVal = new SubVal(val);
427         String type = "png"; // default
428         String fileName = subVal.content;
429         File file = new File(fileName);
430         if ("type".equals(subVal.keyName))
431         {
432           type = subVal.keyValue;
433         }
434         else if (fileName != null)
435         {
436           for (String ext : new String[] { "svg", "png", "html" })
437           {
438             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
439             {
440               type = ext;
441             }
442           }
443         }
444         switch (type)
445         {
446         case "svg":
447           Console.debug("Outputting type '" + type + "' to " + fileName);
448           af.createSVG(file);
449           break;
450         case "png":
451           Console.debug("Outputting type '" + type + "' to " + fileName);
452           af.createPNG(file);
453           break;
454         case "html":
455           Console.debug("Outputting type '" + type + "' to " + fileName);
456           HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
457           htmlSVG.exportHTML(fileName);
458           break;
459         default:
460           Console.warn("--image type '" + type + "' not known. Ignoring");
461           break;
462         }
463       }
464     }
465   }
466
467   private SequenceI getSpecifiedSequence(AlignFrame af, SubVal subId)
468   {
469     AlignmentI al = af.getCurrentView().getAlignment();
470     if (-1 < subId.index && subId.index < al.getSequences().size())
471     {
472       return al.getSequenceAt(subId.index);
473     }
474     else if ("id".equals(subId.keyName))
475     {
476       return al.findName(subId.keyValue);
477     }
478     return null;
479   }
480 }