Logo Search packages:      
Sourcecode: jalview version File versions

AlignFrame jalview::gui::Jalview2XML::LoadFromObject ( JalviewModel  object,
String  file,
boolean  loadTreesAndStructures,
jarInputStreamProvider  jprovider 
) [inline, package]

Load alignment frame from jalview XML DOM object

Parameters:
objectDOM
filefilename source string
loadTreesAndStructureswhen false only create Viewport
jproviderdata source provider
Returns:
alignment frame created from view stored in DOM

store any annotations which forward reference a group's ID

test if annotation is automatically calculated for this view only

Definition at line 1873 of file Jalview2XML.java.

References addMapping(), jalview::gui::AlignmentPanel::AlignmentPanel(), jalview::datamodel::Annotation::Annotation(), errorMessage, jalview::gui::TreePanel::fitToWindow_actionPerformed(), jalview::gui::Desktop::getAlignmentPanels(), jalview::schemes::ColourSchemeProperty::getColour(), jalview::datamodel::Sequence::getSequence(), jalview::gui::TreePanel::getTree(), retrieveExistingObj(), seqRefIds, jalview::gui::AlignViewport::setCurrentTree(), and viewportsAdded.

Referenced by LoadJalviewAlign().

  {
    SequenceSet vamsasSet = object.getVamsasModel().getSequenceSet(0);
    Sequence[] vamsasSeq = vamsasSet.getSequence();

    JalviewModelSequence jms = object.getJalviewModelSequence();

    Viewport view = jms.getViewport(0);
    // ////////////////////////////////
    // LOAD SEQUENCES

    Vector hiddenSeqs = null;
    jalview.datamodel.Sequence jseq;

    ArrayList tmpseqs = new ArrayList();

    boolean multipleView = false;

    JSeq[] JSEQ = object.getJalviewModelSequence().getJSeq();
    int vi = 0; // counter in vamsasSeq array
    for (int i = 0; i < JSEQ.length; i++)
    {
      String seqId = JSEQ[i].getId();

      if (seqRefIds.get(seqId) != null)
      {
        tmpseqs.add((jalview.datamodel.Sequence) seqRefIds.get(seqId));
        multipleView = true;
      }
      else
      {
        jseq = new jalview.datamodel.Sequence(vamsasSeq[vi].getName(),
                vamsasSeq[vi].getSequence());
        jseq.setDescription(vamsasSeq[vi].getDescription());
        jseq.setStart(JSEQ[i].getStart());
        jseq.setEnd(JSEQ[i].getEnd());
        jseq.setVamsasId(uniqueSetSuffix + seqId);
        seqRefIds.put(vamsasSeq[vi].getId(), jseq);
        tmpseqs.add(jseq);
        vi++;
      }

      if (JSEQ[i].getHidden())
      {
        if (hiddenSeqs == null)
        {
          hiddenSeqs = new Vector();
        }

        hiddenSeqs.addElement((jalview.datamodel.Sequence) seqRefIds
                .get(seqId));
      }

    }

    // /
    // Create the alignment object from the sequence set
    // ///////////////////////////////
    jalview.datamodel.Sequence[] orderedSeqs = new jalview.datamodel.Sequence[tmpseqs
            .size()];

    tmpseqs.toArray(orderedSeqs);

    jalview.datamodel.Alignment al = new jalview.datamodel.Alignment(
            orderedSeqs);

    // / Add the alignment properties
    for (int i = 0; i < vamsasSet.getSequenceSetPropertiesCount(); i++)
    {
      SequenceSetProperties ssp = vamsasSet.getSequenceSetProperties(i);
      al.setProperty(ssp.getKey(), ssp.getValue());
    }

    // /
    // SequenceFeatures are added to the DatasetSequence,
    // so we must create or recover the dataset before loading features
    // ///////////////////////////////
    if (vamsasSet.getDatasetId() == null || vamsasSet.getDatasetId() == "")
    {
      // older jalview projects do not have a dataset id.
      al.setDataset(null);
    }
    else
    {
      recoverDatasetFor(vamsasSet, al);
    }
    // ///////////////////////////////

    Hashtable pdbloaded = new Hashtable();
    if (!multipleView)
    {
      // load sequence features, database references and any associated PDB
      // structures for the alignment
      for (int i = 0; i < vamsasSeq.length; i++)
      {
        if (JSEQ[i].getFeaturesCount() > 0)
        {
          Features[] features = JSEQ[i].getFeatures();
          for (int f = 0; f < features.length; f++)
          {
            jalview.datamodel.SequenceFeature sf = new jalview.datamodel.SequenceFeature(
                    features[f].getType(), features[f].getDescription(),
                    features[f].getStatus(), features[f].getBegin(),
                    features[f].getEnd(), features[f].getFeatureGroup());

            sf.setScore(features[f].getScore());
            for (int od = 0; od < features[f].getOtherDataCount(); od++)
            {
              OtherData keyValue = features[f].getOtherData(od);
              if (keyValue.getKey().startsWith("LINK"))
              {
                sf.addLink(keyValue.getValue());
              }
              else
              {
                sf.setValue(keyValue.getKey(), keyValue.getValue());
              }

            }

            al.getSequenceAt(i).getDatasetSequence().addSequenceFeature(sf);
          }
        }
        if (vamsasSeq[i].getDBRefCount() > 0)
        {
          addDBRefs(al.getSequenceAt(i).getDatasetSequence(), vamsasSeq[i]);
        }
        if (JSEQ[i].getPdbidsCount() > 0)
        {
          Pdbids[] ids = JSEQ[i].getPdbids();
          for (int p = 0; p < ids.length; p++)
          {
            jalview.datamodel.PDBEntry entry = new jalview.datamodel.PDBEntry();
            entry.setId(ids[p].getId());
            entry.setType(ids[p].getType());
            if (ids[p].getFile() != null)
            {
              if (!pdbloaded.containsKey(ids[p].getFile()))
              {
                entry.setFile(loadPDBFile(jprovider, ids[p].getId()));
              }
              else
              {
                entry.setFile(pdbloaded.get(ids[p].getId()).toString());
              }
            }

            al.getSequenceAt(i).getDatasetSequence().addPDBId(entry);
          }
        }
      }
    } // end !multipleview

    // ///////////////////////////////
    // LOAD SEQUENCE MAPPINGS

    if (vamsasSet.getAlcodonFrameCount() > 0)
    {
      // TODO Potentially this should only be done once for all views of an
      // alignment
      AlcodonFrame[] alc = vamsasSet.getAlcodonFrame();
      for (int i = 0; i < alc.length; i++)
      {
        jalview.datamodel.AlignedCodonFrame cf = new jalview.datamodel.AlignedCodonFrame(
                alc[i].getAlcodonCount());
        if (alc[i].getAlcodonCount() > 0)
        {
          Alcodon[] alcods = alc[i].getAlcodon();
          for (int p = 0; p < cf.codons.length; p++)
          {
            if (alcods[p].hasPos1() && alcods[p].hasPos2()
                    && alcods[p].hasPos3())
            {
              // translated codons require three valid positions
              cf.codons[p] = new int[3];
              cf.codons[p][0] = (int) alcods[p].getPos1();
              cf.codons[p][1] = (int) alcods[p].getPos2();
              cf.codons[p][2] = (int) alcods[p].getPos3();
            }
            else
            {
              cf.codons[p] = null;
            }
          }
        }
        if (alc[i].getAlcodMapCount() > 0)
        {
          AlcodMap[] maps = alc[i].getAlcodMap();
          for (int m = 0; m < maps.length; m++)
          {
            SequenceI dnaseq = (SequenceI) seqRefIds
                    .get(maps[m].getDnasq());
            // Load Mapping
            jalview.datamodel.Mapping mapping = null;
            // attach to dna sequence reference.
            if (maps[m].getMapping() != null)
            {
              mapping = addMapping(maps[m].getMapping());
            }
            if (dnaseq != null)
            {
              cf.addMap(dnaseq, mapping.getTo(), mapping.getMap());
            }
            else
            {
              // defer to later
              frefedSequence.add(new Object[]
              { maps[m].getDnasq(), cf, mapping });
            }
          }
        }
        al.addCodonFrame(cf);
      }

    }

    // ////////////////////////////////
    // LOAD ANNOTATIONS
    ArrayList<JvAnnotRow> autoAlan = new ArrayList<JvAnnotRow>();
    /**
     * store any annotations which forward reference a group's ID
     */
    Hashtable<String, ArrayList<jalview.datamodel.AlignmentAnnotation>> groupAnnotRefs = new Hashtable<String, ArrayList<jalview.datamodel.AlignmentAnnotation>>();

    if (vamsasSet.getAnnotationCount() > 0)
    {
      Annotation[] an = vamsasSet.getAnnotation();

      for (int i = 0; i < an.length; i++)
      {
        /**
         * test if annotation is automatically calculated for this view only
         */
        boolean autoForView = false;
        if (an[i].getLabel().equals("Quality")
                || an[i].getLabel().equals("Conservation")
                || an[i].getLabel().equals("Consensus"))
        {
          // Kludge for pre 2.5 projects which lacked the autocalculated flag
          autoForView = true;
          if (!an[i].hasAutoCalculated())
          {
            an[i].setAutoCalculated(true);
          }
        }
        if (autoForView
                || (an[i].hasAutoCalculated() && an[i].isAutoCalculated()))
        {
          // remove ID - we don't recover annotation from other views for
          // view-specific annotation
          an[i].setId(null);
        }

        // set visiblity for other annotation in this view
        if (an[i].getId() != null
                && annotationIds.containsKey(an[i].getId()))
        {
          jalview.datamodel.AlignmentAnnotation jda = (jalview.datamodel.AlignmentAnnotation) annotationIds
                  .get(an[i].getId());
          // in principle Visible should always be true for annotation displayed
          // in multiple views
          if (an[i].hasVisible())
            jda.visible = an[i].getVisible();

          al.addAnnotation(jda);

          continue;
        }
        // Construct new annotation from model.
        AnnotationElement[] ae = an[i].getAnnotationElement();
        jalview.datamodel.Annotation[] anot = null;

        if (!an[i].getScoreOnly())
        {
          anot = new jalview.datamodel.Annotation[al.getWidth()];
          for (int aa = 0; aa < ae.length && aa < anot.length; aa++)
          {
            if (ae[aa].getPosition() >= anot.length)
              continue;

            anot[ae[aa].getPosition()] = new jalview.datamodel.Annotation(

            ae[aa].getDisplayCharacter(), ae[aa].getDescription(),
                    (ae[aa].getSecondaryStructure() == null || ae[aa]
                            .getSecondaryStructure().length() == 0) ? ' '
                            : ae[aa].getSecondaryStructure().charAt(0),
                    ae[aa].getValue()

            );
            // JBPNote: Consider verifying dataflow for IO of secondary
            // structure annotation read from Stockholm files
            // this was added to try to ensure that
            // if (anot[ae[aa].getPosition()].secondaryStructure>' ')
            // {
            // anot[ae[aa].getPosition()].displayCharacter = "";
            // }
            anot[ae[aa].getPosition()].colour = new java.awt.Color(
                    ae[aa].getColour());
          }
        }
        jalview.datamodel.AlignmentAnnotation jaa = null;

        if (an[i].getGraph())
        {
          float llim = 0, hlim = 0;
          // if (autoForView || an[i].isAutoCalculated()) {
          // hlim=11f;
          // }
          jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
                  an[i].getDescription(), anot, llim, hlim,
                  an[i].getGraphType());

          jaa.graphGroup = an[i].getGraphGroup();

          if (an[i].getThresholdLine() != null)
          {
            jaa.setThreshold(new jalview.datamodel.GraphLine(an[i]
                    .getThresholdLine().getValue(), an[i]
                    .getThresholdLine().getLabel(), new java.awt.Color(
                    an[i].getThresholdLine().getColour())));

          }
          if (autoForView || an[i].isAutoCalculated())
          {
            // Hardwire the symbol display line to ensure that labels for
            // histograms are displayed
            jaa.hasText = true;
          }
        }
        else
        {
          jaa = new jalview.datamodel.AlignmentAnnotation(an[i].getLabel(),
                  an[i].getDescription(), anot);
        }
        if (autoForView)
        {
          // register new annotation
          if (an[i].getId() != null)
          {
            annotationIds.put(an[i].getId(), jaa);
            jaa.annotationId = an[i].getId();
          }
          // recover sequence association
          if (an[i].getSequenceRef() != null)
          {
            if (al.findName(an[i].getSequenceRef()) != null)
            {
              jaa.createSequenceMapping(
                      al.findName(an[i].getSequenceRef()), 1, true);
              al.findName(an[i].getSequenceRef()).addAlignmentAnnotation(
                      jaa);
            }
          }
        }
        // and make a note of any group association
        if (an[i].getGroupRef() != null && an[i].getGroupRef().length() > 0)
        {
          ArrayList<jalview.datamodel.AlignmentAnnotation> aal = groupAnnotRefs
                  .get(an[i].getGroupRef());
          if (aal == null)
          {
            aal = new ArrayList<jalview.datamodel.AlignmentAnnotation>();
            groupAnnotRefs.put(an[i].getGroupRef(), aal);
          }
          aal.add(jaa);
        }

        if (an[i].hasScore())
        {
          jaa.setScore(an[i].getScore());
        }
        if (an[i].hasVisible())
          jaa.visible = an[i].getVisible();

        if (an[i].hasCentreColLabels())
          jaa.centreColLabels = an[i].getCentreColLabels();

        if (an[i].hasScaleColLabels())
        {
          jaa.scaleColLabel = an[i].getScaleColLabels();
        }
        if (an[i].hasAutoCalculated() && an[i].isAutoCalculated())
        {
          // newer files have an 'autoCalculated' flag and store calculation
          // state in viewport properties
          jaa.autoCalculated = true; // means annotation will be marked for
          // update at end of load.
        }
        if (an[i].hasGraphHeight())
        {
          jaa.graphHeight = an[i].getGraphHeight();
        }
        if (jaa.autoCalculated)
        {
          autoAlan.add(new JvAnnotRow(i, jaa));
        }
        else
        // if (!autoForView)
        {
          // add autocalculated group annotation and any user created annotation
          // for the view
          al.addAnnotation(jaa);
        }
      }
    }

    // ///////////////////////
    // LOAD GROUPS
    // Create alignment markup and styles for this view
    if (jms.getJGroupCount() > 0)
    {
      JGroup[] groups = jms.getJGroup();

      for (int i = 0; i < groups.length; i++)
      {
        ColourSchemeI cs = null;

        if (groups[i].getColour() != null)
        {
          if (groups[i].getColour().startsWith("ucs"))
          {
            cs = GetUserColourScheme(jms, groups[i].getColour());
          }
          else
          {
            cs = ColourSchemeProperty.getColour(al, groups[i].getColour());
          }

          if (cs != null)
          {
            cs.setThreshold(groups[i].getPidThreshold(), true);
          }
        }

        Vector seqs = new Vector();

        for (int s = 0; s < groups[i].getSeqCount(); s++)
        {
          String seqId = groups[i].getSeq(s) + "";
          jalview.datamodel.SequenceI ts = (jalview.datamodel.SequenceI) seqRefIds
                  .get(seqId);

          if (ts != null)
          {
            seqs.addElement(ts);
          }
        }

        if (seqs.size() < 1)
        {
          continue;
        }

        jalview.datamodel.SequenceGroup sg = new jalview.datamodel.SequenceGroup(
                seqs, groups[i].getName(), cs, groups[i].getDisplayBoxes(),
                groups[i].getDisplayText(), groups[i].getColourText(),
                groups[i].getStart(), groups[i].getEnd());

        sg.setOutlineColour(new java.awt.Color(groups[i].getOutlineColour()));

        sg.textColour = new java.awt.Color(groups[i].getTextCol1());
        sg.textColour2 = new java.awt.Color(groups[i].getTextCol2());
        sg.setShowNonconserved(groups[i].hasShowUnconserved() ? groups[i]
                .isShowUnconserved() : false);
        sg.thresholdTextColour = groups[i].getTextColThreshold();
        if (groups[i].hasShowConsensusHistogram())
        {
          sg.setShowConsensusHistogram(groups[i].isShowConsensusHistogram());
        }
        ;
        if (groups[i].hasShowSequenceLogo())
        {
          sg.setshowSequenceLogo(groups[i].isShowSequenceLogo());
        }
        if (groups[i].hasIgnoreGapsinConsensus())
        {
          sg.setIgnoreGapsConsensus(groups[i].getIgnoreGapsinConsensus());
        }
        if (groups[i].getConsThreshold() != 0)
        {
          jalview.analysis.Conservation c = new jalview.analysis.Conservation(
                  "All", ResidueProperties.propHash, 3,
                  sg.getSequences(null), 0, sg.getWidth() - 1);
          c.calculate();
          c.verdict(false, 25);
          sg.cs.setConservation(c);
        }

        if (groups[i].getId() != null && groupAnnotRefs.size() > 0)
        {
          // re-instate unique group/annotation row reference
          ArrayList<jalview.datamodel.AlignmentAnnotation> jaal = groupAnnotRefs
                  .get(groups[i].getId());
          if (jaal != null)
          {
            for (jalview.datamodel.AlignmentAnnotation jaa : jaal)
            {
              jaa.groupRef = sg;
              if (jaa.autoCalculated)
              {
                // match up and try to set group autocalc alignment row for this
                // annotation
                if (jaa.label.startsWith("Consensus for "))
                {
                  sg.setConsensus(jaa);
                }
                // match up and try to set group autocalc alignment row for this
                // annotation
                if (jaa.label.startsWith("Conservation for "))
                {
                  sg.setConservationRow(jaa);
                }
              }
            }
          }
        }
        al.addGroup(sg);

      }
    }

    // ///////////////////////////////
    // LOAD VIEWPORT

    // If we just load in the same jar file again, the sequenceSetId
    // will be the same, and we end up with multiple references
    // to the same sequenceSet. We must modify this id on load
    // so that each load of the file gives a unique id
    String uniqueSeqSetId = view.getSequenceSetId() + uniqueSetSuffix;
    String viewId = (view.getId() == null ? null : view.getId()
            + uniqueSetSuffix);
    AlignFrame af = null;
    AlignViewport av = null;
    // now check to see if we really need to create a new viewport.
    if (multipleView && viewportsAdded.size() == 0)
    {
      // We recovered an alignment for which a viewport already exists.
      // TODO: fix up any settings necessary for overlaying stored state onto
      // state recovered from another document. (may not be necessary).
      // we may need a binding from a viewport in memory to one recovered from
      // XML.
      // and then recover its containing af to allow the settings to be applied.
      // TODO: fix for vamsas demo
      System.err
              .println("About to recover a viewport for existing alignment: Sequence set ID is "
                      + uniqueSeqSetId);
      Object seqsetobj = retrieveExistingObj(uniqueSeqSetId);
      if (seqsetobj != null)
      {
        if (seqsetobj instanceof String)
        {
          uniqueSeqSetId = (String) seqsetobj;
          System.err
                  .println("Recovered extant sequence set ID mapping for ID : New Sequence set ID is "
                          + uniqueSeqSetId);
        }
        else
        {
          System.err
                  .println("Warning : Collision between sequence set ID string and existing jalview object mapping.");
        }

      }
    }
    AlignmentPanel ap = null;
    boolean isnewview = true;
    if (viewId != null)
    {
      // Check to see if this alignment already has a view id == viewId
      jalview.gui.AlignmentPanel views[] = Desktop
              .getAlignmentPanels(uniqueSeqSetId);
      if (views != null && views.length > 0)
      {
        for (int v = 0; v < views.length; v++)
        {
          if (views[v].av.getViewId().equalsIgnoreCase(viewId))
          {
            // recover the existing alignpanel, alignframe, viewport
            af = views[v].alignFrame;
            av = views[v].av;
            ap = views[v];
            // TODO: could even skip resetting view settings if we don't want to
            // change the local settings from other jalview processes
            isnewview = false;
          }
        }
      }
    }

    if (isnewview)
    {
      af = loadViewport(file, JSEQ, hiddenSeqs, al, jms, view,
              uniqueSeqSetId, viewId, autoAlan);
      av = af.viewport;
      ap = af.alignPanel;
    }
    // LOAD TREES
    // /////////////////////////////////////
    if (loadTreesAndStructures && jms.getTreeCount() > 0)
    {
      try
      {
        for (int t = 0; t < jms.getTreeCount(); t++)
        {

          Tree tree = jms.getTree(t);

          TreePanel tp = (TreePanel) retrieveExistingObj(tree.getId());
          if (tp == null)
          {
            tp = af.ShowNewickTree(
                    new jalview.io.NewickFile(tree.getNewick()),
                    tree.getTitle(), tree.getWidth(), tree.getHeight(),
                    tree.getXpos(), tree.getYpos());
            if (tree.getId() != null)
            {
              // perhaps bind the tree id to something ?
            }
          }
          else
          {
            // update local tree attributes ?
            // TODO: should check if tp has been manipulated by user - if so its
            // settings shouldn't be modified
            tp.setTitle(tree.getTitle());
            tp.setBounds(new Rectangle(tree.getXpos(), tree.getYpos(), tree
                    .getWidth(), tree.getHeight()));
            tp.av = av; // af.viewport; // TODO: verify 'associate with all
            // views'
            // works still
            tp.treeCanvas.av = av; // af.viewport;
            tp.treeCanvas.ap = ap; // af.alignPanel;

          }
          if (tp == null)
          {
            warn("There was a problem recovering stored Newick tree: \n"
                    + tree.getNewick());
            continue;
          }

          tp.fitToWindow.setState(tree.getFitToWindow());
          tp.fitToWindow_actionPerformed(null);

          if (tree.getFontName() != null)
          {
            tp.setTreeFont(new java.awt.Font(tree.getFontName(), tree
                    .getFontStyle(), tree.getFontSize()));
          }
          else
          {
            tp.setTreeFont(new java.awt.Font(view.getFontName(), view
                    .getFontStyle(), tree.getFontSize()));
          }

          tp.showPlaceholders(tree.getMarkUnlinked());
          tp.showBootstrap(tree.getShowBootstrap());
          tp.showDistances(tree.getShowDistances());

          tp.treeCanvas.threshold = tree.getThreshold();

          if (tree.getCurrentTree())
          {
            af.viewport.setCurrentTree(tp.getTree());
          }
        }

      } catch (Exception ex)
      {
        ex.printStackTrace();
      }
    }

    // //LOAD STRUCTURES
    if (loadTreesAndStructures)
    {
      // run through all PDB ids on the alignment, and collect mappings between
      // jmol view ids and all sequences referring to it
      Hashtable<String, Object[]> jmolViewIds = new Hashtable();

      for (int i = 0; i < JSEQ.length; i++)
      {
        if (JSEQ[i].getPdbidsCount() > 0)
        {
          Pdbids[] ids = JSEQ[i].getPdbids();
          for (int p = 0; p < ids.length; p++)
          {
            for (int s = 0; s < ids[p].getStructureStateCount(); s++)
            {
              // check to see if we haven't already created this structure view
              String sviewid = (ids[p].getStructureState(s).getViewId() == null) ? null
                      : ids[p].getStructureState(s).getViewId()
                              + uniqueSetSuffix;
              jalview.datamodel.PDBEntry jpdb = new jalview.datamodel.PDBEntry();
              // Originally : ids[p].getFile()
              // : TODO: verify external PDB file recovery still works in normal
              // jalview project load
              jpdb.setFile(loadPDBFile(jprovider, ids[p].getId()));
              jpdb.setId(ids[p].getId());

              int x = ids[p].getStructureState(s).getXpos();
              int y = ids[p].getStructureState(s).getYpos();
              int width = ids[p].getStructureState(s).getWidth();
              int height = ids[p].getStructureState(s).getHeight();

              // Probably don't need to do this anymore...
              // Desktop.desktop.getComponentAt(x, y);
              // TODO: NOW: check that this recovers the PDB file correctly.
              String pdbFile = loadPDBFile(jprovider, ids[p].getId());
              jalview.datamodel.SequenceI seq = (jalview.datamodel.SequenceI) seqRefIds
                      .get(JSEQ[i].getId() + "");
              if (sviewid == null)
              {
                sviewid = "_jalview_pre2_4_" + x + "," + y + "," + width
                        + "," + height;
              }
              if (!jmolViewIds.containsKey(sviewid))
              {
                jmolViewIds.put(sviewid, new Object[]
                { new int[]
                { x, y, width, height }, "",
                    new Hashtable<String, Object[]>(), new boolean[]
                    { false, false, true } });
                // Legacy pre-2.7 conversion JAL-823 :
                // do not assume any view has to be linked for colour by
                // sequence
              }

              // assemble String[] { pdb files }, String[] { id for each
              // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
              // seqs_file 2}, boolean[] {
              // linkAlignPanel,superposeWithAlignpanel}} from hash
              Object[] jmoldat = (Object[]) jmolViewIds.get(sviewid);
              ((boolean[]) jmoldat[3])[0] |= ids[p].getStructureState(s)
                      .hasAlignwithAlignPanel() ? ids[p].getStructureState(
                      s).getAlignwithAlignPanel() : false;
              // never colour by linked panel if not specified
              ((boolean[]) jmoldat[3])[1] |= ids[p].getStructureState(s)
                      .hasColourwithAlignPanel() ? ids[p]
                      .getStructureState(s).getColourwithAlignPanel()
                      : false;
              // default for pre-2.7 projects is that Jmol colouring is enabled
              ((boolean[]) jmoldat[3])[2] &= ids[p].getStructureState(s)
                      .hasColourByJmol() ? ids[p].getStructureState(s)
                      .getColourByJmol() : true;

              if (((String) jmoldat[1]).length() < ids[p]
                      .getStructureState(s).getContent().length())
              {
                {
                  jmoldat[1] = ids[p].getStructureState(s).getContent();
                }
              }
              if (ids[p].getFile() != null)
              {
                Object[] seqstrmaps = (Object[]) ((Hashtable) jmoldat[2])
                        .get(ids[p].getFile());
                if (seqstrmaps == null)
                {
                  ((Hashtable) jmoldat[2]).put(
                          new File(ids[p].getFile()).toString(),
                          seqstrmaps = new Object[]
                          { pdbFile, ids[p].getId(), new Vector(),
                              new Vector() });
                }
                if (!((Vector) seqstrmaps[2]).contains(seq))
                {
                  ((Vector) seqstrmaps[2]).addElement(seq);
                  // ((Vector)seqstrmaps[3]).addElement(n) :
                  // in principle, chains
                  // should be stored here : do we need to
                  // TODO: store and recover seq/pdb_id :
                  // chain mappings
                }
              }
              else
              {
                errorMessage = ("The Jmol views in this project were imported\nfrom an older version of Jalview.\nPlease review the sequence colour associations\nin the Colour by section of the Jmol View menu.\n\nIn the case of problems, see note at\nhttp://issues.jalview.org/browse/JAL-747");
                warn(errorMessage);
              }
            }
          }
        }
      }
      {

        // Instantiate the associated Jmol views
        for (Entry<String, Object[]> entry : jmolViewIds.entrySet())
        {
          String sviewid = entry.getKey();
          Object[] svattrib = entry.getValue();
          int[] geom = (int[]) svattrib[0];
          String state = (String) svattrib[1];
          Hashtable<String, Object[]> oldFiles = (Hashtable<String, Object[]>) svattrib[2];
          final boolean useinJmolsuperpos = ((boolean[]) svattrib[3])[0], usetoColourbyseq = ((boolean[]) svattrib[3])[1], jmolColouring = ((boolean[]) svattrib[3])[2];
          int x = geom[0], y = geom[1], width = geom[2], height = geom[3];
          // collate the pdbfile -> sequence mappings from this view
          Vector<String> pdbfilenames = new Vector<String>();
          Vector<SequenceI[]> seqmaps = new Vector<SequenceI[]>();
          Vector<String> pdbids = new Vector<String>();

          // Search to see if we've already created this Jmol view
          AppJmol comp = null;
          JInternalFrame[] frames = null;
          do
          {
            try
            {
              frames = Desktop.desktop.getAllFrames();
            } catch (ArrayIndexOutOfBoundsException e)
            {
              // occasional No such child exceptions are thrown here...
              frames = null;
              try
              {
                Thread.sleep(10);
              } catch (Exception f)
              {
              }
              ;
            }
          } while (frames == null);
          // search for any Jmol windows already open from other
          // alignment views that exactly match the stored structure state
          for (int f = 0; comp == null && f < frames.length; f++)
          {
            if (frames[f] instanceof AppJmol)
            {
              if (sviewid != null
                      && ((AppJmol) frames[f]).getViewId().equals(sviewid))
              {
                // post jalview 2.4 schema includes structure view id
                comp = (AppJmol) frames[f];
              }
              else if (frames[f].getX() == x && frames[f].getY() == y
                      && frames[f].getHeight() == height
                      && frames[f].getWidth() == width)
              {
                comp = (AppJmol) frames[f];
              }
            }
          }

          if (comp == null)
          {
            // create a new Jmol window.
            // First parse the Jmol state to translate filenames loaded into the
            // view, and record the order in which files are shown in the Jmol
            // view, so we can add the sequence mappings in same order.
            StringBuffer newFileLoc = null;
            int cp = 0, ncp, ecp;
            while ((ncp = state.indexOf("load ", cp)) > -1)
            {
              if (newFileLoc == null)
              {
                newFileLoc = new StringBuffer();
              }
              newFileLoc.append(state.substring(cp,
                      ncp = (state.indexOf("\"", ncp + 1) + 1)));
              String oldfilenam = state.substring(ncp,
                      ecp = state.indexOf("\"", ncp));
              // recover the new mapping data for this old filename
              // have to normalize filename - since Jmol and jalview do filename
              // translation differently.
              Object[] filedat = oldFiles.get(new File(oldfilenam)
                      .toString());
              newFileLoc.append(((String) filedat[0]));
              pdbfilenames.addElement((String) filedat[0]);
              pdbids.addElement((String) filedat[1]);
              seqmaps.addElement((SequenceI[]) ((Vector<SequenceI>) filedat[2])
                      .toArray(new SequenceI[0]));
              newFileLoc.append("\"");
              cp = ecp + 1; // advance beyond last \" and set cursor so we can
                            // look for next file statement.
            }
            if (cp > 0)
            {
              // just append rest of state
              newFileLoc.append(state.substring(cp));
            }
            else
            {
              System.err
                      .print("Ignoring incomplete Jmol state for PDB ids: ");
              newFileLoc = new StringBuffer(state);
              newFileLoc.append("; load append ");
              for (String id : oldFiles.keySet())
              {
                // add this and any other pdb files that should be present in
                // the viewer
                Object[] filedat = oldFiles.get(id);
                String nfilename;
                newFileLoc.append(((String) filedat[0]));
                pdbfilenames.addElement((String) filedat[0]);
                pdbids.addElement((String) filedat[1]);
                seqmaps.addElement((SequenceI[]) ((Vector<SequenceI>) filedat[2])
                        .toArray(new SequenceI[0]));
                newFileLoc.append(" \"");
                newFileLoc.append((String) filedat[0]);
                newFileLoc.append("\"");

              }
              newFileLoc.append(";");
            }

            if (newFileLoc != null)
            {
              int histbug = newFileLoc.indexOf("history = ");
              histbug += 10;
              int diff = histbug == -1 ? -1 : newFileLoc.indexOf(";",
                      histbug);
              String val = (diff == -1) ? null : newFileLoc.substring(
                      histbug, diff);
              if (val != null && val.length() >= 4)
              {
                if (val.contains("e"))
                {
                  if (val.trim().equals("true"))
                  {
                    val = "1";
                  }
                  else
                  {
                    val = "0";
                  }
                  newFileLoc.replace(histbug, diff, val);
                }
              }
              // TODO: assemble String[] { pdb files }, String[] { id for each
              // file }, orig_fileloc, SequenceI[][] {{ seqs_file 1 }, {
              // seqs_file 2}} from hash
              final String[] pdbf = (String[]) pdbfilenames
                      .toArray(new String[pdbfilenames.size()]), id = (String[]) pdbids
                      .toArray(new String[pdbids.size()]);
              final SequenceI[][] sq = (SequenceI[][]) seqmaps
                      .toArray(new SequenceI[seqmaps.size()][]);
              final String fileloc = newFileLoc.toString(), vid = sviewid;
              final AlignFrame alf = af;
              final java.awt.Rectangle rect = new java.awt.Rectangle(x, y,
                      width, height);
              try
              {
                javax.swing.SwingUtilities.invokeAndWait(new Runnable()
                {
                  public void run()
                  {
                    AppJmol sview = null;
                    try
                    {
                      sview = new AppJmol(pdbf, id, sq, alf.alignPanel,
                              useinJmolsuperpos, usetoColourbyseq,
                              jmolColouring, fileloc, rect, vid);
                    } catch (OutOfMemoryError ex)
                    {
                      new OOMWarning("restoring structure view for PDB id "
                              + id, (OutOfMemoryError) ex.getCause());
                      if (sview != null && sview.isVisible())
                      {
                        sview.closeViewer();
                        sview.setVisible(false);
                        sview.dispose();
                      }
                    }
                  }
                });
              } catch (InvocationTargetException ex)
              {
                warn("Unexpected error when opening Jmol view.", ex);

              } catch (InterruptedException e)
              {
                // e.printStackTrace();
              }
            }

          }
          else
          // if (comp != null)
          {
            // NOTE: if the jalview project is part of a shared session then
            // view synchronization should/could be done here.

            // add mapping for sequences in this view to an already open Jmol
            // instance
            for (String id : oldFiles.keySet())
            {
              // add this and any other pdb files that should be present in the
              // viewer
              Object[] filedat = oldFiles.get(id);
              String pdbFile = (String) filedat[0];
              SequenceI[] seq = (SequenceI[]) ((Vector<SequenceI>) filedat[2])
                      .toArray(new SequenceI[0]);
              ((AppJmol) comp).jmb.ssm.setMapping(seq, null, pdbFile,
                      jalview.io.AppletFormatAdapter.FILE);
              ((AppJmol) comp).jmb.addSequenceForStructFile(pdbFile, seq);
            }
            // and add the AlignmentPanel's reference to the Jmol view
            ((AppJmol) comp).addAlignmentPanel(ap);
            if (useinJmolsuperpos)
            {
              ((AppJmol) comp).useAlignmentPanelForSuperposition(ap);
            }
            else
            {
              ((AppJmol) comp).excludeAlignmentPanelForSuperposition(ap);
            }
            if (usetoColourbyseq)
            {
              ((AppJmol) comp).useAlignmentPanelForColourbyseq(ap,
                      !jmolColouring);
            }
            else
            {
              ((AppJmol) comp).excludeAlignmentPanelForColourbyseq(ap);
            }
          }
        }
      }
    }
    // and finally return.
    return af;
  }

Here is the call graph for this function:

Here is the caller graph for this function:


Generated by  Doxygen 1.6.0   Back to index