private SB getShortStringData(int shortSID, int nBytes, boolean asBinaryString) {
   SB data = new SB();
   if (rootEntry == null) return data;
   int thisSID = rootEntry.SIDfirstSector;
   int ptShort = 0;
   byte[] byteBuf = new byte[shortSectorSize];
   ZipData gzipData = new ZipData(nBytes);
   try {
     // System.out.println("CD shortSID=" + shortSID);
     // point to correct short data sector, 512/64 = 4 per page
     while (thisSID >= 0 && shortSID >= 0 && nBytes > 0) {
       while (shortSID - ptShort >= nShortSectorsPerStandardSector) {
         ptShort += nShortSectorsPerStandardSector;
         thisSID = SAT[thisSID];
       }
       seek(getOffset(thisSID) + (shortSID - ptShort) * shortSectorSize);
       nBytes = getSectorData(data, byteBuf, shortSectorSize, nBytes, asBinaryString, gzipData);
       shortSID = SSAT[shortSID];
       // System.out.println("CD shortSID=" + shortSID);
     }
   } catch (Exception e) {
     Logger.error(data.toString());
     Logger.errorEx(null, e);
   }
   if (gzipData.isEnabled) gzipData.addTo(data);
   return data;
 }
 private int getSectorData(
     SB data,
     byte[] byteBuf,
     int nSectorBytes,
     int nBytes,
     boolean asBinaryString,
     ZipData gzipData)
     throws Exception {
   readByteArray(byteBuf, 0, byteBuf.length);
   int n = gzipData.addBytes(byteBuf, nSectorBytes, nBytes);
   if (n >= 0) return n;
   if (asBinaryString) {
     for (int i = 0; i < nSectorBytes; i++) {
       data.append(Integer.toHexString(byteBuf[i] & 0xFF)).appendC(' ');
       if (--nBytes < 1) break;
     }
   } else {
     for (int i = 0; i < nSectorBytes; i++) {
       if (byteBuf[i] == 0) return -9999; // don't allow binary data
       data.appendC((char) byteBuf[i]);
       if (--nBytes < 1) break;
     }
   }
   return nBytes;
 }
Esempio n. 3
0
 @SuppressWarnings("unchecked")
 @Override
 public Object getProperty(String propertyName, int param) {
   if (propertyName.equals("list")) {
     String s = (String) getPropI("list");
     if (s.length() > 1) s += "cutoff = " + getPropI("cutoff") + "\n";
     return vwr.getMoInfo(-1) + "\n" + s;
   }
   if (propertyName == "moNumber") return Integer.valueOf(moNumber);
   if (propertyName == "moLinearCombination") return moLinearCombination;
   if (propertyName == "showMO") {
     SB str = new SB();
     Lst<Map<String, Object>> mos = (Lst<Map<String, Object>>) (sg.getMoData().get("mos"));
     int nOrb = (mos == null ? 0 : mos.size());
     int thisMO = param;
     int currentMO = moNumber;
     boolean isShowCurrent = (thisMO == Integer.MIN_VALUE);
     if (thisMO == Integer.MAX_VALUE) {
       thisMO = currentMO;
     }
     if (nOrb == 0 || isShowCurrent && currentMO == 0) return "";
     boolean doOneMo = (thisMO != 0);
     if (currentMO == 0) thisMO = 0;
     boolean haveHeader = false;
     int nTotal = (thisMO > 0 ? 1 : nOrb);
     int i0 = (nTotal == 1 && currentMO > 0 ? currentMO : 1);
     for (int i = i0; i <= nOrb; i++)
       if (thisMO == 0 || thisMO == i || !doOneMo && i == currentMO) {
         if (!doOneMo) {
           Parameters params = sg.getParams();
           setPropI("init", params, null);
           setOrbital(i, null);
         }
         jvxlData.moleculeXml =
             vwr.getModelCml(vwr.getModelUndeletedAtomsBitSet(thisMesh.modelIndex), 100, true);
         if (!haveHeader) {
           str.append(
               JvxlCoder.jvxlGetFile(
                   jvxlData, null, null, "HEADERONLY", true, nTotal, null, null));
           haveHeader = true;
         }
         str.append(
             JvxlCoder.jvxlGetFile(
                 jvxlData,
                 null,
                 jvxlData.title,
                 null,
                 false,
                 1,
                 thisMesh.getState("mo"),
                 (thisMesh.scriptCommand == null ? "" : thisMesh.scriptCommand)));
         if (!doOneMo) setPropI("delete", "mo_show", null);
         if (nTotal == 1) break;
       }
     str.append(JvxlCoder.jvxlGetFile(jvxlData, null, null, "TRAILERONLY", true, 0, null, null));
     return str.toString();
   }
   return getPropI(propertyName);
 }
Esempio n. 4
0
 @Override
 void dump(int level, SB sb) {
   sb.append("\nnode LEFT" + level);
   eleLeft.dump(level + 1, sb);
   for (int i = 0; i < level; ++i) sb.append("->");
   sb.append(" RIGHT" + level);
   eleRight.dump(level + 1, sb);
 }
Esempio n. 5
0
 @Override
 public String getShapeState() {
   if (!isActive()) return "";
   SB sb = new SB();
   sb.append("\n");
   if (!simpleEllipsoids.isEmpty()) getStateID(sb);
   if (!atomEllipsoids.isEmpty()) getStateAtoms(sb);
   return sb.toString();
 }
Esempio n. 6
0
 @Override
 public String getShapeState() {
   if (htModels == null) return "";
   SB s = new SB();
   int modelCount = vwr.getModelCount();
   for (int i = 0; i < modelCount; i++) s.append(getMoState(i));
   // System.out.println("molecular orbital state " + s.length());
   return s.toString();
 }
Esempio n. 7
0
 String getSavedOrientationText(String saveName) {
   Orientation o;
   if (saveName != null) {
     o = getOrientationFor(saveName);
     return (o == null ? "" : o.getMoveToText(true));
   }
   SB sb = new SB();
   for (Entry<String, Object> e : saved.entrySet()) {
     String name = e.getKey();
     if (name.startsWith("Orientation_"))
       sb.append(((Orientation) e.getValue()).getMoveToText(true));
   }
   return sb.toString();
 }
Esempio n. 8
0
 /**
  * checks an atom line for "ANGSTROMS", possibly overriding the data's natural units, BOHR
  * (similar to Gaussian CUBE files).
  *
  * @param isXLowToHigh
  * @param isAngstroms
  * @param strAtomCount
  * @param atomLine
  * @param bs
  * @return isAngstroms
  */
 protected static boolean checkAtomLine(
     boolean isXLowToHigh, boolean isAngstroms, String strAtomCount, String atomLine, SB bs) {
   if (atomLine.indexOf("ANGSTROMS") >= 0) isAngstroms = true;
   int ac = (strAtomCount == null ? Integer.MAX_VALUE : javajs.util.PT.parseInt(strAtomCount));
   switch (ac) {
     case Integer.MIN_VALUE:
       ac = 0;
       atomLine = " " + atomLine.substring(atomLine.indexOf(" ") + 1);
       break;
     case Integer.MAX_VALUE:
       ac = Integer.MIN_VALUE;
       break;
     default:
       String s = "" + ac;
       atomLine = atomLine.substring(atomLine.indexOf(s) + s.length());
   }
   if (isAngstroms) {
     if (atomLine.indexOf("ANGSTROM") < 0) atomLine += " ANGSTROMS";
   } else {
     if (atomLine.indexOf("BOHR") < 0) atomLine += " BOHR";
   }
   atomLine =
       (ac == Integer.MIN_VALUE ? "" : (isXLowToHigh ? "+" : "-") + Math.abs(ac))
           + atomLine
           + "\n";
   bs.append(atomLine);
   return isAngstroms;
 }
Esempio n. 9
0
 private void getStateAtoms(SB sb) {
   BS bsDone = new BS();
   Map<String, BS> temp = new Hashtable<String, BS>();
   Map<String, BS> temp2 = new Hashtable<String, BS>();
   for (Ellipsoid e : atomEllipsoids.values()) {
     int iType = e.tensor.iType;
     if (bsDone.get(iType + 1)) continue;
     bsDone.set(iType + 1);
     boolean isADP = (e.tensor.iType == Tensor.TYPE_ADP);
     String cmd = (isADP ? null : "Ellipsoids set " + PT.esc(e.tensor.type));
     for (Ellipsoid e2 : atomEllipsoids.values()) {
       if (e2.tensor.iType != iType || isADP && !e2.isOn) continue;
       int i = e2.tensor.atomIndex1;
       //
       BSUtil.setMapBitSet(
           temp,
           i,
           i,
           (isADP
               ? "Ellipsoids " + e2.percent
               : cmd
                   + " scale "
                   + e2.scale
                   + (e2.options == null ? "" : " options " + PT.esc(e2.options))
                   + (e2.isOn ? " ON" : " OFF")));
       if (e2.colix != C.INHERIT_ALL)
         BSUtil.setMapBitSet(
             temp2, i, i, getColorCommand(cmd, e2.pid, e2.colix, translucentAllowed));
     }
   }
   sb.append(vwr.getCommands(temp, temp2, "select"));
 }
 @Override
 public SB getAllDataFiles(String binaryFileList, String firstFile) {
   if (firstFile != null) {
     for (int i = 0; i < directory.size(); i++) {
       CompoundDocDirEntry thisEntry = directory.get(i);
       if (thisEntry.entryName.equals(firstFile)) {
         directory.remove(i);
         directory.add(1, thisEntry); // after ROOT_ENTRY
         break;
       }
     }
   }
   data = new SB();
   data.append("Compound Document File Directory: ");
   data.append(getDirectoryListing("|"));
   data.append("\n");
   binaryFileList = "|" + binaryFileList + "|";
   for (int i = 0; i < directory.size(); i++) {
     CompoundDocDirEntry thisEntry = directory.get(i);
     Logger.info("reading " + thisEntry.entryName);
     if (!thisEntry.isEmpty && thisEntry.entryType != 5) {
       String name = thisEntry.entryName;
       if (name.endsWith(".gz")) name = name.substring(0, name.length() - 3);
       data.append("BEGIN Directory Entry ").append(name).append("\n");
       data.appendSB(
           getEntryAsString(
               thisEntry, binaryFileList.indexOf("|" + thisEntry.entryName + "|") >= 0));
       data.append("\n");
       data.append("END Directory Entry ").append(thisEntry.entryName).append("\n");
     }
   }
   close();
   return data;
 }
Esempio n. 11
0
 private String getMoState(int modelIndex) {
   strID = getId(modelIndex);
   if (!getSettings(strID)) return "";
   SB s = new SB();
   int modelCount = vwr.getModelCount();
   if (modelCount > 1) appendCmd(s, "frame " + vwr.getModelNumberDotted(modelIndex));
   if (moCutoff != null)
     appendCmd(s, "mo cutoff " + (sg.getIsPositiveOnly() ? "+" : "") + moCutoff);
   if (moScale != null) appendCmd(s, "mo scale " + moScale);
   if (moMonteCarloCount != null)
     appendCmd(s, "mo points " + moMonteCarloCount + " " + moRandomSeed);
   if (moResolution != null) appendCmd(s, "mo resolution " + moResolution);
   if (moPlane != null)
     appendCmd(
         s, "mo plane {" + moPlane.x + " " + moPlane.y + " " + moPlane.z + " " + moPlane.w + "}");
   if (moTitleFormat != null) appendCmd(s, "mo titleFormat " + PT.esc(moTitleFormat));
   // the following is a correct object==object test
   if (moColorNeg != null)
     appendCmd(
         s,
         "mo color "
             + Escape.escapeColor(moColorNeg.intValue())
             + (moColorNeg.equals(moColorPos)
                 ? ""
                 : " " + Escape.escapeColor(moColorPos.intValue())));
   if (moSlab != null) {
     if (thisMesh.slabOptions != null) appendCmd(s, thisMesh.slabOptions.toString());
     if (thisMesh.jvxlData.slabValue != Integer.MIN_VALUE)
       appendCmd(s, "mo slab " + thisMesh.jvxlData.slabValue);
   }
   if (moLinearCombination == null) {
     appendCmd(s, "mo " + (moSquareData == Boolean.TRUE ? "squared " : "") + moNumber);
   } else {
     appendCmd(
         s,
         "mo "
             + QS.getMOString(moLinearCombination)
             + (moSquareLinear == Boolean.TRUE ? " squared" : ""));
   }
   if (moTranslucency != null) appendCmd(s, "mo translucent " + moTranslucentLevel);
   appendCmd(s, ((IsosurfaceMesh) thisModel.get("mesh")).getState("mo"));
   return s.toString();
 }
 /**
  * reads a compound document directory and saves all data in a Hashtable so that the files may be
  * organized later in a different order. Also adds a #Directory_Listing entry.
  *
  * <p>Files are bracketed by BEGIN Directory Entry and END Directory Entry lines, similar to
  * ZipUtil.getAllData.
  *
  * @param prefix
  * @param binaryFileList |-separated list of files that should be saved as xx xx xx hex byte
  *     strings. The directory listing is appended with ":asBinaryString"
  * @param fileData
  */
 @Override
 public void getAllDataMapped(String prefix, String binaryFileList, Map<String, String> fileData) {
   fileData.put("#Directory_Listing", getDirectoryListing("|"));
   binaryFileList = "|" + binaryFileList + "|";
   for (int i = 0; i < directory.size(); i++) {
     CompoundDocDirEntry thisEntry = directory.get(i);
     if (!thisEntry.isEmpty && thisEntry.entryType != 5) {
       String name = thisEntry.entryName;
       Logger.info("CompoundDocument file " + name);
       boolean isBinary = (binaryFileList.indexOf("|" + name + "|") >= 0);
       if (isBinary) name += ":asBinaryString";
       SB data = new SB();
       data.append("BEGIN Directory Entry ").append(name).append("\n");
       data.appendSB(getEntryAsString(thisEntry, isBinary));
       data.append("\nEND Directory Entry ").append(name).append("\n");
       fileData.put(prefix + "/" + name, data.toString());
     }
   }
   close();
 }
Esempio n. 13
0
 Object createAtomSeCollectionFromStrings(
     String[] arrayModels, SB loadScript, Map<String, Object> htParams, boolean isAppend) {
   if (!htParams.containsKey("isData")) {
     String oldSep = "\"" + viewer.getDataSeparator() + "\"";
     String tag = "\"" + (isAppend ? "append" : "model") + " inline\"";
     SB sb = new SB();
     sb.append("set dataSeparator \"~~~next file~~~\";\ndata ").append(tag);
     for (int i = 0; i < arrayModels.length; i++) {
       if (i > 0) sb.append("~~~next file~~~");
       sb.append(arrayModels[i]);
     }
     sb.append("end ").append(tag).append(";set dataSeparator ").append(oldSep);
     loadScript.appendSB(sb);
   }
   setLoadState(htParams);
   Logger.info("FileManager.getAtomSetCollectionFromStrings(string[])");
   String[] fullPathNames = new String[arrayModels.length];
   DataReader[] readers = new DataReader[arrayModels.length];
   for (int i = 0; i < arrayModels.length; i++) {
     fullPathNames[i] = "string[" + i + "]";
     readers[i] = newDataReader(arrayModels[i]);
   }
   JmolFilesReaderInterface filesReader =
       newFilesReader(fullPathNames, fullPathNames, null, readers, htParams, isAppend);
   filesReader.run();
   return filesReader.getAtomSetCollection();
 }
Esempio n. 14
0
  public static String getVariableList(
      Map<String, SV> htVariables, int nMax, boolean withSites, boolean definedOnly) {
    SB sb = new SB();
    // user variables only:
    int n = 0;

    String[] list = new String[htVariables.size()];
    for (Map.Entry<String, SV> entry : htVariables.entrySet()) {
      String key = entry.getKey();
      SV var = entry.getValue();
      if ((withSites || !key.startsWith("site_")) && (!definedOnly || key.charAt(0) == '@'))
        list[n++] =
            key
                + (key.charAt(0) == '@'
                    ? " " + var.asString()
                    : " = " + varClip(key, var.escape(), nMax));
    }
    Arrays.sort(list, 0, n);
    for (int i = 0; i < n; i++) if (list[i] != null) sb.append("  ").append(list[i]).append(";\n");
    if (n == 0 && !definedOnly) sb.append("# --no global user variables defined--;\n");
    return sb.toString();
  }
Esempio n. 15
0
 protected void jvxlDecodeContourData(JvxlData jvxlData, String data) throws Exception {
   List<List<Object>> vs = new List<List<Object>>();
   SB values = new SB();
   SB colors = new SB();
   int pt = -1;
   jvxlData.vContours = null;
   if (data == null) return;
   while ((pt = data.indexOf("<jvxlContour", pt + 1)) >= 0) {
     List<Object> v = new List<Object>();
     String s = xr.getXmlData("jvxlContour", data.substring(pt), true, false);
     float value = parseFloatStr(XmlReader.getXmlAttrib(s, "value"));
     values.append(" ").appendF(value);
     int color = getColor(XmlReader.getXmlAttrib(s, "color"));
     short colix = C.getColix(color);
     colors.append(" ").append(Escape.escapeColor(color));
     String fData = JvxlCoder.jvxlDecompressString(XmlReader.getXmlAttrib(s, "data"));
     BS bs = JvxlCoder.jvxlDecodeBitSet(xr.getXmlData("jvxlContour", s, false, false));
     int n = bs.length();
     IsosurfaceMesh.setContourVector(v, n, bs, value, colix, color, SB.newS(fData));
     vs.addLast(v);
   }
   int n = vs.size();
   if (n > 0) {
     jvxlData.vContours = AU.createArrayOfArrayList(n);
     // 3D contour values and colors
     jvxlData.contourColixes = params.contourColixes = new short[n];
     jvxlData.contourValues = params.contoursDiscrete = new float[n];
     for (int i = 0; i < n; i++) {
       jvxlData.vContours[i] = vs.get(i);
       jvxlData.contourValues[i] = ((Float) jvxlData.vContours[i].get(2)).floatValue();
       jvxlData.contourColixes[i] = ((short[]) jvxlData.vContours[i].get(3))[0];
     }
     jvxlData.contourColors = C.getHexCodes(jvxlData.contourColixes);
     Logger.info("JVXL read: " + n + " discrete contours");
     Logger.info("JVXL read: contour values: " + values);
     Logger.info("JVXL read: contour colors: " + colors);
   }
 }
Esempio n. 16
0
 @Override
 protected void readParameters() throws Exception {
   String s = xr.getXmlData("jvxlFileTitle", null, false, false);
   jvxlFileHeaderBuffer = SB.newS(s);
   xr.toTag("jvxlVolumeData");
   String data = tempDataXml = xr.getXmlData("jvxlVolumeData", null, true, false);
   volumetricOrigin.setT(xr.getXmlPoint(data, "origin"));
   isAngstroms = true;
   readVector(0);
   readVector(1);
   readVector(2);
   line = xr.toTag("jvxlSurfaceSet");
   nSurfaces = parseIntStr(XmlReader.getXmlAttrib(line, "count"));
   Logger.info("jvxl file surfaces: " + nSurfaces);
   Logger.info("using default edge fraction base and range");
   Logger.info("using default color fraction base and range");
   cJvxlEdgeNaN = (char) (edgeFractionBase + edgeFractionRange);
 }
Esempio n. 17
0
 private void getStateID(SB sb) {
   V3 v1 = new V3();
   for (Ellipsoid ellipsoid : simpleEllipsoids.values()) {
     Tensor t = ellipsoid.tensor;
     if (!ellipsoid.isValid || t == null) continue;
     sb.append("  Ellipsoid ID ")
         .append(ellipsoid.id)
         .append(" modelIndex ")
         .appendI(t.modelIndex)
         .append(" center ")
         .append(Escape.eP(ellipsoid.center))
         .append(" axes");
     for (int i = 0; i < 3; i++) {
       v1.setT(t.eigenVectors[i]);
       v1.scale(ellipsoid.lengths[i]);
       sb.append(" ").append(Escape.eP(v1));
     }
     sb.append(" " + getColorCommandUnk("", ellipsoid.colix, translucentAllowed));
     if (ellipsoid.options != null) sb.append(" options ").append(PT.esc(ellipsoid.options));
     if (!ellipsoid.isOn) sb.append(" off");
     sb.append(";\n");
   }
 }
Esempio n. 18
0
 /**
  * delivers file contents and directory listing for a ZIP/JAR file into sb
  *
  * @param name
  * @param header
  * @param fileData
  * @return name of entry
  */
 private String getObjectAsSections(String name, String header, Map<String, String> fileData) {
   if (name == null) return null;
   String[] subFileList = null;
   boolean asBinaryString = false;
   String name0 = name.replace('\\', '/');
   if (name.indexOf(":asBinaryString") >= 0) {
     asBinaryString = true;
     name = name.substring(0, name.indexOf(":asBinaryString"));
   }
   SB sb = null;
   if (fileData.containsKey(name0)) return name0;
   if (name.indexOf("#JMOL_MODEL ") >= 0) {
     fileData.put(name0, name0 + "\n");
     return name0;
   }
   String fullName = name;
   if (name.indexOf("|") >= 0) {
     subFileList = PT.split(name, "|");
     name = subFileList[0];
   }
   BufferedInputStream bis = null;
   try {
     Object t =
         getBufferedInputStreamOrErrorMessageFromName(name, fullName, false, false, null, false);
     if (t instanceof String) {
       fileData.put(name0, (String) t + "\n");
       return name0;
     }
     bis = (BufferedInputStream) t;
     if (JmolBinary.isCompoundDocumentS(bis)) {
       JmolDocument doc = (JmolDocument) Interface.getOptionInterface("io2.CompoundDocument");
       doc.setStream(bis, true);
       doc.getAllDataMapped(name.replace('\\', '/'), "Molecule", fileData);
     } else if (JmolBinary.isZipS(bis)) {
       JmolBinary.getAllZipData(bis, subFileList, name.replace('\\', '/'), "Molecule", fileData);
     } else if (asBinaryString) {
       // used for Spartan binary file reading
       JmolDocument bd = (JmolDocument) Interface.getOptionInterface("io2.BinaryDocument");
       bd.setStream(bis, false);
       sb = new SB();
       // note -- these headers must match those in ZipUtil.getAllData and
       // CompoundDocument.getAllData
       if (header != null) sb.append("BEGIN Directory Entry " + name0 + "\n");
       try {
         while (true) sb.append(Integer.toHexString(bd.readByte() & 0xFF)).appendC(' ');
       } catch (Exception e1) {
         sb.appendC('\n');
       }
       if (header != null) sb.append("\nEND Directory Entry " + name0 + "\n");
       fileData.put(name0, sb.toString());
     } else {
       BufferedReader br =
           JmolBinary.getBufferedReader(
               JmolBinary.isGzipS(bis)
                   ? new BufferedInputStream(JmolBinary.newGZIPInputStream(bis))
                   : bis,
               null);
       String line;
       sb = new SB();
       if (header != null) sb.append("BEGIN Directory Entry " + name0 + "\n");
       while ((line = br.readLine()) != null) {
         sb.append(line);
         sb.appendC('\n');
       }
       br.close();
       if (header != null) sb.append("\nEND Directory Entry " + name0 + "\n");
       fileData.put(name0, sb.toString());
     }
   } catch (Exception ioe) {
     fileData.put(name0, ioe.toString());
   }
   if (bis != null)
     try {
       bis.close();
     } catch (Exception e) {
       //
     }
   if (!fileData.containsKey(name0)) fileData.put(name0, "FILE NOT FOUND: " + name0 + "\n");
   return name0;
 }
Esempio n. 19
0
 public Object getBufferedInputStreamOrErrorMessageFromName(
     String name,
     String fullName,
     boolean showMsg,
     boolean checkOnly,
     byte[] outputBytes,
     boolean allowReader) {
   byte[] cacheBytes = null;
   if (outputBytes == null) {
     cacheBytes =
         (fullName == null || pngjCache == null
             ? null
             : JmolBinary.getCachedPngjBytes(this, fullName));
     if (cacheBytes == null) cacheBytes = (byte[]) cacheGet(name, true);
   }
   BufferedInputStream bis = null;
   Object ret = null;
   String errorMessage = null;
   try {
     if (cacheBytes == null) {
       boolean isPngjBinaryPost = (name.indexOf("?POST?_PNGJBIN_") >= 0);
       boolean isPngjPost = (isPngjBinaryPost || name.indexOf("?POST?_PNGJ_") >= 0);
       if (name.indexOf("?POST?_PNG_") > 0 || isPngjPost) {
         String[] errMsg = new String[1];
         byte[] bytes = viewer.getImageAsBytes(isPngjPost ? "PNGJ" : "PNG", 0, 0, -1, errMsg);
         if (errMsg[0] != null) return errMsg[0];
         if (isPngjBinaryPost) {
           outputBytes = bytes;
           name = PT.simpleReplace(name, "?_", "=_");
         } else {
           name = new SB().append(name).append("=").appendSB(Base64.getBase64(bytes)).toString();
         }
       }
       int iurl = urlTypeIndex(name);
       boolean isURL = (iurl >= 0);
       String post = null;
       if (isURL && (iurl = name.indexOf("?POST?")) >= 0) {
         post = name.substring(iurl + 6);
         name = name.substring(0, iurl);
       }
       boolean isApplet = (appletDocumentBaseURL != null);
       if (name.indexOf(".png") >= 0 && pngjCache == null && viewer.cachePngFiles())
         JmolBinary.cachePngjFile(this, null);
       if (isApplet || isURL) {
         if (isApplet && isURL && appletProxy != null)
           name = appletProxy + "?url=" + urlEncode(name);
         URL url =
             (isApplet
                 ? new URL(appletDocumentBaseURL, name, null)
                 : new URL((URL) null, name, null));
         if (checkOnly) return null;
         name = url.toString();
         if (showMsg && name.toLowerCase().indexOf("password") < 0)
           Logger.info("FileManager opening 1 " + name);
         ret = viewer.apiPlatform.getBufferedURLInputStream(url, outputBytes, post);
         byte[] bytes = null;
         if (ret instanceof SB) {
           SB sb = (SB) ret;
           if (allowReader && !JmolBinary.isBase64(sb)) return JmolBinary.getBR(sb.toString());
           bytes = JmolBinary.getBytesFromSB(sb);
         } else if (PT.isAB(ret)) {
           bytes = (byte[]) ret;
         }
         if (bytes != null) ret = JmolBinary.getBIS(bytes);
       } else if ((cacheBytes = (byte[]) cacheGet(name, true)) == null) {
         if (showMsg) Logger.info("FileManager opening 2 " + name);
         ret = viewer.apiPlatform.getBufferedFileInputStream(name);
       }
       if (ret instanceof String) return ret;
     }
     bis = (cacheBytes == null ? (BufferedInputStream) ret : JmolBinary.getBIS(cacheBytes));
     if (checkOnly) {
       bis.close();
       bis = null;
     }
     return bis;
   } catch (Exception e) {
     try {
       if (bis != null) bis.close();
     } catch (IOException e1) {
     }
     errorMessage = "" + e;
   }
   return errorMessage;
 }
Esempio n. 20
0
 protected String skipComments(boolean allowBlankLines) throws Exception {
   SB sb = new SB();
   while (readLine() != null && (allowBlankLines && line.length() == 0 || line.indexOf("#") == 0))
     sb.append(line).appendC('\n');
   return sb.toString();
 }
Esempio n. 21
0
  public Object getUnzippedReaderOrStreamFromName(
      String name,
      byte[] bytes,
      boolean allowZipStream,
      boolean forceInputStream,
      boolean isTypeCheckOnly,
      boolean doSpecialLoad,
      Map<String, Object> htParams) {
    String[] subFileList = null;
    String[] info = (bytes == null && doSpecialLoad ? getSpartanFileList(name) : null);
    String name00 = name;
    if (info != null) {
      if (isTypeCheckOnly) return info;
      if (info[2] != null) {
        String header = info[1];
        Map<String, String> fileData = new Hashtable<String, String>();
        if (info.length == 3) {
          // we need information from the output file, info[2]
          String name0 = getObjectAsSections(info[2], header, fileData);
          fileData.put("OUTPUT", name0);
          info = JmolBinary.spartanFileList(name, fileData.get(name0));
          if (info.length == 3) {
            // might have a second option
            name0 = getObjectAsSections(info[2], header, fileData);
            fileData.put("OUTPUT", name0);
            info = JmolBinary.spartanFileList(info[1], fileData.get(name0));
          }
        }
        // load each file individually, but return files IN ORDER
        SB sb = new SB();
        if (fileData.get("OUTPUT") != null) sb.append(fileData.get(fileData.get("OUTPUT")));
        String s;
        for (int i = 2; i < info.length; i++) {
          name = info[i];
          name = getObjectAsSections(name, header, fileData);
          Logger.info("reading " + name);
          s = fileData.get(name);
          sb.append(s);
        }
        s = sb.toString();
        if (spardirCache == null) spardirCache = new Hashtable<String, byte[]>();
        spardirCache.put(name00.replace('\\', '/'), s.getBytes());
        return JmolBinary.getBR(s);
      }
      // continuing...
      // here, for example, for an SPT file load that is not just a type check
      // (type check is only for application file opening and drag-drop to
      // determine if
      // script or load command should be used)
    }

    if (bytes == null && pngjCache != null) {
      bytes = JmolBinary.getCachedPngjBytes(this, name);
      if (bytes != null && htParams != null) htParams.put("sourcePNGJ", Boolean.TRUE);
    }
    String fullName = name;
    if (name.indexOf("|") >= 0) {
      subFileList = PT.split(name, "|");
      if (bytes == null) Logger.info("FileManager opening 3 " + name);
      name = subFileList[0];
    }
    Object t =
        (bytes == null
            ? getBufferedInputStreamOrErrorMessageFromName(
                name, fullName, true, false, null, !forceInputStream)
            : JmolBinary.getBIS(bytes));
    try {
      if (t instanceof String) return t;
      if (t instanceof BufferedReader) return t;
      BufferedInputStream bis = JmolBinary.getUnzippedInputStream((BufferedInputStream) t);
      if (JmolBinary.isCompoundDocumentS(bis)) {
        JmolDocument doc = (JmolDocument) Interface.getOptionInterface("io2.CompoundDocument");
        doc.setStream(bis, true);
        return JmolBinary.getBR(doc.getAllDataFiles("Molecule", "Input").toString());
      }
      if (JmolBinary.isPickleS(bis)) return bis;
      bis = JmolBinary.checkPngZipStream(bis);
      if (JmolBinary.isZipS(bis)) {
        if (allowZipStream) return JmolBinary.newZipInputStream(bis);
        Object o = JmolBinary.getZipFileContents(bis, subFileList, 1, forceInputStream);
        return (o instanceof String ? JmolBinary.getBR((String) o) : o);
      }
      return (forceInputStream ? bis : JmolBinary.getBufferedReader(bis, null));
    } catch (Exception ioe) {
      return ioe.toString();
    }
  }
Esempio n. 22
0
  public boolean slabPolygons(Object[] slabObject, boolean allowCap) {
    if (polygonCount0 < 0) return false; // disabled for some surface types
    int slabType = ((Integer) slabObject[0]).intValue();
    if (slabType == T.none || slabType == T.brillouin) {
      if (bsSlabDisplay != null && (polygonCount0 != 0 || vertexCount0 != 0)) {
        pc = polygonCount0;
        vc = vertexCount0;
        polygonCount0 = vertexCount0 = 0;
        normixCount = (isTriangleSet ? pc : vc);
        bsSlabDisplay.setBits(0, (pc == 0 ? vc : pc));
        slabOptions = new SB().append(meshType + " slab none");
        bsSlabGhost = null;
        slabMeshType = T.none;
      }
      if (slabType == T.none) return false;
    }
    Object slabbingObject = slabObject[1];
    boolean andCap = ((Boolean) slabObject[2]).booleanValue() && !(slabType == T.brillouin);
    if (andCap && !allowCap) return false;
    Object[] colorData = (Object[]) slabObject[3];
    boolean isGhost = (colorData != null);
    if (bsSlabDisplay == null || polygonCount0 == 0 && vertexCount0 == 0) {
      polygonCount0 = pc;
      vertexCount0 = vc;
      bsSlabDisplay = BSUtil.setAll(pc == 0 ? vc : pc);
      bsSlabGhost = null;
      if (pc == 0 && vc == 0) return false;
    } else if (isMerged) {
      if (pc == 0) bsSlabDisplay.setBits(mergeVertexCount0, vc);
      else bsSlabDisplay.setBits(mergePolygonCount0, pc);
    }

    if (isGhost) {
      if (bsSlabGhost == null) bsSlabGhost = new BS();
      slabMeshType = ((Integer) colorData[0]).intValue();
      slabColix = ((Short) colorData[1]).shortValue();
      // if (C.isColixColorInherited(slabColix))
      // slabColix = C.copyColixTranslucency(slabColix, colix);
      andCap = false;
      colix = C.getColixTranslucent3(colix, false, 0);
    }

    SB sb = new SB();
    sb.append(andCap ? " cap " : " slab ");
    if (isGhost) {
      sb.append("translucent ").appendF(C.getColixTranslucencyFractional(slabColix)).append(" ");
      String s = C.getHexCode(slabColix);
      if (s != null) sb.append(s).append(" ");
      if (slabMeshType == T.mesh) sb.append("mesh ");
    }
    switch (slabType) {
      case T.brillouin:
        sb.append("brillouin");
        slabBrillouin((P3[]) slabbingObject);
        break;
      case T.decimal:
        getIntersection(
            0,
            null,
            null,
            null,
            null,
            (BS) slabbingObject,
            null,
            andCap,
            false,
            T.decimal,
            isGhost);
        break;
      case T.plane:
        P4 plane = (P4) slabbingObject;
        sb.append(Escape.eP4(plane));
        getIntersection(0, plane, null, null, null, null, null, andCap, false, T.plane, isGhost);
        break;
      case T.unitcell:
      case T.boundbox:
        P3[] box = (P3[]) slabbingObject;
        sb.append("within ").append(Escape.eAP(box));
        P4[] faces = BoxInfo.getFacesFromCriticalPoints(box);
        for (int i = 0; i < faces.length; i++) {
          getIntersection(
              0, faces[i], null, null, null, null, null, andCap, false, T.plane, isGhost);
        }
        break;
      case T.data:
        getIntersection(
            0,
            null,
            null,
            null,
            (float[]) slabbingObject,
            null,
            null,
            false,
            false,
            T.min,
            isGhost);
        break;
      case T.within:
      case T.range:
      case T.mesh:
        Object[] o = (Object[]) slabbingObject;
        float distance = ((Float) o[0]).floatValue();
        switch (slabType) {
          case T.within:
            P3[] points = (P3[]) o[1];
            BS bs = (BS) o[2];
            sb.append("within ")
                .appendF(distance)
                .append(bs == null ? Escape.e(points) : Escape.e(bs));
            getIntersection(
                distance,
                null,
                points,
                null,
                null,
                null,
                null,
                andCap,
                false,
                (distance > 0 ? T.distance : T.sphere),
                isGhost);
            break;
          case T.range:
            // isosurface slab within range x.x y.y
            // if y.y < x.x then this effectively means "NOT within range y.y x.x"
            if (vvs == null) return false;
            float distanceMax = ((Float) o[1]).floatValue();
            sb.append("within range ").appendF(distance).append(" ").appendF(distanceMax);
            bs = (distanceMax < distance ? BSUtil.copy(bsSlabDisplay) : null);
            getIntersection(
                distance, null, null, null, null, null, null, andCap, false, T.min, isGhost);
            BS bsA = (bs == null ? null : BSUtil.copy(bsSlabDisplay));
            BSUtil.copy2(bs, bsSlabDisplay);
            getIntersection(
                distanceMax, null, null, null, null, null, null, andCap, false, T.max, isGhost);
            if (bsA != null) bsSlabDisplay.or(bsA);
            break;
          case T.mesh:
            // NOT IMPLEMENTED
            MeshSurface mesh = (MeshSurface) o[1];
            // distance = -1;
            getIntersection(
                0,
                null,
                null,
                null,
                null,
                null,
                mesh,
                andCap,
                false,
                distance < 0 ? T.min : T.max,
                isGhost);
            // TODO: unresolved how exactly to store this in the state
            // -- must indicate exact set of triangles to slab and how!
            break;
        }
        break;
    }
    String newOptions = sb.toString();
    if (slabOptions == null) slabOptions = new SB();
    if (slabOptions.indexOf(newOptions) < 0)
      slabOptions.append(slabOptions.length() > 0 ? "; " : "").append(meshType).append(newOptions);
    return true;
  }