Exemple #1
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"));
 }
 public static String fixFileNameVariables(String format, String fname) {
   String str = PT.simpleReplace(format, "%FILE", fname);
   if (str.indexOf("%LC") < 0) return str;
   fname = fname.toLowerCase();
   str = PT.simpleReplace(str, "%LCFILE", fname);
   if (fname.length() == 4) str = PT.simpleReplace(str, "%LC13", fname.substring(1, 3));
   return str;
 }
Exemple #3
0
 private boolean checkID(String thisID) {
   ellipsoidSet = new Lst<Ellipsoid>();
   if (thisID == null) return false;
   thisID = thisID.toLowerCase();
   if (PT.isWild(thisID)) {
     for (Entry<String, Ellipsoid> e : simpleEllipsoids.entrySet()) {
       String key = e.getKey().toLowerCase();
       if (PT.isMatch(key, thisID, true, true)) ellipsoidSet.addLast(e.getValue());
     }
   }
   Ellipsoid e = simpleEllipsoids.get(thisID);
   if (e != null) ellipsoidSet.addLast(e);
   return (ellipsoidSet.size() > 0);
 }
 public static String setScriptFileReferences(
     String script, String localPath, String remotePath, String scriptPath) {
   if (localPath != null) script = setScriptFileRefs(script, localPath, true);
   if (remotePath != null) script = setScriptFileRefs(script, remotePath, false);
   script = PT.simpleReplace(script, "\1\"", "\"");
   if (scriptPath != null) {
     while (scriptPath.endsWith("/"))
       scriptPath = scriptPath.substring(0, scriptPath.length() - 1);
     for (int ipt = 0; ipt < scriptFilePrefixes.length; ipt++) {
       String tag = scriptFilePrefixes[ipt];
       script = PT.simpleReplace(script, tag + ".", tag + scriptPath);
     }
   }
   return script;
 }
 public Object getFileAsBytes(String name, OC out, boolean allowZip) {
   // ?? used by eval of "WRITE FILE"
   // will be full path name
   if (name == null) return null;
   String fullName = name;
   String[] subFileList = null;
   if (name.indexOf("|") >= 0) {
     subFileList = PT.split(name, "|");
     name = subFileList[0];
     allowZip = true;
   }
   Object t =
       getBufferedInputStreamOrErrorMessageFromName(name, fullName, false, false, null, false);
   if (t instanceof String) return "Error:" + t;
   try {
     BufferedInputStream bis = (BufferedInputStream) t;
     Object bytes =
         (out != null
                 || !allowZip
                 || subFileList == null
                 || subFileList.length <= 1
                 || !JmolBinary.isZipS(bis) && !JmolBinary.isPngZipStream(bis)
             ? JmolBinary.getStreamAsBytes(bis, out)
             : JmolBinary.getZipFileContentsAsBytes(bis, subFileList, 1));
     bis.close();
     return bytes;
   } catch (Exception ioe) {
     return ioe.toString();
   }
 }
 /**
  * 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;
 }
Exemple #7
0
  @Override
  protected void readParameters() throws Exception {
    jvxlFileHeaderBuffer = new SB();
    jvxlFileHeaderBuffer.append(readLine()).appendC('\n');
    jvxlFileHeaderBuffer.append(readLine()).appendC('\n');
    String atomLine = readLine();
    String[] tokens = PT.getTokensAt(atomLine, 0);
    ac = parseIntStr(tokens[0]);
    negativeAtomCount = (ac < 0); // MO list
    if (negativeAtomCount) ac = -ac;
    volumetricOrigin.set(
        parseFloatStr(tokens[1]), parseFloatStr(tokens[2]), parseFloatStr(tokens[3]));
    VolumeFileReader.checkAtomLine(
        isXLowToHigh, isAngstroms, tokens[0], atomLine, jvxlFileHeaderBuffer);
    if (!isAngstroms) volumetricOrigin.scale(ANGSTROMS_PER_BOHR);
    for (int i = 0; i < 3; ++i) readVoxelVector(i);
    for (int i = 0; i < ac; ++i) jvxlFileHeaderBuffer.append(readLine() + "\n");

    if (!negativeAtomCount) {
      nSurfaces = 1;
    } else {
      readLine();
      Logger.info("Reading extra CUBE information line: " + line);
      nSurfaces = parseIntStr(line);
    }
  }
 private DataReader newDataReader(Object data) {
   String reader =
       (data instanceof String
           ? "String"
           : PT.isAS(data) ? "Array" : data instanceof List<?> ? "List" : null);
   if (reader == null) return null;
   DataReader dr = (DataReader) Interface.getOptionInterface("io2." + reader + "DataReader");
   return dr.setData(data);
 }
  private static String fixPath(String path) {
    path = path.replace('\\', '/');
    path = PT.simpleReplace(path, "/./", "/");
    int pt = path.lastIndexOf("//") + 1;
    if (pt < 1) pt = path.indexOf(":/") + 1;
    if (pt < 1) pt = path.indexOf("/");
    if (pt < 0) return null;
    String protocol = path.substring(0, pt);
    path = path.substring(pt);

    while ((pt = path.lastIndexOf("/../")) >= 0) {
      int pt0 = path.substring(0, pt).lastIndexOf("/");
      if (pt0 < 0) return PT.simpleReplace(protocol + path, "/../", "/");
      path = path.substring(0, pt0) + path.substring(pt + 3);
    }
    if (path.length() == 0) path = "/";
    return protocol + path;
  }
 private static int getColor(String c) {
   int n = 0;
   try {
     switch (c.charAt(0)) {
       case '[':
         n = CU.getArgbFromString(c);
         break;
       case '0': // 0x
         n = PT.parseIntRadix(c.substring(2), 16);
         break;
       default:
         n = PT.parseIntRadix(c, 10);
     }
     // if (n < 0x1000000)
     // n |= 0xFF000000;
   } catch (Exception e) {
   }
   return n;
 }
 Map<String, Integer> cacheList() {
   Map<String, Integer> map = new Hashtable<String, Integer>();
   for (Map.Entry<String, Object> entry : cache.entrySet())
     map.put(
         entry.getKey(),
         Integer.valueOf(
             PT.isAB(entry.getValue())
                 ? ((byte[]) entry.getValue()).length
                 : entry.getValue().toString().length()));
   return map;
 }
 /**
  * decode vertex data found within <jvxlVertexData> element as created by jvxlEncodeVertexData
  * (see above)
  *
  * @param data tag and contents
  * @param asArray or just addVertexCopy
  * @return Point3f[] if desired
  * @throws Exception
  */
 public P3[] jvxlDecodeVertexData(String data, boolean asArray) throws Exception {
   int vertexCount = parseIntStr(XmlReader.getXmlAttrib(data, "count"));
   if (!asArray) Logger.info("Reading " + vertexCount + " vertices");
   int ptCount = vertexCount * 3;
   P3[] vertices = (asArray ? new P3[vertexCount] : null);
   P3 p = (asArray ? null : new P3());
   float fraction;
   String vData = XmlReader.getXmlAttrib(data, "data");
   String encoding = getEncoding(data);
   if ("none".equals(encoding)) {
     if (vData.length() == 0) vData = xr.getXmlData("jvxlVertexData", data, false, false);
     float[] fdata = PT.parseFloatArray(vData);
     // first point is count -- ignored.
     if (fdata[0] != vertexCount * 3)
       Logger.info(
           "JvxlXmlReader: vertexData count="
               + ((int) fdata[0])
               + "; expected "
               + (vertexCount * 3));
     for (int i = 0, pt = 1; i < vertexCount; i++) {
       p = P3.new3(fdata[pt++], fdata[pt++], fdata[pt++]);
       if (asArray) vertices[i] = p;
       else addVertexCopy(p, 0, i);
     }
   } else {
     P3 min = xr.getXmlPoint(data, "min");
     P3 range = xr.getXmlPoint(data, "max");
     range.sub(min);
     int colorFractionBase = jvxlData.colorFractionBase;
     int colorFractionRange = jvxlData.colorFractionRange;
     String s = JvxlCoder.jvxlDecompressString(vData);
     if (s.length() == 0) s = xr.getXmlData("jvxlVertexData", data, false, false);
     for (int i = 0, pt = -1; i < vertexCount; i++) {
       if (asArray) p = vertices[i] = new P3();
       fraction =
           JvxlCoder.jvxlFractionFromCharacter2(
               s.charAt(++pt), s.charAt(pt + ptCount), colorFractionBase, colorFractionRange);
       p.x = min.x + fraction * range.x;
       fraction =
           JvxlCoder.jvxlFractionFromCharacter2(
               s.charAt(++pt), s.charAt(pt + ptCount), colorFractionBase, colorFractionRange);
       p.y = min.y + fraction * range.y;
       fraction =
           JvxlCoder.jvxlFractionFromCharacter2(
               s.charAt(++pt), s.charAt(pt + ptCount), colorFractionBase, colorFractionRange);
       p.z = min.z + fraction * range.z;
       if (!asArray) addVertexCopy(p, 0, i);
     }
   }
   return vertices;
 }
Exemple #13
0
  @Override
  public void processStartElement(String localName) {
    String[] tokens;
    // System.out.println( " " + localName + " " + atts);
    // System.out.println("xmlchem3d: start " + localName);
    if ("Molecule".equalsIgnoreCase(localName)) {
      asc.newAtomSet();
      asc.setAtomSetName(atts.get("Name"));
      return;
    }

    if ("LinearChain".equalsIgnoreCase(localName)) {
      iGroup = 0;
      iChain++;
    }

    if ("RepeatUnit".equalsIgnoreCase(localName)) {
      iGroup++;
    }

    if ("Atom3d".equalsIgnoreCase(localName)) {
      atom = new Atom();
      atom.elementSymbol = atts.get("Components");
      atom.atomName = atts.get("ID");
      atom.atomSerial = ++iAtom;
      if (iChain >= 0) parent.setChainID(atom, "" + (char) ((iChain - 1) % 26 + 'A'));
      atom.group3 = "UNK";
      if (iGroup == 0) iGroup = 1;
      atom.sequenceNumber = iGroup;
      String xyz = atts.get("XYZ");
      if (xyz != null) {
        tokens = getTokensStr(xyz.replace(',', ' '));
        atom.set(parseFloatStr(tokens[0]), parseFloatStr(tokens[1]), parseFloatStr(tokens[2]));
      }
      boolean isBackbone = "1".equals(atts.get("IsBackboneAtom"));
      if (isBackbone) bsBackbone.set(iAtom);
      return;
    }
    if ("Bond".equalsIgnoreCase(localName)) {
      String[] atoms = PT.split(atts.get("Connects"), ",");
      int order = 1;
      if (atts.containsKey("Type")) {
        String type = atts.get("Type");
        if (type.equals("Double")) order = 2;
        else if (type.equals("Triple")) order = 3;
      }
      asc.addNewBondFromNames(atoms[0], atoms[1], order);
      return;
    }
  }
 Object getBufferedReaderOrErrorMessageFromName(
     String name, String[] fullPathNameReturn, boolean isBinary, boolean doSpecialLoad) {
   Object data = cacheGet(name, false);
   boolean isBytes = PT.isAB(data);
   byte[] bytes = (isBytes ? (byte[]) data : null);
   if (name.startsWith("cache://")) {
     if (data == null) return "cannot read " + name;
     if (isBytes) {
       bytes = (byte[]) data;
     } else {
       return JmolBinary.getBR((String) data);
     }
   }
   String[] names = classifyName(name, true);
   if (names == null) return "cannot read file name: " + name;
   if (fullPathNameReturn != null) fullPathNameReturn[0] = names[0].replace('\\', '/');
   return getUnzippedReaderOrStreamFromName(
       names[0], bytes, false, isBinary, false, doSpecialLoad, null);
 }
 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();
 }
Exemple #16
0
 public static String prompt(String label, String data, String[] list, boolean asButtons) {
   try {
     if (!asButtons) return JOptionPane.showInputDialog(label, data);
     if (data != null) list = PT.split(data, "|");
     int i =
         JOptionPane.showOptionDialog(
             null,
             label,
             "Jmol prompt",
             JOptionPane.DEFAULT_OPTION,
             JOptionPane.INFORMATION_MESSAGE,
             null,
             list,
             list[0]);
     // ESCAPE will close the panel with no option selected.
     return (data == null ? "" + i : i == JOptionPane.CLOSED_OPTION ? "null" : list[i]);
   } catch (Throwable e) {
     return "null";
   }
 }
Exemple #17
0
 /**
  * legacy -- for some scripts with early isosurface slabbing
  *
  * @param s
  * @param isCap
  * @return slabInfo object
  */
 public static Object[] getCapSlabObject(String s, boolean isCap) {
   try {
     if (s.indexOf("array") == 0) {
       String[] pts = PT.split(s.substring(6, s.length() - 1), ",");
       return TempArray.getSlabObjectType(
           T.boundbox,
           new P3[] {
             (P3) Escape.uP(pts[0]),
             (P3) Escape.uP(pts[1]),
             (P3) Escape.uP(pts[2]),
             (P3) Escape.uP(pts[3])
           },
           isCap,
           null);
     }
     Object plane = Escape.uP(s);
     if (plane instanceof P4) return TempArray.getSlabObjectType(T.plane, plane, isCap, null);
   } catch (Exception e) {
     //
   }
   return null;
 }
Exemple #18
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");
   }
 }
 void loadImage(String name, String echoName) {
   Object image = null;
   Object info = null;
   String fullPathName = "";
   while (true) {
     if (name == null) break;
     String[] names = classifyName(name, true);
     if (names == null) {
       fullPathName = "cannot read file name: " + name;
       break;
     }
     GenericPlatform apiPlatform = viewer.apiPlatform;
     fullPathName = names[0].replace('\\', '/');
     if (fullPathName.indexOf("|") > 0) {
       Object ret = getFileAsBytes(fullPathName, null, true);
       if (!PT.isAB(ret)) {
         fullPathName = "" + ret;
         break;
       }
       image = (viewer.isJS ? ret : apiPlatform.createImage(ret));
     } else if (viewer.isJS) {
     } else if (urlTypeIndex(fullPathName) >= 0) {
       try {
         image = apiPlatform.createImage(new URL((URL) null, fullPathName, null));
       } catch (Exception e) {
         fullPathName = "bad URL: " + fullPathName;
         break;
       }
     } else {
       image = apiPlatform.createImage(fullPathName);
     }
     /** @j2sNative info = [echoName, fullPathName]; */
     {
       if (image == null) break;
     }
     try {
       if (!apiPlatform.waitForDisplay(info, image)) {
         image = null;
         break;
       }
       /**
        * note -- JavaScript just returns immediately, because we must wait for the image to load,
        * and it is single-threaded
        *
        * @j2sNative fullPathName = null; break;
        */
       {
         if (apiPlatform.getImageWidth(image) < 1) {
           fullPathName = "invalid or missing image " + fullPathName;
           image = null;
         }
         break;
       }
     } catch (Exception e) {
       System.out.println(e.toString());
       fullPathName = e.toString() + " opening 4 " + fullPathName;
       image = null;
       break;
     }
   }
   viewer.loadImageData(image, fullPathName, echoName, null);
 }
 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;
 }
  @Override
  protected String readColorData() {
    if (!jvxlDataIsColorMapped) return "";
    // overloads SurfaceReader
    // standard jvxl file read for color

    int vertexCount = jvxlData.vertexCount = meshData.vertexCount;
    // the problem is that the new way to read data in Marching Cubes
    // is to ignore all points that are NaN. But then we also have to
    // remove those points from the color string.

    short[] colixes = meshData.vertexColixes;
    float[] vertexValues = meshData.vertexValues;
    /*
     * haveReadColorData?
     = (isJvxl ? jvxlColorDataRead : "");
    if (isJvxl && strValueTemp.length() == 0) {
      Logger
          .error("You cannot use JVXL data to map onto OTHER data, because it only contains the data for one surface. Use ISOSURFACE \"file.jvxl\" not ISOSURFACE .... MAP \"file.jvxl\".");
      return "";
    }
    */

    if ("none".equals(jvxlColorEncodingRead)) {
      jvxlData.vertexColors = new int[vertexCount];
      int[] nextc = new int[1];
      int n = PT.parseIntNext(jvxlColorDataRead, nextc);
      n = Math.min(n, vertexCount);
      String[] tokens = PT.getTokens(jvxlColorDataRead.substring(nextc[0]));
      boolean haveTranslucent = false;
      float trans = jvxlData.translucency;
      int lastColor = 0;
      for (int i = 0; i < n; i++)
        // colix will be one of 8 shades of translucent if A in ARGB is not FF.
        try {
          int c = getColor(tokens[i]);
          if (c == 0) c = lastColor;
          else lastColor = c;
          colixes[i] = C.getColixTranslucent(jvxlData.vertexColors[i] = c);
          if (C.isColixTranslucent(colixes[i])) haveTranslucent = true;
          else if (trans != 0) colixes[i] = C.getColixTranslucent3(colixes[i], true, trans);
        } catch (Exception e) {
          Logger.info("JvxlXmlReader: Cannot interpret color code: " + tokens[i]);
          // ignore this color if parsing error
        }
      if (haveTranslucent && trans == 0) {
        // set to show in pass2
        jvxlData.translucency = 0.5f;
      }
      return "-";
    }
    if (params.colorEncoder == null) params.colorEncoder = new ColorEncoder(null);
    params.colorEncoder.setColorScheme(null, false);
    params.colorEncoder.setRange(
        params.valueMappedToRed, params.valueMappedToBlue, params.isColorReversed);
    Logger.info(
        "JVXL reading color data mapped min/max: "
            + params.mappedDataMin
            + "/"
            + params.mappedDataMax
            + " for "
            + vertexCount
            + " vertices."
            + " using encoding keys "
            + colorFractionBase
            + " "
            + colorFractionRange);
    Logger.info(
        "mapping red-->blue for "
            + params.valueMappedToRed
            + " to "
            + params.valueMappedToBlue
            + " colorPrecision:"
            + jvxlData.isJvxlPrecisionColor);
    boolean getValues = (Float.isNaN(valueMin));
    if (getValues) setValueMinMax();
    float contourPlaneMinimumValue = Float.MAX_VALUE;
    float contourPlaneMaximumValue = -Float.MAX_VALUE;
    if (colixes == null || colixes.length < vertexCount)
      meshData.vertexColixes = colixes = new short[vertexCount];
    // hasColorData = true;
    short colixNeg = 0, colixPos = 0;
    if (params.colorBySign) {
      colixPos = C.getColix(params.isColorReversed ? params.colorNeg : params.colorPos);
      colixNeg = C.getColix(params.isColorReversed ? params.colorPos : params.colorNeg);
    }
    int vertexIncrement = meshData.vertexIncrement;
    // here's the problem: we are assuming here that vertexCount == nPointsRead
    boolean needContourMinMax = (params.mappedDataMin == Float.MAX_VALUE);
    for (int i = 0; i < vertexCount; i += vertexIncrement) {
      float value;
      if (getValues) value = vertexValues[i] = getNextValue();
      else value = vertexValues[i];
      if (needContourMinMax) {
        if (value < contourPlaneMinimumValue) contourPlaneMinimumValue = value;
        if (value > contourPlaneMaximumValue) contourPlaneMaximumValue = value;
      }
    }
    if (needContourMinMax) {
      params.mappedDataMin = contourPlaneMinimumValue;
      params.mappedDataMax = contourPlaneMaximumValue;
    }
    if (jvxlData.colorScheme != null)
      for (int i = 0; i < vertexCount; i += vertexIncrement) {
        float value = vertexValues[i];
        // note: these are just default colorings
        // orbital color had a bug through 11.2.6/11.3.6
        if (marchingSquares != null && params.isContoured) {
          marchingSquares.setContourData(i, value);
          continue;
        }
        short colix =
            (!params.colorBySign
                ? params.colorEncoder.getColorIndex(value)
                : (params.isColorReversed ? value > 0 : value <= 0) ? colixNeg : colixPos);
        colixes[i] = C.getColixTranslucent3(colix, true, jvxlData.translucency);
      }
    return jvxlColorDataRead + "\n";
  }
Exemple #22
0
  private WebExport(JmolViewer vwr, HistoryFile hFile) {
    super(new BorderLayout());

    historyFile = hFile;
    remoteAppletPath = historyFile.getProperty("webMakerAppletPath", "..");
    localAppletPath = historyFile.getProperty("webMakerLocalAppletPath", "..");
    pageAuthorName = historyFile.getProperty("webMakerPageAuthorName",
        GT._("Jmol Web Page Maker"));
    popInWidth=PT.parseInt(historyFile.getProperty("webMakerPopInWidth", "300"));
    popInHeight=PT.parseInt(historyFile.getProperty("webMakerPopInHeight", "300"));
    scriptButtonPercent = PT.parseInt(historyFile.getProperty(
        "webMakerScriptButtonPercent", "60"));

    //Define the tabbed pane
    JTabbedPane mainTabs = new JTabbedPane();

    //Create file chooser
    JFileChooser fc = new JFileChooser();

    webPanels = new WebPanel[2];
    
    if (runStatus != STAND_ALONE) {
      //Add tabs to the tabbed pane

      JPanel introPanel = new JPanel();
      String introFileName = "WebExportIntro";
      URL url = GuiMap.getHtmlResource(this, introFileName);
      if (url == null) {
        System.err.println(GT.o(GT._("Couldn't find file: {0}"), introFileName+".html"));
      }
      JEditorPane intro = new JEditorPane();
      if (url != null) {
        try {
          intro.setPage(url);
        } catch (IOException e) {
          System.err.println("Attempted to read a bad URL: " + url);
        }
      }
      intro.setEditable(false);
      JScrollPane introPane = new JScrollPane(intro);
      introPane.setMaximumSize(new Dimension(450, 350));
      introPane.setPreferredSize(new Dimension(400, 300));
      introPanel.setLayout(new BorderLayout());
      introPanel.add(introPane);
      introPanel.setMaximumSize(new Dimension(450, 350));
      introPanel.setPreferredSize(new Dimension(400, 300));

      mainTabs.add(GT._("Introduction"), introPanel);

      webPanels[0] = new PopInJmol(vwr, fc, webPanels, 0);
      webPanels[1] = new ScriptButtons(vwr, fc, webPanels, 1);

      int w = Integer.parseInt(historyFile.getProperty("webMakerInfoWidth",
          "300"));
      int h = Integer.parseInt(historyFile.getProperty("webMakerInfoHeight",
          "350"));

      mainTabs.addTab(GT._("Pop-In Jmol"), webPanels[0].getPanel(w, h));
      mainTabs.addTab(GT._("ScriptButton Jmol"), webPanels[1].getPanel(w, h));

      // Uncomment to activate the test panel
      //    Test TestCreator = new Test((Viewer)vwr);
      //    JComponent Test = TestCreator.Panel();
      //    Maintabs.addTab("Tests",Test);
    }

    showMoleculesAndOrbitals = (runStatus == STAND_ALONE || JmolViewer
        .checkOption(vwr, "webMakerAllTabs"));
    if (showMoleculesAndOrbitals) {
      //mainTabs.addTab("Orbitals", (new Orbitals()).getPanel());
      //mainTabs.addTab("Molecules", (new Molecules()).getPanel());
    }

    //The LogPanel should always be the last one

    mainTabs.addTab(GT._("Log"), LogPanel.getPanel());

    //Add the tabbed pane to this panel
    add(mainTabs);

    //Create the small log

    add(LogPanel.getMiniPanel(), BorderLayout.SOUTH);

    //Uncomment the following line to use scrolling tabs.
    //tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

  }
  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();
    }
  }
 /**
  * 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;
 }
 /**
  * decode triangle data found within <jvxlTriangleData> element as created with
  * jvxlEncodeTriangleData (see above)
  *
  * @param tdata tag and contents
  * @param edgeData
  * @param colorData
  * @throws Exception
  */
 void jvxlDecodeTriangleData(String tdata, String edgeData, String colorData) throws Exception {
   int nTriangles = parseIntStr(XmlReader.getXmlAttrib(tdata, "count"));
   if (nTriangles < 0) return;
   int[] nextc = new int[1];
   int nColors = (colorData == null ? -1 : PT.parseIntNext(colorData, nextc));
   int color = 0;
   Logger.info("Reading " + nTriangles + " triangles");
   String encoding = getEncoding(tdata);
   tdata = getData(tdata, "jvxlTriangleData");
   String edata = getData(edgeData, "jvxlTriangleEdgeData");
   int[] vertex = new int[3];
   int[] nextp = new int[1];
   int[] nexte = null;
   int edgeMask = 7;
   boolean haveEdgeInfo;
   boolean haveEncoding = !"none".equals(encoding);
   if (haveEncoding) {
     tdata = JvxlCoder.jvxlDecompressString(tdata);
     edata = JvxlCoder.jvxlDecompressString(edata).trim();
     haveEdgeInfo = (edata.length() == nTriangles);
   } else {
     int n = PT.parseIntNext(tdata, nextp);
     haveEdgeInfo = (edata.length() > 0);
     if (haveEdgeInfo) {
       nexte = new int[1];
       PT.parseIntNext(edata, nexte); // throw away count
     } else if (n > 0) {
       Logger.info("JvxlXmlReader: jvxlTriangleEdgeData count=" + n + "; expected " + nTriangles);
     }
   }
   for (int i = 0, v = 0, p = 0, pt = -1; i < nTriangles; ) {
     if (haveEncoding) {
       char ch = tdata.charAt(++pt);
       int diff;
       switch (ch) {
         case '!':
           diff = 0;
           break;
         case '+':
         case '.':
         case ' ':
         case '\n':
         case '\r':
         case '\t':
         case ',':
           continue;
         case '-':
         case '0':
         case '1':
         case '2':
         case '3':
         case '4':
         case '5':
         case '6':
         case '7':
         case '8':
         case '9':
           nextp[0] = pt;
           diff = PT.parseIntNext(tdata, nextp);
           pt = nextp[0] - 1;
           break;
         default:
           diff = ch - 92; // '\' character
       }
       v += diff;
     } else {
       v = PT.parseIntNext(tdata, nextp) - 1;
     }
     vertex[p] = v;
     if (++p == 3) {
       p = 0;
       if (haveEdgeInfo) {
         edgeMask =
             (nexte == null ? edata.charAt(i) - '0' : javajs.util.PT.parseIntNext(edata, nexte));
         if (edgeMask < 0 || edgeMask > 7) edgeMask = 7;
       }
       if (nColors > 0) {
         int c = PT.parseIntNext(colorData, nextc);
         if (c == Integer.MIN_VALUE) nColors = 0;
         else color = c;
         nColors--;
       }
       addTriangleCheck(vertex[0], vertex[1], vertex[2], edgeMask, 0, false, color);
       i++;
     }
   }
 }
Exemple #26
0
 static String nextStringToken(ScriptTokenizer eachParam, boolean removeQuotes) {
   String s = eachParam.nextToken();
   return (removeQuotes && s.charAt(0) == '"' && s.endsWith("\"") && s.length() > 1
       ? PT.trimQuotes(s)
       : s);
 }
 /**
  * [0] and [2] may return same as [1] in the case of a local unsigned applet.
  *
  * @param name
  * @param isFullLoad false only when just checking path
  * @return [0] full path name, [1] file name without path, [2] full URL
  */
 private String[] classifyName(String name, boolean isFullLoad) {
   if (name == null) return new String[] {null};
   boolean doSetPathForAllFiles = (pathForAllFiles.length() > 0);
   if (name.startsWith("?")) {
     if ((name = viewer.dialogAsk("Load", name.substring(1))) == null)
       return new String[] {isFullLoad ? "#CANCELED#" : null};
     doSetPathForAllFiles = false;
   }
   GenericFileInterface file = null;
   URL url = null;
   String[] names = null;
   if (name.startsWith("cache://")) {
     names = new String[3];
     names[0] = names[2] = name;
     names[1] = stripPath(names[0]);
     return names;
   }
   name = viewer.resolveDatabaseFormat(name);
   if (name.indexOf(":") < 0 && name.indexOf("/") != 0)
     name = addDirectory(viewer.getDefaultDirectory(), name);
   if (appletDocumentBaseURL == null) {
     // This code is for the app or signed local applet
     // -- no local file reading for headless
     if (urlTypeIndex(name) >= 0
         || viewer.haveAccess(ACCESS.NONE)
         || viewer.haveAccess(ACCESS.READSPT) && !name.endsWith(".spt") && !name.endsWith("/")) {
       try {
         url = new URL((URL) null, name, null);
       } catch (MalformedURLException e) {
         return new String[] {isFullLoad ? e.toString() : null};
       }
     } else {
       file = viewer.apiPlatform.newFile(name);
       String s = file.getFullPath();
       // local unsigned applet may have access control issue here and get a null return
       String fname = file.getName();
       names =
           new String[] {
             (s == null ? fname : s), fname, (s == null ? fname : "file:/" + s.replace('\\', '/'))
           };
     }
   } else {
     // This code is only for the non-local applet
     try {
       if (name.indexOf(":\\") == 1 || name.indexOf(":/") == 1) name = "file:/" + name;
       //        else if (name.indexOf("/") == 0 && viewer.isSignedApplet())
       //        name = "file:" + name;
       url = new URL(appletDocumentBaseURL, name, null);
     } catch (MalformedURLException e) {
       return new String[] {isFullLoad ? e.toString() : null};
     }
   }
   if (url != null) {
     names = new String[3];
     names[0] = names[2] = url.toString();
     names[1] = stripPath(names[0]);
   }
   if (doSetPathForAllFiles) {
     String name0 = names[0];
     names[0] = pathForAllFiles + names[1];
     Logger.info("FileManager substituting " + name0 + " --> " + names[0]);
   }
   if (isFullLoad && (file != null || urlTypeIndex(names[0]) == URL_LOCAL)) {
     String path = (file == null ? PT.trim(names[0].substring(5), "/") : names[0]);
     int pt = path.length() - names[1].length() - 1;
     if (pt > 0) {
       path = path.substring(0, pt);
       setLocalPath(viewer, path, true);
     }
   }
   return names;
 }