JAL-629 stray code deleted
[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.gui.AlignFrame;
19 import jalview.gui.Desktop;
20 import jalview.io.AppletFormatAdapter;
21 import jalview.io.DataSourceType;
22 import jalview.io.FileFormatException;
23 import jalview.io.FileFormatI;
24 import jalview.io.FileLoader;
25 import jalview.io.IdentifyFile;
26 import jalview.util.HttpUtils;
27 import jalview.util.MessageManager;
28 import jalview.util.Platform;
29 import jalview.ws.dbsources.EBIAlfaFold;
30
31 public class Commands
32 {
33   Desktop desktop;
34
35   private static boolean headless;
36
37   private static ArgParser argParser;
38
39   private Map<String, AlignFrame> afMap;
40
41   public static void processArgs(ArgParser ap, boolean h)
42   {
43     argParser = ap;
44     headless = h;
45     for (String id : argParser.linkedIds())
46     {
47       Commands cmds = new Commands();
48       if (id == null)
49       {
50         cmds.processUnlinked(id);
51       }
52       else
53       {
54         cmds.processLinked(id);
55       }
56     }
57   }
58
59   public Commands()
60   {
61     this(Desktop.instance);
62   }
63
64   public Commands(Desktop d)
65   {
66     this.desktop = d;
67     afMap = new HashMap<String, AlignFrame>();
68   }
69
70   protected void processUnlinked(String id)
71   {
72     processLinked(id);
73   }
74
75   protected void processLinked(String id)
76   {
77     Map<Arg, ArgValues> m = argParser.linkedArgs(id);
78
79     /*
80     // script to execute after all loading is completed one way or another
81     String groovyscript = m.get(Arg.GROOVY) == null ? null
82             : m.get(Arg.GROOVY).getValue();
83     String file = m.get(Arg.OPEN) == null ? null
84             : m.get(Arg.OPEN).getValue();
85     String data = null;
86     FileFormatI format = null;
87     DataSourceType protocol = null;
88     */
89
90     if (m.get(Arg.OPEN) != null)
91     {
92       long progress = -1;
93
94       boolean first = true;
95       AlignFrame af;
96       OPEN: for (String openFile : m.get(Arg.OPEN).getValues())
97       {
98         if (openFile == null)
99           continue OPEN;
100
101         if (first)
102         {
103           first = false;
104           if (!headless)
105           {
106             desktop.setProgressBar(
107                     MessageManager.getString(
108                             "status.processing_commandline_args"),
109                     progress = System.currentTimeMillis());
110           }
111         }
112
113         if (!Platform.isJS())
114         /**
115          * ignore in JavaScript -- can't just file existence - could load it?
116          * 
117          * @j2sIgnore
118          */
119         {
120           if (!HttpUtils.startsWithHttpOrHttps(openFile))
121           {
122             if (!(new File(openFile)).exists())
123             {
124               Console.warn("Can't find file '" + openFile + "'");
125               continue OPEN;
126             }
127           }
128         }
129
130         DataSourceType protocol = AppletFormatAdapter
131                 .checkProtocol(openFile);
132
133         FileFormatI format = null;
134         try
135         {
136           format = new IdentifyFile().identify(openFile, protocol);
137         } catch (FileFormatException e1)
138         {
139           Console.error("Unknown file format for '" + openFile + "'");
140         }
141
142         af = afMap.get(id);
143         if (af == null)
144         {
145           // get kind of temperature factor annotation
146           AlignmentAnnotation.TFType tempfacType = null;
147           if ((m.get(Arg.NOTEMPFAC) == null
148                   || !m.get(Arg.NOTEMPFAC).getBoolean())
149                   && m.get(Arg.TEMPFAC) != null)
150           {
151             try
152             {
153               tempfacType = AlignmentAnnotation.TFType
154                       .valueOf(m.get(Arg.TEMPFAC).getValue()
155                               .toUpperCase(Locale.ROOT));
156               Console.debug("Obtained Temperature Factor type of '"
157                       + tempfacType + "'");
158             } catch (IllegalArgumentException e)
159             {
160               StringBuilder sb = new StringBuilder().append("Cannot set --")
161                       .append(Arg.TEMPFAC.getName()).append(" to '")
162                       .append(tempfacType)
163                       .append("', ignoring.  Valid values are: ");
164               Iterator<AlignmentAnnotation.TFType> it = Arrays
165                       .stream(AlignmentAnnotation.TFType.values())
166                       .iterator();
167               while (it.hasNext())
168               {
169                 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
170                 if (it.hasNext())
171                   sb.append(", ");
172               }
173               Console.warn(sb.toString());
174             }
175           }
176
177           Console.debug(
178                   "Opening '" + openFile + "' in new alignment frame");
179           FileLoader fileLoader = new FileLoader(!headless);
180           af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol, format,
181                   tempfacType);
182
183           // wrap alignment?
184           if (m.get(Arg.WRAP) != null && m.get(Arg.WRAP).getBoolean())
185           {
186             af.getCurrentView().setWrapAlignment(true);
187           }
188
189           // change alignment frame title
190           if (m.get(Arg.TITLE) != null)
191             af.setTitle(m.get(Arg.TITLE).getValue());
192
193           // show secondary structure annotations?
194           if (m.get(Arg.SSANNOTATION) != null
195                   && !m.get(Arg.SSANNOTATION).getBoolean())
196           {
197             // do this better (annotation types?)
198             AlignmentUtils.showOrHideSequenceAnnotations(
199                     af.getCurrentView().getAlignment(),
200                     Collections.singleton("Secondary Structure"), null,
201                     false, false);
202           }
203
204           // show temperature factor annotations?
205           if (m.get(Arg.NOTEMPFAC) != null
206                   && m.get(Arg.NOTEMPFAC).getBoolean())
207           {
208             // do this better (annotation types?)
209             List<String> hideThese = new ArrayList<>();
210             hideThese.add("Temperature Factor");
211             hideThese.add(MessageManager
212                     .getString("label.alphafold_reliability"));
213             AlignmentUtils.showOrHideSequenceAnnotations(
214                     af.getCurrentView().getAlignment(), hideThese, null,
215                     false, false);
216           }
217           else
218           {
219             if (m.get(Arg.TEMPFAC_LABEL) != null)
220             {
221               AlignmentAnnotation aa = AlignmentUtils
222                       .getFirstSequenceAnnotationOfType(
223                               af.getCurrentView().getAlignment(),
224                               AlignmentAnnotation.LINE_GRAPH);
225               if (aa != null)
226               {
227                 aa.label = m.get(Arg.TEMPFAC_LABEL).getValue();
228               }
229             }
230           }
231
232           // store the AlignFrame for this id
233           afMap.put(id, af);
234         }
235         else
236         {
237           Console.debug(
238                   "Opening '" + openFile + "' in existing alignment frame");
239           af.getCurrentView().addFile(new File(openFile), format);
240         }
241
242         System.out
243                 .println("Command " + Arg.OPEN + " executed successfully!");
244
245       }
246       if (first) // first=true means nothing opened
247       {
248         if (headless)
249         {
250           Console.error("Could not open any files in headless mode");
251           System.exit(1);
252         }
253       }
254       else
255       {
256         Console.warn("No more files to open");
257         if (desktop != null)
258           desktop.setProgressBar(null, progress);
259       }
260
261     }
262
263     // load a pAE file if given
264     if (m.get(Arg.PAEMATRIX) != null)
265     {
266       AlignFrame af = afMap.get(id);
267       if (af != null)
268       {
269         for (String val : m.get(Arg.PAEMATRIX).getValues())
270         {
271           SubId subId = new SubId(val);
272           File paeFile = new File(subId.content);
273           EBIAlfaFold.addAlphaFoldPAE(af.getCurrentView().getAlignment(),
274                   paeFile, subId.index,
275                   "id".equals(subId.keyName) ? subId.keyValue : null);
276           // required to readjust the height and position of the pAE
277           // annotation
278           for (AlignmentViewPanel ap : af.getAlignPanels())
279           {
280             ap.adjustAnnotationHeight();
281           }
282         }
283       }
284     }
285   }
286
287   /**
288    * A helper class to parse a string of the possible forms "content"
289    * "[index]content", "[keyName=keyValue]content" and return the integer index,
290    * the strings keyName and keyValue, and the content after the square brackets
291    * (if present). Values not set will be -1 or null.
292    */
293   protected class SubId
294   {
295     protected int index = 0;
296
297     protected String keyName = null;
298
299     protected String keyValue = null;
300
301     protected String content = null;
302
303     protected SubId(String item)
304     {
305       if (item.indexOf('[') == 0 && item.indexOf(']') > 1)
306       {
307         int openBracket = item.indexOf('[');
308         int closeBracket = item.indexOf(']');
309         String indexString = item.substring(openBracket + 1, closeBracket);
310         this.content = item.substring(closeBracket + 1);
311         int equals = indexString.indexOf('=');
312         if (equals > -1)
313         {
314           this.keyName = indexString.substring(0, equals);
315           this.keyValue = indexString.substring(equals + 1);
316           this.index = -1;
317         }
318         else
319         {
320           try
321           {
322             this.index = Integer.parseInt(indexString);
323           } catch (NumberFormatException e)
324           {
325             Console.warn("Failed to obtain sequenced id or index from '"
326                     + item + "'. Setting index=0 and using content='"
327                     + content + "'.");
328           }
329         }
330       }
331       else
332       {
333         this.content = item;
334       }
335     }
336   }
337 }