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