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