1 /*
2 * Copyright (c) 2002-2026 Gargoyle Software Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 * https://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.htmlunit.html;
16
17 import static org.htmlunit.BrowserVersionFeatures.HTMLINPUT_TYPE_IMAGE_IGNORES_CUSTOM_VALIDITY;
18
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.net.URL;
24 import java.nio.file.Files;
25 import java.util.Map;
26
27 import org.apache.commons.io.IOUtils;
28 import org.htmlunit.BrowserVersion;
29 import org.htmlunit.ElementNotFoundException;
30 import org.htmlunit.Page;
31 import org.htmlunit.SgmlPage;
32 import org.htmlunit.WebClient;
33 import org.htmlunit.WebRequest;
34 import org.htmlunit.WebResponse;
35 import org.htmlunit.html.csp.ContentSecurityPolicy;
36 import org.htmlunit.javascript.host.event.Event;
37 import org.htmlunit.util.NameValuePair;
38 import org.htmlunit.util.StringUtils;
39
40 /**
41 * Wrapper for the HTML element "input".
42 * HtmlUnit does not download the associated image for performance reasons.
43 *
44 * @author Mike Bowler
45 * @author David K. Taylor
46 * @author Christian Sell
47 * @author Marc Guillemot
48 * @author Daniel Gredler
49 * @author Ahmed Ashour
50 * @author Ronald Brill
51 * @author Frank Danek
52 */
53 public class HtmlImageInput extends HtmlInput implements LabelableElement {
54
55 // For click with x, y position.
56 private boolean wasPositionSpecified_;
57 private int xPosition_;
58 private int yPosition_;
59 private WebResponse imageWebResponse_;
60 private boolean downloaded_;
61
62 /**
63 * Creates an instance.
64 *
65 * @param qualifiedName the qualified name of the element type to instantiate
66 * @param page the page that contains this element
67 * @param attributes the initial attributes
68 */
69 HtmlImageInput(final String qualifiedName, final SgmlPage page, final Map<String, DomAttr> attributes) {
70 super(qualifiedName, page, attributes);
71 }
72
73 /**
74 * {@inheritDoc}
75 */
76 @Override
77 public NameValuePair[] getSubmitNameValuePairs() {
78 final String name = getNameAttribute();
79 final String prefix;
80 // a clicked image without name sends parameter x and y
81 if (StringUtils.isEmptyOrNull(name)) {
82 prefix = "";
83 }
84 else {
85 prefix = name + ".";
86 }
87
88 if (wasPositionSpecified_) {
89 final NameValuePair valueX = new NameValuePair(prefix + 'x', Integer.toString(xPosition_));
90 final NameValuePair valueY = new NameValuePair(prefix + 'y', Integer.toString(yPosition_));
91 return new NameValuePair[] {valueX, valueY};
92 }
93 return new NameValuePair[]{new NameValuePair(getNameAttribute(), getRawValue())};
94 }
95
96 /**
97 * Submit the form that contains this input. Only a couple of the inputs
98 * support this method so it is made protected here. Those subclasses
99 * that wish to expose it will override and make it public.
100 *
101 * @return the Page that is the result of submitting this page to the server
102 * @throws IOException If an IO error occurs
103 */
104 @Override
105 @SuppressWarnings("unchecked")
106 public Page click() throws IOException {
107 return click(0, 0);
108 }
109
110 /**
111 * {@inheritDoc}
112 * @throws IOException if an IO error occurred
113 */
114 @Override
115 protected boolean doClickStateUpdate(final boolean shiftKey, final boolean ctrlKey) throws IOException {
116 final HtmlForm form = getEnclosingForm();
117 if (form != null) {
118 form.submit(this);
119 return false;
120 }
121 super.doClickStateUpdate(shiftKey, ctrlKey);
122 return false;
123 }
124
125 /**
126 * Simulate clicking this input with a pointing device. The x and y coordinates
127 * of the pointing device will be sent to the server.
128 *
129 * @param <P> the page type
130 * @param x the x coordinate of the pointing device at the time of clicking
131 * @param y the y coordinate of the pointing device at the time of clicking
132 * @return the page that is loaded after the click has taken place
133 * @throws IOException If an IO error occurs
134 * @throws ElementNotFoundException If a particular XML element could not be found in the DOM model
135 */
136 public <P extends Page> P click(final int x, final int y) throws IOException, ElementNotFoundException {
137 wasPositionSpecified_ = true;
138 xPosition_ = x;
139 yPosition_ = y;
140 return super.click();
141 }
142
143 /**
144 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
145 *
146 * Simulates clicking on this element, returning the page in the window that has the focus
147 * after the element has been clicked. Note that the returned page may or may not be the same
148 * as the original page, depending on the type of element being clicked, the presence of JavaScript
149 * action listeners, etc.
150 *
151 * @param event the click event used
152 * @param <P> the page type
153 * @return the page contained in the current window as returned by
154 * {@link org.htmlunit.WebClient#getCurrentWindow()}
155 * @throws IOException if an IO error occurs
156 */
157 @Override
158 public <P extends Page> P click(final Event event,
159 final boolean shiftKey, final boolean ctrlKey, final boolean altKey,
160 final boolean ignoreVisibility) throws IOException {
161 wasPositionSpecified_ = true;
162 return super.click(event, shiftKey, ctrlKey, altKey, ignoreVisibility);
163 }
164
165 /**
166 * {@inheritDoc}
167 */
168 @Override
169 public void setValue(final String newValue) {
170 unmarkValueDirty();
171 setDefaultValue(newValue);
172 }
173
174 /**
175 * {@inheritDoc}
176 */
177 @Override
178 public void setDefaultChecked(final boolean defaultChecked) {
179 // Empty.
180 }
181
182 /**
183 * {@inheritDoc} Also sets the value to the new default value.
184 * @see SubmittableElement#setDefaultValue(String)
185 */
186 @Override
187 public void setDefaultValue(final String defaultValue) {
188 super.setDefaultValue(defaultValue);
189 setRawValue(defaultValue);
190 }
191
192 /**
193 * {@inheritDoc}
194 */
195 @Override
196 public boolean willValidate() {
197 if (hasFeature(HTMLINPUT_TYPE_IMAGE_IGNORES_CUSTOM_VALIDITY)) {
198 return false;
199 }
200 return super.willValidate();
201 }
202
203 /**
204 * {@inheritDoc}
205 */
206 @Override
207 protected boolean isCustomValidityValid() {
208 if (hasFeature(HTMLINPUT_TYPE_IMAGE_IGNORES_CUSTOM_VALIDITY)) {
209 return true;
210 }
211
212 return super.isCustomValidityValid();
213 }
214
215 /**
216 * {@inheritDoc}
217 */
218 @Override
219 protected boolean isRequiredSupported() {
220 return false;
221 }
222
223 /**
224 * {@inheritDoc}
225 */
226 @Override
227 public void setSrcAttribute(final String src) {
228 super.setSrcAttribute(src);
229 downloaded_ = false;
230 imageWebResponse_ = null;
231 }
232
233 /**
234 * <p>Downloads the image contained by this image element.</p>
235 * <p><span style="color:red">POTENTIAL PERFORMANCE KILLER - DOWNLOADS THE IMAGE - USE AT YOUR OWN RISK</span></p>
236 * <p>If the image has not already been downloaded, this method triggers a download and caches the image.</p>
237 *
238 * @throws IOException if an error occurs while downloading the image
239 */
240 private void downloadImageIfNeeded() throws IOException {
241 if (!downloaded_) {
242 final String src = getSrc();
243 if (!StringUtils.isEmptyString(src)) {
244 final HtmlPage page = (HtmlPage) getPage();
245 final WebClient webClient = page.getWebClient();
246
247 final BrowserVersion browser = webClient.getBrowserVersion();
248 // upgrade-insecure-requests of the Content-Security-Policy
249 final URL url = ContentSecurityPolicy.upgradeInsecureRequest(page, new URL(src));
250 // like the browsers, a page not loaded from a file is not allowed to load a local file
251 if (!page.isLocalResourceAccessAllowed(url)) {
252 notifyIncorrectness("Not allowed to load local resource: " + url);
253 imageWebResponse_ = null;
254 downloaded_ = true;
255 return;
256 }
257 final WebRequest request = new WebRequest(url, browser.getImgAcceptHeader(),
258 browser.getAcceptEncodingHeader());
259 request.setCharset(page.getCharset());
260 request.setRefererHeader(page.getUrl());
261 request.setReferrerPolicy(page.getReferrerPolicy(this));
262 imageWebResponse_ = webClient.loadWebResponse(request);
263 }
264
265 downloaded_ = true;
266 }
267 }
268
269 /**
270 * Saves this image as the specified file.
271 * @param file the file to save to
272 * @throws IOException if an IO error occurs
273 */
274 public void saveAs(final File file) throws IOException {
275 downloadImageIfNeeded();
276 if (null != imageWebResponse_) {
277 try (OutputStream fos = Files.newOutputStream(file.toPath());
278 InputStream inputStream = imageWebResponse_.getContentAsStream()) {
279 IOUtils.copy(inputStream, fos);
280 }
281 }
282 }
283 }