JAL-629 removed debug prints. added .cif. added some comments/code-markers
[jalview.git] / src / jalview / bin / Commands.java
1 package jalview.bin;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7 import java.util.Collections;
8 import java.util.HashMap;
9 import java.util.Iterator;
10 import java.util.List;
11 import java.util.Locale;
12 import java.util.Map;
13
14 import jalview.analysis.AlignmentUtils;
15 import jalview.api.AlignmentViewPanel;
16 import jalview.bin.ArgParser.Arg;
17 import jalview.bin.ArgParser.ArgValue;
18 import jalview.bin.ArgParser.ArgValuesMap;
19 import jalview.bin.ArgParser.SubVals;
20 import jalview.datamodel.AlignmentAnnotation;
21 import jalview.datamodel.AlignmentI;
22 import jalview.datamodel.SequenceI;
23 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
24 import jalview.gui.AlignFrame;
25 import jalview.gui.AlignmentPanel;
26 import jalview.gui.Desktop;
27 import jalview.gui.StructureChooser;
28 import jalview.io.AppletFormatAdapter;
29 import jalview.io.DataSourceType;
30 import jalview.io.FileFormatException;
31 import jalview.io.FileFormatI;
32 import jalview.io.FileLoader;
33 import jalview.io.HtmlSvgOutput;
34 import jalview.io.IdentifyFile;
35 import jalview.schemes.AnnotationColourGradient;
36 import jalview.structure.StructureImportSettings;
37 import jalview.structure.StructureImportSettings.TFType;
38 import jalview.structure.StructureSelectionManager;
39 import jalview.util.HttpUtils;
40 import jalview.util.MessageManager;
41 import jalview.util.Platform;
42 import jalview.ws.dbsources.EBIAlfaFold;
43 import mc_view.PDBChain;
44
45 public class Commands
46 {
47   Desktop desktop;
48
49   private static boolean headless;
50
51   private static ArgParser argParser;
52
53   private Map<String, AlignFrame> afMap;
54
55   public static boolean processArgs(ArgParser ap, boolean h)
56   {
57     argParser = ap;
58     headless = h;
59     boolean argsWereParsed = false;
60     if (headless)
61     {
62       System.setProperty("java.awt.headless", "true");
63     }
64
65     if (argParser != null && argParser.linkedIds() != null)
66     {
67       for (String id : argParser.linkedIds())
68       {
69         Commands cmds = new Commands();
70         if (id == null)
71         {
72           cmds.processUnlinked(id);
73         }
74         else
75         {
76           cmds.processLinked(id);
77         }
78         cmds.processImages(id);
79         argsWereParsed |= cmds.wereParsed();
80       }
81
82     }
83     if (argParser.getBool(Arg.QUIT))
84     {
85       Jalview.getInstance().quit();
86       return true;
87     }
88     // carry on with jalview.bin.Jalview
89     return argsWereParsed;
90   }
91
92   boolean argsWereParsed = false;
93
94   private boolean wereParsed()
95   {
96     return argsWereParsed;
97   }
98
99   public Commands()
100   {
101     this(Desktop.instance);
102   }
103
104   public Commands(Desktop d)
105   {
106     this.desktop = d;
107     afMap = new HashMap<String, AlignFrame>();
108   }
109
110   protected void processUnlinked(String id)
111   {
112     ArgValuesMap avm = new ArgValuesMap(argParser.linkedArgs(id));
113
114     processLinked(id);
115   }
116
117   protected void processLinked(String id)
118   {
119     ArgValuesMap avm = new ArgValuesMap(argParser.linkedArgs(id));
120
121     /*
122     // script to execute after all loading is completed one way or another
123     String groovyscript = m.get(Arg.GROOVY) == null ? null
124             : m.get(Arg.GROOVY).getValue();
125     String file = m.get(Arg.OPEN) == null ? null
126             : m.get(Arg.OPEN).getValue();
127     String data = null;
128     FileFormatI format = null;
129     DataSourceType protocol = null;
130     */
131     if (avm.hasValue(Arg.OPEN))
132     {
133       long progress = -1;
134
135       boolean first = true;
136       AlignFrame af;
137       for (ArgValue av : avm.getArgValueList(Arg.OPEN))
138       {
139         String openFile = av.getValue();
140         if (openFile == null)
141           continue;
142
143         argsWereParsed = true;
144         if (first)
145         {
146           first = false;
147           if (!headless)
148           {
149             desktop.setProgressBar(
150                     MessageManager.getString(
151                             "status.processing_commandline_args"),
152                     progress = System.currentTimeMillis());
153           }
154         }
155
156         if (!Platform.isJS())
157         /**
158          * ignore in JavaScript -- can't just file existence - could load it?
159          * 
160          * @j2sIgnore
161          */
162         {
163           if (!HttpUtils.startsWithHttpOrHttps(openFile))
164           {
165             if (!(new File(openFile)).exists())
166             {
167               Console.warn("Can't find file '" + openFile + "'");
168             }
169           }
170         }
171
172         DataSourceType protocol = AppletFormatAdapter
173                 .checkProtocol(openFile);
174
175         FileFormatI format = null;
176         try
177         {
178           format = new IdentifyFile().identify(openFile, protocol);
179         } catch (FileFormatException e1)
180         {
181           Console.error("Unknown file format for '" + openFile + "'");
182         }
183
184         af = afMap.get(id);
185         if (af == null)
186         {
187           /*
188            * this approach isn't working yet
189           // get default annotations before opening AlignFrame
190           if (m.get(Arg.SSANNOTATION) != null)
191           {
192             Console.debug("***** SSANNOTATION="
193                     + m.get(Arg.SSANNOTATION).getBoolean());
194           }
195           if (m.get(Arg.NOTEMPFAC) != null)
196           {
197             Console.debug(
198                     "***** NOTEMPFAC=" + m.get(Arg.NOTEMPFAC).getBoolean());
199           }
200           boolean showSecondaryStructure = (m.get(Arg.SSANNOTATION) != null)
201                   ? m.get(Arg.SSANNOTATION).getBoolean()
202                   : false;
203           boolean showTemperatureFactor = (m.get(Arg.NOTEMPFAC) != null)
204                   ? !m.get(Arg.NOTEMPFAC).getBoolean()
205                   : false;
206           Console.debug("***** tempfac=" + showTemperatureFactor
207                   + ", showSS=" + showSecondaryStructure);
208           StructureSelectionManager ssm = StructureSelectionManager
209                   .getStructureSelectionManager(Desktop.instance);
210           if (ssm != null)
211           {
212             ssm.setAddTempFacAnnot(showTemperatureFactor);
213             ssm.setProcessSecondaryStructure(showSecondaryStructure);
214           }
215            */
216
217           // get kind of temperature factor annotation
218           StructureImportSettings.TFType tempfacType = TFType.DEFAULT;
219           if ((!avm.getBoolean(Arg.NOTEMPFAC)) && avm.hasValue(Arg.TEMPFAC))
220           {
221             try
222             {
223               tempfacType = StructureImportSettings.TFType
224                       .valueOf(avm.getArgValue(Arg.TEMPFAC).getValue()
225                               .toUpperCase(Locale.ROOT));
226               Console.debug("Obtained Temperature Factor type of '"
227                       + tempfacType + "'");
228             } catch (IllegalArgumentException e)
229             {
230               // Just an error message!
231               StringBuilder sb = new StringBuilder().append("Cannot set --")
232                       .append(Arg.TEMPFAC.getName()).append(" to '")
233                       .append(tempfacType)
234                       .append("', ignoring.  Valid values are: ");
235               Iterator<StructureImportSettings.TFType> it = Arrays
236                       .stream(StructureImportSettings.TFType.values())
237                       .iterator();
238               while (it.hasNext())
239               {
240                 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
241                 if (it.hasNext())
242                   sb.append(", ");
243               }
244               Console.warn(sb.toString());
245             }
246           }
247
248           Console.debug(
249                   "Opening '" + openFile + "' in new alignment frame");
250           FileLoader fileLoader = new FileLoader(!headless);
251
252           StructureImportSettings.setTemperatureFactorType(tempfacType);
253
254           af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
255                   format);
256
257           // wrap alignment?
258           if (avm.getBoolean(Arg.WRAP))
259           {
260             af.getCurrentView().setWrapAlignment(true);
261           }
262
263           // colour aligment?
264           if (avm.hasValue(Arg.COLOUR))
265           {
266             af.changeColour_actionPerformed(avm.getValue(Arg.COLOUR));
267           }
268
269           // change alignment frame title
270           if (avm.hasValue(Arg.TITLE))
271             af.setTitle(avm.getValue(Arg.TITLE));
272
273           /* hacky approach to hiding the annotations */
274           // show secondary structure annotations?
275           if (avm.getBoolean(Arg.SSANNOTATION))
276           {
277             // do this better (annotation types?)
278             AlignmentUtils.showOrHideSequenceAnnotations(
279                     af.getCurrentView().getAlignment(),
280                     Collections.singleton("Secondary Structure"), null,
281                     false, false);
282           }
283
284           // show temperature factor annotations?
285           if (avm.getBoolean(Arg.NOTEMPFAC))
286           {
287             // do this better (annotation types?)
288             List<String> hideThese = new ArrayList<>();
289             hideThese.add("Temperature Factor");
290             hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
291             AlignmentUtils.showOrHideSequenceAnnotations(
292                     af.getCurrentView().getAlignment(), hideThese, null,
293                     false, false);
294           }
295           else
296           /* comment out hacky approach up to here and add this line:
297            if (showTemperatureFactor)
298              */
299           {
300             if (avm.hasValue(Arg.TEMPFAC_LABEL))
301             {
302               AlignmentAnnotation aa = AlignmentUtils
303                       .getFirstSequenceAnnotationOfType(
304                               af.getCurrentView().getAlignment(),
305                               AlignmentAnnotation.LINE_GRAPH);
306               String label = avm.getValue(Arg.TEMPFAC_LABEL);
307               if (aa != null)
308               {
309                 aa.label = label;
310               }
311               else
312               {
313                 Console.info(
314                         "Could not find annotation to apply tempfac_label '"
315                                 + label);
316               }
317             }
318           }
319
320           // store the AlignFrame for this id
321           afMap.put(id, af);
322
323           // is it its own structure file?
324           if (format.isStructureFile())
325           {
326             StructureSelectionManager ssm = StructureSelectionManager
327                     .getStructureSelectionManager(Desktop.instance);
328             SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
329             ssm.computeMapping(false, new SequenceI[] { seq }, null,
330                     openFile, DataSourceType.FILE, null);
331           }
332         }
333         else
334         {
335           Console.debug(
336                   "Opening '" + openFile + "' in existing alignment frame");
337           af.getCurrentView().addFile(new File(openFile), format);
338         }
339
340         Console.debug("Command " + Arg.OPEN + " executed successfully!");
341
342       }
343       if (first) // first=true means nothing opened
344       {
345         if (headless)
346         {
347           Console.error("Could not open any files in headless mode");
348           System.exit(1);
349         }
350         else
351         {
352           Console.warn("No more files to open");
353           if (desktop != null)
354             desktop.setProgressBar(null, progress);
355         }
356       }
357
358     }
359
360     // open the structure (from same PDB file or given PDBfile)
361     if (!avm.getBoolean(Arg.NOSTRUCTURE))
362     {
363       AlignFrame af = afMap.get(id);
364       if (avm.hasValue(Arg.STRUCTURE))
365       {
366         for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
367         {
368           String val = av.getValue();
369           SubVals subId = new SubVals(val);
370           SequenceI seq = getSpecifiedSequence(af, subId);
371           if (seq == null)
372           {
373             Console.warn("Could not find sequence for argument --"
374                     + Arg.STRUCTURE + "=" + val);
375             // you probably want to continue here, not break
376             // break;
377             continue;
378           }
379           File structureFile = null;
380           if (subId.getContent() != null
381                   && subId.getContent().length() != 0)
382           {
383             structureFile = new File(subId.getContent());
384             Console.debug("Using structure file (from argument) '"
385                     + structureFile.getAbsolutePath() + "'");
386           }
387
388           // TRY THIS
389           /*
390            PDBEntry fileEntry = new AssociatePdbFileWithSeq()
391                   .associatePdbWithSeq(selectedPdbFileName,
392                           DataSourceType.FILE, selectedSequence, true,
393                           Desktop.instance);
394                           
395            sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
396                   ap, new SequenceI[]
397                   { selectedSequence });
398           
399            */
400
401           /* THIS DOESN'T WORK */
402           else if (seq.getAllPDBEntries() != null
403                   && seq.getAllPDBEntries().size() > 0)
404           {
405             structureFile = new File(
406                     seq.getAllPDBEntries().elementAt(0).getFile());
407             Console.debug("Using structure file (from sequence) '"
408                     + structureFile.getAbsolutePath() + "'");
409           }
410
411           if (structureFile == null)
412           {
413             Console.warn("Not provided structure file with '" + val + "'");
414             continue;
415           }
416
417           if (!structureFile.exists())
418           {
419             Console.warn("Structure file '"
420                     + structureFile.getAbsoluteFile() + "' not found.");
421             continue;
422           }
423
424           Console.debug("Using structure file "
425                   + structureFile.getAbsolutePath());
426
427           // open structure view
428           AlignmentPanel ap = af.alignPanel;
429           StructureChooser.openStructureFileForSequence(ap, seq,
430                   structureFile);
431         }
432       }
433     }
434
435     // load a pAE file if given
436     if (avm.hasValue(Arg.PAEMATRIX))
437     {
438       AlignFrame af = afMap.get(id);
439       if (af != null)
440       {
441         for (ArgValue av : avm.getArgValueList(Arg.PAEMATRIX))
442         {
443           String val = av.getValue();
444           SubVals subVals = ArgParser.getSubVals(val);
445           File paeFile = new File(subVals.getContent());
446           String paePath = null;
447           try
448           {
449             paePath = paeFile.getCanonicalPath();
450           } catch (IOException e)
451           {
452             paePath = paeFile.getAbsolutePath();
453             Console.warn(
454                     "Problem with the PAE file path: '" + paePath + "'");
455           }
456           String structId = subVals.get("structid");
457           if (subVals.notSet())
458           {
459             // take structid from pdbfilename
460           }
461           if (subVals.has("structfile"))
462           {
463             Console.info("***** Attaching paeFile '" + paePath + "' to "
464                     + "structfile=" + subVals.get("structfile"));
465             EBIAlfaFold.addAlphaFoldPAEToStructure(
466                     af.getCurrentView().getAlignment(), paeFile,
467                     subVals.getIndex(), subVals.get("structfile"), false);
468           }
469           else if (subVals.has("structid"))
470           {
471             Console.info("***** Attaching paeFile '" + paePath + "' to "
472                     + "structid=" + subVals.get("structid"));
473             EBIAlfaFold.addAlphaFoldPAEToStructure(
474                     af.getCurrentView().getAlignment(), paeFile,
475                     subVals.getIndex(), subVals.get("structid"), true);
476           }
477           else
478           {
479             Console.debug("***** Attaching paeFile '" + paePath
480                     + "' to sequence index " + subVals.getIndex());
481             EBIAlfaFold.addAlphaFoldPAEToSequence(
482                     af.getCurrentView().getAlignment(), paeFile,
483                     subVals.getIndex(), null);
484             // required to readjust the height and position of the pAE
485             // annotation
486           }
487           for (AlignmentViewPanel ap : af.getAlignPanels())
488           {
489             ap.adjustAnnotationHeight();
490           }
491         }
492       }
493     }
494
495     boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
496     if (doShading)
497     {
498       AlignFrame af = afMap.get(id);
499       for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
500               .findAnnotation(PDBChain.class.getName().toString()))
501       {
502         AnnotationColourGradient acg = new AnnotationColourGradient(aa,
503                 af.alignPanel.av.getGlobalColourScheme(), 0);
504         acg.setSeqAssociated(true);
505         af.changeColour(acg);
506         Console.info("Changed colour " + acg.toString());
507       }
508     }
509   }
510
511   protected void processImages(String id)
512   {
513     ArgValuesMap avm = new ArgValuesMap(argParser.linkedArgs(id));
514     AlignFrame af = afMap.get(id);
515
516     if (af == null)
517     {
518       Console.warn("Did not have an alignment window for id=" + id);
519       return;
520     }
521
522     if (avm.hasValue(Arg.IMAGE))
523     {
524       for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
525       {
526         String val = av.getValue();
527         SubVals subVal = new SubVals(val);
528         String type = "png"; // default
529         String fileName = subVal.getContent();
530         File file = new File(fileName);
531         if (subVal.has("type"))
532         {
533           type = subVal.get("type");
534         }
535         else if (fileName != null)
536         {
537           for (String ext : new String[] { "svg", "png", "html" })
538           {
539             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
540             {
541               type = ext;
542             }
543           }
544         }
545         // for moment we disable JSON export
546         Cache.setPropsAreReadOnly(true);
547         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
548
549         switch (type)
550         {
551         case "svg":
552           Console.debug("Outputting type '" + type + "' to " + fileName);
553           af.createSVG(file);
554           break;
555         case "png":
556           Console.debug("Outputting type '" + type + "' to " + fileName);
557           af.createPNG(file);
558           break;
559         case "html":
560           Console.debug("Outputting type '" + type + "' to " + fileName);
561           HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
562           htmlSVG.exportHTML(fileName);
563           break;
564         default:
565           Console.warn("--image type '" + type + "' not known. Ignoring");
566           break;
567         }
568       }
569     }
570   }
571
572   private SequenceI getSpecifiedSequence(AlignFrame af, SubVals subId)
573   {
574     AlignmentI al = af.getCurrentView().getAlignment();
575     if (-1 < subId.getIndex()
576             && subId.getIndex() < al.getSequences().size())
577     {
578       return al.getSequenceAt(subId.getIndex());
579     }
580     else if (subId.has("seqid"))
581     {
582       return al.findName(subId.get("seqid"));
583     }
584     return null;
585   }
586 }