src/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlWriter.java

Mon, 16 Oct 2017 16:07:48 +0800

author
aoqi
date
Mon, 16 Oct 2017 16:07:48 +0800
changeset 2893
ca5783d9a597
parent 2800
f6923d26b0fb
parent 2525
2eb010b6cb22
child 3295
859dc787b52b
permissions
-rw-r--r--

merge

     1 /*
     2  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.doclets.formats.html.markup;
    28 import java.io.*;
    29 import java.util.*;
    30 import java.util.regex.Matcher;
    31 import java.util.regex.Pattern;
    33 import com.sun.tools.doclets.internal.toolkit.*;
    34 import com.sun.tools.doclets.internal.toolkit.util.*;
    36 /**
    37  * Class for the Html format code generation.
    38  * Initializes PrintWriter with FileWriter, to enable print
    39  * related methods to generate the code to the named File through FileWriter.
    40  *
    41  *  <p><b>This is NOT part of any supported API.
    42  *  If you write code that depends on this, you do so at your own risk.
    43  *  This code and its internal interfaces are subject to change or
    44  *  deletion without notice.</b>
    45  *
    46  * @since 1.2
    47  * @author Atul M Dambalkar
    48  * @author Bhavesh Patel (Modified)
    49  */
    50 public class HtmlWriter {
    52     /**
    53      * The window title of this file
    54      */
    55     protected String winTitle;
    57     /**
    58      * The configuration
    59      */
    60     protected Configuration configuration;
    62     /**
    63      * The flag to indicate whether a member details list is printed or not.
    64      */
    65     protected boolean memberDetailsListPrinted;
    67     /**
    68      * Header for table displaying profiles and description..
    69      */
    70     protected final String[] profileTableHeader;
    72     /**
    73      * Header for tables displaying packages and description..
    74      */
    75     protected final String[] packageTableHeader;
    77     /**
    78      * Summary for use tables displaying class and package use.
    79      */
    80     protected final String useTableSummary;
    82     /**
    83      * Column header for class docs displaying Modifier and Type header.
    84      */
    85     protected final String modifierTypeHeader;
    87     public final Content overviewLabel;
    89     public final Content defaultPackageLabel;
    91     public final Content packageLabel;
    93     public final Content profileLabel;
    95     public final Content useLabel;
    97     public final Content prevLabel;
    99     public final Content nextLabel;
   101     public final Content prevclassLabel;
   103     public final Content nextclassLabel;
   105     public final Content summaryLabel;
   107     public final Content detailLabel;
   109     public final Content framesLabel;
   111     public final Content noframesLabel;
   113     public final Content treeLabel;
   115     public final Content classLabel;
   117     public final Content deprecatedLabel;
   119     public final Content deprecatedPhrase;
   121     public final Content allclassesLabel;
   123     public final Content allpackagesLabel;
   125     public final Content allprofilesLabel;
   127     public final Content indexLabel;
   129     public final Content helpLabel;
   131     public final Content seeLabel;
   133     public final Content descriptionLabel;
   135     public final Content prevpackageLabel;
   137     public final Content nextpackageLabel;
   139     public final Content prevprofileLabel;
   141     public final Content nextprofileLabel;
   143     public final Content packagesLabel;
   145     public final Content profilesLabel;
   147     public final Content methodDetailsLabel;
   149     public final Content annotationTypeDetailsLabel;
   151     public final Content fieldDetailsLabel;
   153     public final Content propertyDetailsLabel;
   155     public final Content constructorDetailsLabel;
   157     public final Content enumConstantsDetailsLabel;
   159     public final Content specifiedByLabel;
   161     public final Content overridesLabel;
   163     public final Content descfrmClassLabel;
   165     public final Content descfrmInterfaceLabel;
   167     private final Writer writer;
   169     private Content script;
   171     /**
   172      * Constructor.
   173      *
   174      * @param path The directory path to be created for this file
   175      *             or null if none to be created.
   176      * @exception IOException Exception raised by the FileWriter is passed on
   177      * to next level.
   178      * @exception UnsupportedEncodingException Exception raised by the
   179      * OutputStreamWriter is passed on to next level.
   180      */
   181     public HtmlWriter(Configuration configuration, DocPath path)
   182             throws IOException, UnsupportedEncodingException {
   183         writer = DocFile.createFileForOutput(configuration, path).openWriter();
   184         this.configuration = configuration;
   185         this.memberDetailsListPrinted = false;
   186         profileTableHeader = new String[] {
   187             configuration.getText("doclet.Profile"),
   188             configuration.getText("doclet.Description")
   189         };
   190         packageTableHeader = new String[] {
   191             configuration.getText("doclet.Package"),
   192             configuration.getText("doclet.Description")
   193         };
   194         useTableSummary = configuration.getText("doclet.Use_Table_Summary",
   195                 configuration.getText("doclet.packages"));
   196         modifierTypeHeader = configuration.getText("doclet.0_and_1",
   197                 configuration.getText("doclet.Modifier"),
   198                 configuration.getText("doclet.Type"));
   199         overviewLabel = getResource("doclet.Overview");
   200         defaultPackageLabel = new StringContent(DocletConstants.DEFAULT_PACKAGE_NAME);
   201         packageLabel = getResource("doclet.Package");
   202         profileLabel = getResource("doclet.Profile");
   203         useLabel = getResource("doclet.navClassUse");
   204         prevLabel = getResource("doclet.Prev");
   205         nextLabel = getResource("doclet.Next");
   206         prevclassLabel = getNonBreakResource("doclet.Prev_Class");
   207         nextclassLabel = getNonBreakResource("doclet.Next_Class");
   208         summaryLabel = getResource("doclet.Summary");
   209         detailLabel = getResource("doclet.Detail");
   210         framesLabel = getResource("doclet.Frames");
   211         noframesLabel = getNonBreakResource("doclet.No_Frames");
   212         treeLabel = getResource("doclet.Tree");
   213         classLabel = getResource("doclet.Class");
   214         deprecatedLabel = getResource("doclet.navDeprecated");
   215         deprecatedPhrase = getResource("doclet.Deprecated");
   216         allclassesLabel = getNonBreakResource("doclet.All_Classes");
   217         allpackagesLabel = getNonBreakResource("doclet.All_Packages");
   218         allprofilesLabel = getNonBreakResource("doclet.All_Profiles");
   219         indexLabel = getResource("doclet.Index");
   220         helpLabel = getResource("doclet.Help");
   221         seeLabel = getResource("doclet.See");
   222         descriptionLabel = getResource("doclet.Description");
   223         prevpackageLabel = getNonBreakResource("doclet.Prev_Package");
   224         nextpackageLabel = getNonBreakResource("doclet.Next_Package");
   225         prevprofileLabel = getNonBreakResource("doclet.Prev_Profile");
   226         nextprofileLabel = getNonBreakResource("doclet.Next_Profile");
   227         packagesLabel = getResource("doclet.Packages");
   228         profilesLabel = getResource("doclet.Profiles");
   229         methodDetailsLabel = getResource("doclet.Method_Detail");
   230         annotationTypeDetailsLabel = getResource("doclet.Annotation_Type_Member_Detail");
   231         fieldDetailsLabel = getResource("doclet.Field_Detail");
   232         propertyDetailsLabel = getResource("doclet.Property_Detail");
   233         constructorDetailsLabel = getResource("doclet.Constructor_Detail");
   234         enumConstantsDetailsLabel = getResource("doclet.Enum_Constant_Detail");
   235         specifiedByLabel = getResource("doclet.Specified_By");
   236         overridesLabel = getResource("doclet.Overrides");
   237         descfrmClassLabel = getResource("doclet.Description_From_Class");
   238         descfrmInterfaceLabel = getResource("doclet.Description_From_Interface");
   239     }
   241     public void write(Content c) throws IOException {
   242         c.write(writer, true);
   243     }
   245     public void close() throws IOException {
   246         writer.close();
   247     }
   249     /**
   250      * Get the configuration string as a content.
   251      *
   252      * @param key the key to look for in the configuration file
   253      * @return a content tree for the text
   254      */
   255     public Content getResource(String key) {
   256         return configuration.getResource(key);
   257     }
   259     /**
   260      * Get the configuration string as a content, replacing spaces
   261      * with non-breaking spaces.
   262      *
   263      * @param key the key to look for in the configuration file
   264      * @return a content tree for the text
   265      */
   266     public Content getNonBreakResource(String key) {
   267         String text = configuration.getText(key);
   268         Content c = configuration.newContent();
   269         int start = 0;
   270         int p;
   271         while ((p = text.indexOf(" ", start)) != -1) {
   272             c.addContent(text.substring(start, p));
   273             c.addContent(RawHtml.nbsp);
   274             start = p + 1;
   275         }
   276         c.addContent(text.substring(start));
   277         return c;
   278     }
   280     /**
   281      * Get the configuration string as a content.
   282      *
   283      * @param key the key to look for in the configuration file
   284      * @param o   string or content argument added to configuration text
   285      * @return a content tree for the text
   286      */
   287     public Content getResource(String key, Object o) {
   288         return configuration.getResource(key, o);
   289     }
   291     /**
   292      * Get the configuration string as a content.
   293      *
   294      * @param key the key to look for in the configuration file
   295      * @param o1  string or content argument added to configuration text
   296      * @param o2  string or content argument added to configuration text
   297      * @return a content tree for the text
   298      */
   299     public Content getResource(String key, Object o0, Object o1) {
   300         return configuration.getResource(key, o0, o1);
   301     }
   303     /**
   304      * Returns an HtmlTree for the SCRIPT tag.
   305      *
   306      * @return an HtmlTree for the SCRIPT tag
   307      */
   308     protected HtmlTree getWinTitleScript(){
   309         HtmlTree script = new HtmlTree(HtmlTag.SCRIPT);
   310         if(winTitle != null && winTitle.length() > 0) {
   311             script.addAttr(HtmlAttr.TYPE, "text/javascript");
   312             String scriptCode = "<!--" + DocletConstants.NL +
   313                     "    try {" + DocletConstants.NL +
   314                     "        if (location.href.indexOf('is-external=true') == -1) {" + DocletConstants.NL +
   315                     "            parent.document.title=\"" + escapeJavaScriptChars(winTitle) + "\";" + DocletConstants.NL +
   316                     "        }" + DocletConstants.NL +
   317                     "    }" + DocletConstants.NL +
   318                     "    catch(err) {" + DocletConstants.NL +
   319                     "    }" + DocletConstants.NL +
   320                     "//-->" + DocletConstants.NL;
   321             RawHtml scriptContent = new RawHtml(scriptCode);
   322             script.addContent(scriptContent);
   323         }
   324         return script;
   325     }
   327     /**
   328      * Returns a String with escaped special JavaScript characters.
   329      *
   330      * @param s String that needs to be escaped
   331      * @return a valid escaped JavaScript string
   332      */
   333     private static String escapeJavaScriptChars(String s) {
   334         StringBuilder sb = new StringBuilder();
   335         for (int i = 0; i < s.length(); i++) {
   336             char ch = s.charAt(i);
   337             switch (ch) {
   338                 case '\b':
   339                     sb.append("\\b");
   340                     break;
   341                 case '\t':
   342                     sb.append("\\t");
   343                     break;
   344                 case '\n':
   345                     sb.append("\\n");
   346                     break;
   347                 case '\f':
   348                     sb.append("\\f");
   349                     break;
   350                 case '\r':
   351                     sb.append("\\r");
   352                     break;
   353                 case '"':
   354                     sb.append("\\\"");
   355                     break;
   356                 case '\'':
   357                     sb.append("\\\'");
   358                     break;
   359                 case '\\':
   360                     sb.append("\\\\");
   361                     break;
   362                 default:
   363                     if (ch < 32 || ch >= 127) {
   364                         sb.append(String.format("\\u%04X", (int)ch));
   365                     } else {
   366                         sb.append(ch);
   367                     }
   368                     break;
   369             }
   370         }
   371         return sb.toString();
   372     }
   374     /**
   375      * Returns a content tree for the SCRIPT tag for the main page(index.html).
   376      *
   377      * @return a content for the SCRIPT tag
   378      */
   379     protected Content getFramesetJavaScript() {
   380         HtmlTree script = new HtmlTree(HtmlTag.SCRIPT);
   381         script.addAttr(HtmlAttr.TYPE, "text/javascript");
   382         String scriptCode = DocletConstants.NL +
   383                 "    targetPage = \"\" + window.location.search;" + DocletConstants.NL +
   384                 "    if (targetPage != \"\" && targetPage != \"undefined\")" + DocletConstants.NL +
   385                 "        targetPage = targetPage.substring(1);" + DocletConstants.NL +
   386                 "    if (targetPage.indexOf(\":\") != -1 || (targetPage != \"\" && !validURL(targetPage)))" + DocletConstants.NL +
   387                 "        targetPage = \"undefined\";" + DocletConstants.NL +
   388                 "    function validURL(url) {" + DocletConstants.NL +
   389                 "        try {" + DocletConstants.NL +
   390                 "            url = decodeURIComponent(url);" + DocletConstants.NL +
   391                 "        }" + DocletConstants.NL +
   392                 "        catch (error) {" + DocletConstants.NL +
   393                 "            return false;" + DocletConstants.NL +
   394                 "        }" + DocletConstants.NL +
   395                 "        var pos = url.indexOf(\".html\");" + DocletConstants.NL +
   396                 "        if (pos == -1 || pos != url.length - 5)" + DocletConstants.NL +
   397                 "            return false;" + DocletConstants.NL +
   398                 "        var allowNumber = false;" + DocletConstants.NL +
   399                 "        var allowSep = false;" + DocletConstants.NL +
   400                 "        var seenDot = false;" + DocletConstants.NL +
   401                 "        for (var i = 0; i < url.length - 5; i++) {" + DocletConstants.NL +
   402                 "            var ch = url.charAt(i);" + DocletConstants.NL +
   403                 "            if ('a' <= ch && ch <= 'z' ||" + DocletConstants.NL +
   404                 "                    'A' <= ch && ch <= 'Z' ||" + DocletConstants.NL +
   405                 "                    ch == '$' ||" + DocletConstants.NL +
   406                 "                    ch == '_' ||" + DocletConstants.NL +
   407                 "                    ch.charCodeAt(0) > 127) {" + DocletConstants.NL +
   408                 "                allowNumber = true;" + DocletConstants.NL +
   409                 "                allowSep = true;" + DocletConstants.NL +
   410                 "            } else if ('0' <= ch && ch <= '9'" + DocletConstants.NL +
   411                 "                    || ch == '-') {" + DocletConstants.NL +
   412                 "                if (!allowNumber)" + DocletConstants.NL +
   413                 "                     return false;" + DocletConstants.NL +
   414                 "            } else if (ch == '/' || ch == '.') {" + DocletConstants.NL +
   415                 "                if (!allowSep)" + DocletConstants.NL +
   416                 "                    return false;" + DocletConstants.NL +
   417                 "                allowNumber = false;" + DocletConstants.NL +
   418                 "                allowSep = false;" + DocletConstants.NL +
   419                 "                if (ch == '.')" + DocletConstants.NL +
   420                 "                     seenDot = true;" + DocletConstants.NL +
   421                 "                if (ch == '/' && seenDot)" + DocletConstants.NL +
   422                 "                     return false;" + DocletConstants.NL +
   423                 "            } else {" + DocletConstants.NL +
   424                 "                return false;"+ DocletConstants.NL +
   425                 "            }" + DocletConstants.NL +
   426                 "        }" + DocletConstants.NL +
   427                 "        return true;" + DocletConstants.NL +
   428                 "    }" + DocletConstants.NL +
   429                 "    function loadFrames() {" + DocletConstants.NL +
   430                 "        if (targetPage != \"\" && targetPage != \"undefined\")" + DocletConstants.NL +
   431                 "             top.classFrame.location = top.targetPage;" + DocletConstants.NL +
   432                 "    }" + DocletConstants.NL;
   433         RawHtml scriptContent = new RawHtml(scriptCode);
   434         script.addContent(scriptContent);
   435         return script;
   436     }
   438     /**
   439      * Returns an HtmlTree for the BODY tag.
   440      *
   441      * @param includeScript  set true if printing windowtitle script
   442      * @param title title for the window
   443      * @return an HtmlTree for the BODY tag
   444      */
   445     public HtmlTree getBody(boolean includeScript, String title) {
   446         HtmlTree body = new HtmlTree(HtmlTag.BODY);
   447         // Set window title string which is later printed
   448         this.winTitle = title;
   449         // Don't print windowtitle script for overview-frame, allclasses-frame
   450         // and package-frame
   451         if (includeScript) {
   452             this.script = getWinTitleScript();
   453             body.addContent(script);
   454             Content noScript = HtmlTree.NOSCRIPT(
   455                     HtmlTree.DIV(getResource("doclet.No_Script_Message")));
   456             body.addContent(noScript);
   457         }
   458         return body;
   459     }
   461     /**
   462      * Generated javascript variables for the document.
   463      *
   464      * @param typeMap map comprising of method and type relationship
   465      * @param methodTypes set comprising of all methods types for this class
   466      */
   467     public void generateMethodTypesScript(Map<String,Integer> typeMap,
   468             Set<MethodTypes> methodTypes) {
   469         String sep = "";
   470         StringBuilder vars = new StringBuilder("var methods = {");
   471         for (Map.Entry<String,Integer> entry : typeMap.entrySet()) {
   472             vars.append(sep);
   473             sep = ",";
   474             vars.append("\"")
   475                     .append(entry.getKey())
   476                     .append("\":")
   477                     .append(entry.getValue());
   478         }
   479         vars.append("};").append(DocletConstants.NL);
   480         sep = "";
   481         vars.append("var tabs = {");
   482         for (MethodTypes entry : methodTypes) {
   483             vars.append(sep);
   484             sep = ",";
   485             vars.append(entry.value())
   486                     .append(":")
   487                     .append("[")
   488                     .append("\"")
   489                     .append(entry.tabId())
   490                     .append("\"")
   491                     .append(sep)
   492                     .append("\"")
   493                     .append(configuration.getText(entry.resourceKey()))
   494                     .append("\"]");
   495         }
   496         vars.append("};")
   497                 .append(DocletConstants.NL);
   498         addStyles(HtmlStyle.altColor, vars);
   499         addStyles(HtmlStyle.rowColor, vars);
   500         addStyles(HtmlStyle.tableTab, vars);
   501         addStyles(HtmlStyle.activeTableTab, vars);
   502         script.addContent(new RawHtml(vars.toString()));
   503     }
   505     /**
   506      * Adds javascript style variables to the document.
   507      *
   508      * @param style style to be added as a javascript variable
   509      * @param vars variable string to which the style variable will be added
   510      */
   511     public void addStyles(HtmlStyle style, StringBuilder vars) {
   512         vars.append("var ").append(style).append(" = \"").append(style)
   513                 .append("\";").append(DocletConstants.NL);
   514     }
   516     /**
   517      * Returns an HtmlTree for the TITLE tag.
   518      *
   519      * @return an HtmlTree for the TITLE tag
   520      */
   521     public HtmlTree getTitle() {
   522         HtmlTree title = HtmlTree.TITLE(new StringContent(winTitle));
   523         return title;
   524     }
   526     public String codeText(String text) {
   527         return "<code>" + text + "</code>";
   528     }
   530     /**
   531      * Return "&#38;nbsp;", non-breaking space.
   532      */
   533     public Content getSpace() {
   534         return RawHtml.nbsp;
   535     }
   537     /*
   538      * Returns a header for Modifier and Type column of a table.
   539      */
   540     public String getModifierTypeHeader() {
   541         return modifierTypeHeader;
   542     }
   543 }

mercurial