View Javadoc
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;
16  
17  import static org.htmlunit.BrowserVersionFeatures.JS_WINDOW_COMPUTED_STYLE_PSEUDO_ACCEPT_WITHOUT_COLON;
18  import static org.htmlunit.BrowserVersionFeatures.JS_WINDOW_OUTER_INNER_HEIGHT_DIFF_138;
19  import static org.htmlunit.BrowserVersionFeatures.JS_WINDOW_OUTER_INNER_HEIGHT_DIFF_147;
20  import static org.htmlunit.BrowserVersionFeatures.JS_WINDOW_OUTER_INNER_HEIGHT_DIFF_94;
21  
22  import java.io.IOException;
23  import java.io.ObjectInputStream;
24  import java.io.ObjectOutputStream;
25  import java.util.ArrayList;
26  import java.util.List;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.htmlunit.css.ComputedCssStyleDeclaration;
31  import org.htmlunit.css.CssStyleSheet;
32  import org.htmlunit.css.ElementCssStyleDeclaration;
33  import org.htmlunit.html.DomElement;
34  import org.htmlunit.html.HtmlPage;
35  import org.htmlunit.javascript.AbstractJavaScriptEngine;
36  import org.htmlunit.javascript.HtmlUnitScriptable;
37  import org.htmlunit.javascript.background.BackgroundJavaScriptFactory;
38  import org.htmlunit.javascript.background.JavaScriptJobManager;
39  import org.htmlunit.javascript.host.Window;
40  import org.w3c.dom.Document;
41  
42  /**
43   * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
44   *
45   * Base class for common WebWindow functionality. While public, this class is not
46   * exposed in any other places of the API. Internally we can cast to this class
47   * when we need access to functionality that is not present in {@link WebWindow}
48   *
49   * @author Brad Clarke
50   * @author David K. Taylor
51   * @author Ahmed Ashour
52   * @author Ronald Brill
53   * @author Sven Strickroth
54   */
55  public abstract class WebWindowImpl implements WebWindow {
56  
57      private static final Log LOG = LogFactory.getLog(WebWindowImpl.class);
58  
59      /**
60       * The maximum time to wait for a running job of the current page
61       * before the page gets replaced.
62       */
63      private static final long MAX_WAIT_FOR_RUNNING_JOB_MILLIS = 10_000;
64  
65      private final WebClient webClient_;
66      private final Screen screen_;
67      private Page enclosedPage_;
68      private transient HtmlUnitScriptable scriptObject_;
69      private JavaScriptJobManager jobManager_;
70      private final List<WebWindowImpl> childWindows_ = new ArrayList<>();
71      private String name_ = "";
72      private final History history_ = new History(this);
73      // volatile: e.g. the window is closed by the main thread while the JavaScript thread checks this
74      private volatile boolean closed_;
75  
76      private volatile int innerHeight_;
77      private volatile int outerHeight_;
78      private volatile int innerWidth_;
79      private volatile int outerWidth_;
80  
81      /**
82       * Creates a window and associates it with the client.
83       *
84       * @param webClient the web client that "owns" this window
85       */
86      public WebWindowImpl(final WebClient webClient) {
87          WebAssert.notNull("webClient", webClient);
88          webClient_ = webClient;
89          jobManager_ = BackgroundJavaScriptFactory.theFactory().createJavaScriptJobManager(this);
90  
91          screen_ = new Screen(webClient);
92  
93          innerHeight_ = 605;
94          innerWidth_ = 1256;
95          if (webClient.getBrowserVersion().hasFeature(JS_WINDOW_OUTER_INNER_HEIGHT_DIFF_94)) {
96              outerHeight_ = innerHeight_ + 94;
97              outerWidth_ = innerWidth_ + 16;
98          }
99          else if (webClient.getBrowserVersion().hasFeature(JS_WINDOW_OUTER_INNER_HEIGHT_DIFF_138)) {
100             outerHeight_ = innerHeight_ + 138;
101             outerWidth_ = innerWidth_ + 24;
102         }
103         else if (webClient.getBrowserVersion().hasFeature(JS_WINDOW_OUTER_INNER_HEIGHT_DIFF_147)) {
104             outerHeight_ = innerHeight_ + 147;
105             outerWidth_ = innerWidth_ + 16;
106         }
107         else {
108             outerHeight_ = innerHeight_ + 115;
109             outerWidth_ = innerWidth_ + 14;
110         }
111     }
112 
113     /**
114      * Registers the window with the client.
115      */
116     protected void performRegistration() {
117         webClient_.registerWebWindow(this);
118     }
119 
120     /**
121      * {@inheritDoc}
122      */
123     @Override
124     public WebClient getWebClient() {
125         return webClient_;
126     }
127 
128     /**
129      * {@inheritDoc}
130      */
131     @Override
132     public Screen getScreen() {
133         return screen_;
134     }
135 
136     /**
137      * {@inheritDoc}
138      */
139     @Override
140     public Page getEnclosedPage() {
141         return enclosedPage_;
142     }
143 
144     /**
145      * {@inheritDoc}
146      */
147     @Override
148     public void setEnclosedPage(final Page page) {
149         if (LOG.isDebugEnabled()) {
150             LOG.debug("setEnclosedPage: " + page);
151         }
152         if (page == enclosedPage_) {
153             return;
154         }
155         waitForRunningJob();
156         destroyChildren();
157 
158         if (isJavaScriptInitializationNeeded(page)) {
159             webClient_.initialize(this, page);
160         }
161         if (webClient_.isJavaScriptEngineEnabled()) {
162             final Window window = getScriptableObject();
163             window.initialize(page);
164         }
165 
166         // has to be done after page initialization to make sure
167         // the enclosedPage has a scriptable object
168         enclosedPage_ = page;
169         history_.addPage(page);
170     }
171 
172     /**
173      * Browsers do not interrupt a running script when navigating to a new page;
174      * the new page replaces the current one after the script has finished.
175      * Therefore we wait (with a limit) for the job currently running for this window.
176      * If the job is still running afterwards, it will be stopped
177      * by the JavaScript engine as soon as the page is replaced.
178      * There is no wait if this is called from a JavaScript thread, because the running
179      * job might be the caller itself.
180      */
181     private void waitForRunningJob() {
182         final JavaScriptJobManager jobManager = getJobManager();
183         if (enclosedPage_ == null || jobManager == null) {
184             return;
185         }
186 
187         final AbstractJavaScriptEngine<?> engine = webClient_.getJavaScriptEngine();
188         if (engine == null || engine.isScriptRunning()) {
189             return;
190         }
191 
192         // no new jobs from the queue, only the running one;
193         // jobs scheduled by the running job are removed by destroyChildren()
194         jobManager.removeAllJobs();
195         jobManager.waitForJobsStartingBefore(0, MAX_WAIT_FOR_RUNNING_JOB_MILLIS);
196     }
197 
198     /**
199      * Returns {@code true} if this window needs JavaScript initialization to occur when the enclosed page is set.
200      * @param page the page that will become the enclosing page
201      * @return {@code true} if this window needs JavaScript initialization to occur when the enclosed page is set
202      */
203     protected abstract boolean isJavaScriptInitializationNeeded(Page page);
204 
205     /**
206      * {@inheritDoc}
207      */
208     @Override
209     public <T extends HtmlUnitScriptable> void setScriptableObject(final T scriptObject) {
210         scriptObject_ = scriptObject;
211     }
212 
213     /**
214      * {@inheritDoc}
215      */
216     @Override
217     @SuppressWarnings("unchecked")
218     public <T> T getScriptableObject() {
219         return (T) scriptObject_;
220     }
221 
222     /**
223      * {@inheritDoc}
224      */
225     @Override
226     public JavaScriptJobManager getJobManager() {
227         return jobManager_;
228     }
229 
230     /**
231      * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
232      *
233      * <p>Sets the JavaScript job manager for this window.</p>
234      *
235      * @param jobManager the JavaScript job manager to use
236      */
237     public void setJobManager(final JavaScriptJobManager jobManager) {
238         jobManager_ = jobManager;
239     }
240 
241     /**
242      * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
243      *
244      * <p>Adds a child to this window, for shutdown purposes.</p>
245      *
246      * @param child the child window to associate with this window
247      */
248     public void addChildWindow(final WebWindowImpl child) {
249         synchronized (childWindows_) {
250             childWindows_.add(child);
251         }
252     }
253 
254     /**
255      * Destroy our children.
256      */
257     protected void destroyChildren() {
258         LOG.debug("destroyChildren");
259         getJobManager().removeAllJobs();
260 
261         // try to deal with js thread adding a new window in between
262         while (!childWindows_.isEmpty()) {
263             final WebWindowImpl window = childWindows_.get(0);
264             removeChildWindow(window);
265         }
266     }
267 
268     /**
269      * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
270      *
271      * Destroy the child window.
272      * @param window the child to destroy
273      */
274     public void removeChildWindow(final WebWindowImpl window) {
275         if (LOG.isDebugEnabled()) {
276             LOG.debug("closing child window: " + window);
277         }
278         window.setClosed();
279         window.getJobManager().shutdown();
280         final Page page = window.getEnclosedPage();
281         if (page != null) {
282             page.cleanUp();
283         }
284         window.destroyChildren();
285 
286         synchronized (childWindows_) {
287             childWindows_.remove(window);
288         }
289         webClient_.deregisterWebWindow(window);
290     }
291 
292     /**
293      * {@inheritDoc}
294      */
295     @Override
296     public String getName() {
297         return name_;
298     }
299 
300     /**
301      * {@inheritDoc}
302      */
303     @Override
304     public void setName(final String name) {
305         name_ = name;
306     }
307 
308     /**
309      * Returns this window's navigation history.
310      * @return this window's navigation history
311      */
312     @Override
313     public History getHistory() {
314         return history_;
315     }
316 
317     /**
318      * {@inheritDoc}
319      */
320     @Override
321     public boolean isClosed() {
322         return closed_;
323     }
324 
325     /**
326      * Sets this window as closed.
327      */
328     protected void setClosed() {
329         closed_ = true;
330     }
331 
332     /**
333      * {@inheritDoc}
334      */
335     @Override
336     public int getInnerWidth() {
337         return innerWidth_;
338     }
339 
340     /**
341      * {@inheritDoc}
342      */
343     @Override
344     public void setInnerWidth(final int innerWidth) {
345         innerWidth_ = innerWidth;
346     }
347 
348     /**
349      * {@inheritDoc}
350      */
351     @Override
352     public int getOuterWidth() {
353         return outerWidth_;
354     }
355 
356     /**
357      * {@inheritDoc}
358      */
359     @Override
360     public void setOuterWidth(final int outerWidth) {
361         outerWidth_ = outerWidth;
362     }
363 
364     /**
365      * {@inheritDoc}
366      */
367     @Override
368     public int getInnerHeight() {
369         return innerHeight_;
370     }
371 
372     /**
373      * {@inheritDoc}
374      */
375     @Override
376     public void setInnerHeight(final int innerHeight) {
377         innerHeight_ = innerHeight;
378     }
379 
380     /**
381      * {@inheritDoc}
382      */
383     @Override
384     public int getOuterHeight() {
385         return outerHeight_;
386     }
387 
388     /**
389      * {@inheritDoc}
390      */
391     @Override
392     public void setOuterHeight(final int outerHeight) {
393         outerHeight_ = outerHeight;
394     }
395 
396     private void writeObject(final ObjectOutputStream oos) throws IOException {
397         oos.defaultWriteObject();
398         oos.writeObject(scriptObject_);
399     }
400 
401     private void readObject(final ObjectInputStream ois) throws ClassNotFoundException, IOException {
402         ois.defaultReadObject();
403         scriptObject_ = (HtmlUnitScriptable) ois.readObject();
404     }
405 
406     /**
407      * {@inheritDoc}
408      */
409     @Override
410     public ComputedCssStyleDeclaration getComputedStyle(final DomElement element, final String pseudoElement) {
411         String normalizedPseudo = pseudoElement;
412         if (normalizedPseudo != null) {
413             if (normalizedPseudo.startsWith("::")) {
414                 normalizedPseudo = normalizedPseudo.substring(1);
415             }
416             else if (getWebClient().getBrowserVersion().hasFeature(JS_WINDOW_COMPUTED_STYLE_PSEUDO_ACCEPT_WITHOUT_COLON)
417                     && normalizedPseudo.length() > 0 && normalizedPseudo.charAt(0) != ':') {
418                 normalizedPseudo = ":" + normalizedPseudo;
419             }
420         }
421 
422         final SgmlPage sgmlPage = element.getPage();
423         if (sgmlPage instanceof HtmlPage page) {
424             final ComputedCssStyleDeclaration styleFromCache =
425                     page.getStyleFromCache(element, normalizedPseudo);
426             if (styleFromCache != null) {
427                 return styleFromCache;
428             }
429         }
430 
431         final ComputedCssStyleDeclaration computedsStyleDeclaration =
432                 new ComputedCssStyleDeclaration(new ElementCssStyleDeclaration(element));
433 
434         final Document ownerDocument = element.getOwnerDocument();
435         if (ownerDocument instanceof HtmlPage htmlPage) {
436 
437             final WebClient webClient = getWebClient();
438 
439             if (webClient.getOptions().isCssEnabled()) {
440                 final boolean trace = LOG.isTraceEnabled();
441                 for (final CssStyleSheet cssStyleSheet : htmlPage.getStyleSheets()) {
442                     if (cssStyleSheet != null
443                             && cssStyleSheet.isEnabled()
444                             && cssStyleSheet.isActive()) {
445                         if (trace) {
446                             LOG.trace("modifyIfNecessary: " + cssStyleSheet
447                                         + ", " + computedsStyleDeclaration + ", " + element);
448                         }
449                         cssStyleSheet.modifyIfNecessary(computedsStyleDeclaration,
450                                         element, normalizedPseudo, htmlPage.getDocumentElement());
451                     }
452                 }
453             }
454 
455             ((HtmlPage) element.getPage()).putStyleIntoCache(element, normalizedPseudo, computedsStyleDeclaration);
456         }
457 
458         return computedsStyleDeclaration;
459     }
460 }