cz.vutbr.web.css.MediaSpec Java Examples

The following examples show how to use cz.vutbr.web.css.MediaSpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DOMAnalyzer.java    From CSSBox with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new DOM analyzer.
 * @param doc the document to be analyzed
 * @param baseUrl the base URL for loading the style sheets. If <code>detectBase</code>, this URL may be redefined by the <code>&lt;base&gt;</code> tag used in the
 * document header.
 * @param detectBase sets whether to try to accept the <code>&lt;base&gt;</code> tags in the document header.
 */
public DOMAnalyzer(org.w3c.dom.Document doc, URL baseUrl, boolean detectBase) 
{
    this.doc = doc;
    this.encoding = null;
    this.media = new MediaSpec(DEFAULT_MEDIA);
    styles = new Vector<StyleSheet>();
    this.baseUrl = baseUrl;
    if (detectBase)
    {
        String docbase = getDocumentBase();
        if (docbase != null)
        {
            try {
                this.baseUrl = new URL(baseUrl, docbase);
                log.info("Using specified document base " + this.baseUrl);
            } catch (MalformedURLException e) {
                log.warn("Malformed base URL " + docbase);
            }
        }
    }
    stylemap = null;
    istylemap = null;
}
 
Example #2
Source File: BoxBrowser.java    From CSSBox with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Updates the given media specification according to the real screen parametres (if they may be obtained).
 * @param media The media specification to be updated.
 */
protected void updateCurrentMedia(MediaSpec media)
{
       Dimension size = getContentScroll().getViewport().getSize();
       Dimension deviceSize = Toolkit.getDefaultToolkit().getScreenSize();
       ColorModel colors = Toolkit.getDefaultToolkit().getColorModel();
       
       media.setDimensions(size.width, size.height);
       media.setDeviceDimensions(deviceSize.width, deviceSize.height);
       media.setColor(colors.getComponentSize()[0]);
       if (colors instanceof IndexColorModel)
       {
           media.setColorIndex(((IndexColorModel) colors).getMapSize());
       }
       media.setResolution(Toolkit.getDefaultToolkit().getScreenResolution());
}
 
Example #3
Source File: DOMAnalyzer.java    From CSSBox with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** 
 * Returns a vector of CSSStyleSheet objects referenced from the document for the specified
 * media type and features. The internal style sheets are read from the document directly, the external
 * ones are downloaded and parsed automatically.
 * @param media the media specification
 */
public void getStyleSheets(MediaSpec media)
{
    this.media = media;
    StyleSheet newsheet = CSSFactory.getUsedStyles(doc, encoding, baseUrl, this.media);
    styles.add(newsheet);
}
 
Example #4
Source File: AnalyzerUtil.java    From jStyleParser with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Classifies the rules in all the style sheets.
 * @param mediaspec The specification of the media for evaluating the media queries.
 */
static void classifyAllSheets(final List<StyleSheet> sheets, final Holder rules, final MediaSpec mediaspec)
{
	final Counter orderCounter = new Counter();
    for (final StyleSheet sheet : sheets)
        classifyRules(sheet, mediaspec, rules, orderCounter);
}
 
Example #5
Source File: DOMAssignMediaTest.java    From jStyleParser with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void queryBasic() throws SAXException, IOException {  

    NodeData data;
    data = evaluateForMedia(new MediaSpec("screen"));
    assertNotNull("Data for #test exist", data);
    assertThat(data.getValue(TermColor.class, "color"), is(tf.createColor(0, 0, 255)));
    
}
 
Example #6
Source File: DOMAssignMediaTest.java    From jStyleParser with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void queryAlternatives() throws SAXException, IOException {  

    NodeData data;
    data = evaluateForMedia(new MediaSpec("projection"));
    assertNotNull("Data for #test exist", data);
    assertThat(data.getValue(TermColor.class, "color"), is(tf.createColor(0, 0, 255)));
    
}
 
Example #7
Source File: DOMAssignMediaTest.java    From jStyleParser with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void queryInvalidAndAlternative() throws SAXException, IOException {  

    NodeData data;
    data = evaluateForMedia(new MediaSpec("print"));
    assertNotNull("Data for #test exist", data);
    assertThat(data.getValue(TermColor.class, "color"), is(tf.createColor(0, 128, 0)));
    
}
 
Example #8
Source File: ReferenceTestCase.java    From CSSBox with GNU Lesser General Public License v3.0 5 votes vote down vote up
private BufferedImage renderDocument(Document doc)
{
    //create the media specification
    MediaSpec media = new MediaSpec(mediaType);
    media.setDimensions(windowSize.width, windowSize.height);
    media.setDeviceDimensions(windowSize.width, windowSize.height);

    //Create the CSS analyzer
    DOMAnalyzer da = new DOMAnalyzer(doc, docSource.getURL());
    da.setMediaSpec(media);
    da.attributesToStyles(); //convert the HTML presentation attributes to inline styles
    da.addStyleSheet(null, CSSNorm.stdStyleSheet(), DOMAnalyzer.Origin.AGENT); //use the standard style sheet
    da.addStyleSheet(null, CSSNorm.userStyleSheet(), DOMAnalyzer.Origin.AGENT); //use the additional style sheet
    da.addStyleSheet(null, CSSNorm.formsStyleSheet(), DOMAnalyzer.Origin.AGENT); //render form fields using css
    da.getStyleSheets(); //load the author style sheets
    
    GraphicsEngine engine = new GraphicsEngine(da.getRoot(), da, docSource.getURL()) {
        @Override
        protected void setupGraphics(Graphics2D g)
        {
            // disable antialiasing for testing in order to compare the resulting images more precisely
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
            g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        }
    };
    engine.setUseKerning(false);
    engine.setAutoMediaUpdate(false); //we have a correct media specification, do not update
    engine.getConfig().setClipViewport(cropWindow);
    engine.getConfig().setLoadImages(loadImages);
    engine.getConfig().setLoadBackgroundImages(loadBackgroundImages);

    engine.createLayout(windowSize);
    return engine.getImage();
}
 
Example #9
Source File: DOMAssignMediaTest.java    From jStyleParser with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void queryNoMatch() throws SAXException, IOException {  

    NodeData data;
    data = evaluateForMedia(new MediaSpec("speech"));
    assertNotNull("Data for #test exist", data);
    assertThat(data.getValue(TermColor.class, "color"), is(tf.createColor(255, 0, 0)));
    
}
 
Example #10
Source File: DOMAnalyzer.java    From CSSBox with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** 
 * Returns a vector of CSSStyleSheet objects referenced from the document for the specified
 * media type with default values of the remaining media features. The internal style sheets
 * are read from the document directly, the external ones are downloaded and parsed automatically.
 * @param media the media type string
 */
public void getStyleSheets(String media)
{
	this.media = new MediaSpec(media);
    StyleSheet newsheet = CSSFactory.getUsedStyles(doc, encoding, baseUrl, this.media);
    styles.add(newsheet);
}
 
Example #11
Source File: DOMAssignMediaTest.java    From jStyleParser with GNU Lesser General Public License v3.0 5 votes vote down vote up
private NodeData evaluateForMedia(MediaSpec spec) throws SAXException, IOException
{
    DOMSource ds = new DOMSource(getClass().getResourceAsStream("/media/media1.html"));
    Document doc = ds.parse();
    ElementMap elements = new ElementMap(doc);
    
    StyleMap decl = CSSFactory.assignDOM(doc, null, getClass().getResource("/media/media1.html"), spec, true);
    NodeData data = decl.get(elements.getElementById("test"));
    
    return data;
}
 
Example #12
Source File: Analyzer.java    From jStyleParser with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates map of declarations assigned to each element of a DOM tree
 * 
 * @param doc
 *            DOM document
 * @param media
 *            Media type to be used for declarations
 * @param inherit
 *            Inheritance (cascade propagation of values)
 * @return Map of elements as keys and their declarations
 */
protected DeclarationMap assingDeclarationsToDOM(Document doc, MediaSpec media, final boolean inherit) {

	// classify the rules
    classifyAllSheets(media);
	
	// resulting map
	DeclarationMap declarations = new DeclarationMap();
	
       // if the holder is empty skip evaluation
       if(rules!=null && !rules.isEmpty()) {
           
   		Traversal<DeclarationMap> traversal = new Traversal<DeclarationMap>(
   				doc, (Object) rules, NodeFilter.SHOW_ELEMENT) {
   			protected void processNode(DeclarationMap result,
   					Node current, Object source) {
   				assignDeclarationsToElement(result, walker, (Element) current,
   						(Holder) source);
   			}
   		};
   
   		// list traversal will be enough
   		if (!inherit)
   			traversal.listTraversal(declarations);
   		// we will do level traversal to economize blind returning
   		// in tree
   		else
   			traversal.levelTraversal(declarations);
       }

	return declarations;
}
 
Example #13
Source File: Analyzer.java    From jStyleParser with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Classifies the rules in all the style sheets.
 * @param mediaspec The specification of the media for evaluating the media queries.
 */
protected void classifyAllSheets(MediaSpec mediaspec)
{
    rules = new Holder();

    AnalyzerUtil.classifyAllSheets(sheets, rules, mediaspec);
}
 
Example #14
Source File: DOMAnalyzer.java    From CSSBox with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new DOM analyzer.
 * @param doc the document to be analyzed
 */
public DOMAnalyzer(org.w3c.dom.Document doc) 
{
    this.doc = doc;
    this.media = new MediaSpec(DEFAULT_MEDIA);
    baseUrl = null;
    encoding = null;
    styles = new Vector<StyleSheet>();
    stylemap = null;
    istylemap = null;
}
 
Example #15
Source File: ImportTest1.java    From jStyleParser with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testMediaImportLimit2() throws CSSException, IOException {
    CSSFactory.setAutoImportMedia(new MediaSpec("screen"));
    StyleSheet ss = CSSFactory.parse(getClass().getResource("/simple/impmedia.css"), null);
    assertEquals("No rules have been imported", 0, ss.size());
}
 
Example #16
Source File: Analyzer.java    From jStyleParser with GNU Lesser General Public License v3.0 4 votes vote down vote up
public StyleMap evaluateDOM(Document doc, String media, final boolean inherit) {
    return evaluateDOM(doc, new MediaSpec(media), inherit);
}
 
Example #17
Source File: ImportTest1.java    From jStyleParser with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testMediaImportLimit1() throws CSSException, IOException {
    CSSFactory.setAutoImportMedia(new MediaSpec("projection"));
    StyleSheet ss = CSSFactory.parse(getClass().getResource("/simple/impmedia.css"), null);
    assertEquals("All rules have been imported", 8, ss.size());
}
 
Example #18
Source File: AnalyzerUtil.java    From jStyleParser with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static Holder getClassifiedRules(final List<StyleSheet> sheets, final MediaSpec mediaspec) {
 final Holder rules = new Holder();
 AnalyzerUtil.classifyAllSheets(sheets, rules, mediaspec);
 return rules;
}
 
Example #19
Source File: DOMAnalyzer.java    From CSSBox with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Returns the full specification of the currently used medium.
 * @return the media specification according to CSS
 */
public MediaSpec getMediaSpec()
{
    return media;
}
 
Example #20
Source File: DOMAnalyzer.java    From CSSBox with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Set the type of the medium used for computing the style. Default is "screen".
 * @param media the medium to set
 */
public void setMedia(String media)
{
	this.media = new MediaSpec(media);
}
 
Example #21
Source File: HtmlUtils.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
public DeclarationMap getDeclarationMap(Document document, String media) {
    // To keep media queries working (if any) don't assign inherited styles.
    final boolean useInheritance = StringUtils.isEmpty(media);

    return assingDeclarationsToDOM(document, new MediaSpec(media), useInheritance);
}
 
Example #22
Source File: PreviewImageServiceImpl.java    From openemm with GNU Affero General Public License v3.0 3 votes vote down vote up
private BufferedImage renderDocumentWithCssBox(String url) throws IOException, SAXException {
	DocumentSource docSource = new DefaultDocumentSource(ensureUrlHasProtocol(url));
    
    final Dimension windowSize = new Dimension(VIEWPORT_WIDTH, VIEWPORT_HEIGHT);
    final String mediaType = "screen";

    // Parse the input document
    DOMSource parser = new DefaultDOMSource(docSource);
    Document doc = parser.parse();

    // Create the media specification
    MediaSpec media = new MediaSpec(mediaType);
    media.setDimensions(windowSize.width, windowSize.height);
    media.setDeviceDimensions(windowSize.width, windowSize.height);

    // Create the CSS analyzer
    DOMAnalyzer analyzer = new DOMAnalyzer(doc, docSource.getURL());

    analyzer.setMediaSpec(media);

    // Convert the HTML presentation attributes to inline styles
    analyzer.attributesToStyles();

    // Use the standard style sheet
    analyzer.addStyleSheet(null, CSSNorm.stdStyleSheet(), DOMAnalyzer.Origin.AGENT);

    // Use the additional style sheet
    analyzer.addStyleSheet(null, CSSNorm.userStyleSheet(), DOMAnalyzer.Origin.AGENT);

    // Render form fields using css
    analyzer.addStyleSheet(null, CSSNorm.formsStyleSheet(), DOMAnalyzer.Origin.AGENT);

    // Load the author style sheets
    analyzer.getStyleSheets();

    BrowserCanvas contentCanvas = new BrowserCanvas(analyzer.getRoot(), analyzer, docSource.getURL());
    // We have a correct media specification, do not update
    contentCanvas.setAutoMediaUpdate(false);
    contentCanvas.getConfig().setClipViewport(false);
    contentCanvas.getConfig().setLoadImages(true);
    contentCanvas.getConfig().setLoadBackgroundImages(true);
    contentCanvas.getConfig().setImageLoadTimeout((int) TimeUnit.SECONDS.toMillis(IMAGE_LOADING_TIMEOUT));

    contentCanvas.createLayout(windowSize);

    return contentCanvas.getImage();
}
 
Example #23
Source File: ImageRenderer.java    From CSSBox with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * Renders the URL and prints the result to the specified output stream in the specified
 * format.
 * @param urlstring the source URL
 * @param out output stream
 * @return true in case of success, false otherwise
 * @throws SAXException 
 */
public boolean renderURL(String urlstring, OutputStream out) throws IOException, SAXException
{
    if (!urlstring.startsWith("http:") &&
        !urlstring.startsWith("https:") &&
        !urlstring.startsWith("ftp:") &&
        !urlstring.startsWith("file:"))
            urlstring = "http://" + urlstring;
    
    //Open the network connection 
    DocumentSource docSource = new DefaultDocumentSource(urlstring);
    
    //Parse the input document
    DOMSource parser = new DefaultDOMSource(docSource);
    Document doc = parser.parse();
    
    //create the media specification
    MediaSpec media = new MediaSpec(mediaType);
    media.setDimensions(windowSize.width, windowSize.height);
    media.setDeviceDimensions(windowSize.width, windowSize.height);

    //Create the CSS analyzer
    DOMAnalyzer da = new DOMAnalyzer(doc, docSource.getURL());
    da.setMediaSpec(media);
    da.attributesToStyles(); //convert the HTML presentation attributes to inline styles
    da.addStyleSheet(null, CSSNorm.stdStyleSheet(), DOMAnalyzer.Origin.AGENT); //use the standard style sheet
    da.addStyleSheet(null, CSSNorm.userStyleSheet(), DOMAnalyzer.Origin.AGENT); //use the additional style sheet
    da.addStyleSheet(null, CSSNorm.formsStyleSheet(), DOMAnalyzer.Origin.AGENT); //render form fields using css
    da.getStyleSheets(); //load the author style sheets
    
    GraphicsEngine contentCanvas = new GraphicsEngine(da.getRoot(), da, docSource.getURL());
    contentCanvas.setAutoMediaUpdate(false); //we have a correct media specification, do not update
    contentCanvas.getConfig().setClipViewport(cropWindow);
    contentCanvas.getConfig().setLoadImages(loadImages);
    contentCanvas.getConfig().setLoadBackgroundImages(loadBackgroundImages);

    contentCanvas.createLayout(windowSize);
    ImageIO.write(contentCanvas.getImage(), "png", out);
    
    docSource.close();

    return true;
}
 
Example #24
Source File: AnalyzerUtil.java    From jStyleParser with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Returns all applicable rules for an element
 * 
 * @param sheets
 * @param element
 * @param mediaspec
 * @return
 */
public static OrderedRule[] getApplicableRules(final List<StyleSheet> sheets, final Element element, final MediaSpec mediaspec) {
 final Holder rules = getClassifiedRules(sheets, mediaspec);
 return getApplicableRules(element, rules, null);
}
 
Example #25
Source File: DirectAnalyzer.java    From jStyleParser with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Computes the style of an element with an eventual pseudo element for the given media.
 * @param el The DOM element.
 * @param pseudo A pseudo element that should be used for style computation or <code>null</code> if no pseudo element should be used (e.g. :after).
 * @param media Used media name (e.g. "screen" or "all")
 * @return The relevant declarations from the registered style sheets.
 */
public NodeData getElementStyle(Element el, PseudoElementType pseudo, String media)
{
    return getElementStyle(el, pseudo, new MediaSpec(media));
}
 
Example #26
Source File: DirectAnalyzer.java    From jStyleParser with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Computes the style of an element with an eventual pseudo element for the given media.
 * @param el The DOM element.
 * @param pseudo A pseudo element that should be used for style computation or <code>null</code> if no pseudo element should be used (e.g. :after).
 * @param media Used media specification.
 * @return The relevant declarations from the registered style sheets.
 */
public NodeData getElementStyle(Element el, PseudoElementType pseudo, MediaSpec media)
{
    final OrderedRule[] applicableRules = AnalyzerUtil.getApplicableRules(sheets, el, media);
    return AnalyzerUtil.getElementStyle(el, pseudo, getElementMatcher(), getMatchCondition(), applicableRules);
}
 
Example #27
Source File: DOMAnalyzer.java    From CSSBox with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Set the specification of the medium used for computing the style. The default is "screen" with
 * some standard features that correspond to a normal desktop station.
 * @param media the medium to set
 */
public void setMediaSpec(MediaSpec media)
{
    this.media = media;
}