📄 xcustomrenderer.java
字号:
String search_data = getRenderedText();
if( !case_sensitive )
{
search_data = search_data.toLowerCase();
find_phrase = find_phrase.toLowerCase();
}
if( whole_word )
{
for( int k=0; k<WORD_SEPARATORS.length; k++ )
{
if( find_phrase.indexOf(WORD_SEPARATORS[k])>=0 )
throw new Exception(XRendererSupport.getContext().getResourceManager().getProperty(this, "IllegalCharacter", ""+WORD_SEPARATORS[k]));
}
}
int start = -1;
int finish = -1;
while( true )
{
if( search_up )
start = search_data.lastIndexOf(find_phrase, pos-1);
else
start = search_data.indexOf(find_phrase, pos);
if( start<0 )
throw new Exception( XRendererSupport.getContext().getResourceManager().getProperty(this, "FinishedSearching") );
finish = start+find_phrase.length();
if( whole_word )
{
boolean s1 = start>0;
boolean b1 = s1 && !isSeparator(search_data.charAt(start-1));
boolean s2 = finish<search_data.length();
boolean b2 = s2 && !isSeparator(search_data.charAt(finish));
if( b1 || b2 ) // Not a whole word
{
if( search_up && s1 ) // Can continue up
{
pos = start;
continue;
}
if( !search_up && s2 ) // Can continue down
{
pos = finish;
continue;
}
// Found, but not a whole word, and we cannot continue
throw new Exception( XRendererSupport.getContext().getResourceManager().getProperty(this, "FinishedSearching") );
}
}
break;
}
setSelection(start, finish, search_up);
}
public void startPrinting(boolean print_immediately)
{
prnJob = PrinterJob.getPrinterJob();
prnJob.setPrintable(this);
if( !print_immediately && !prnJob.printDialog() )
return;
try
{
rendererListeners.pagePrintingStarted();
prnJob.print();
rendererListeners.pagePrintingFinished(null);
}
catch( PrinterException e )
{
rendererListeners.pagePrintingFinished(e);
}
prnJob = null;
}
public void stopPrinting()
{
if( prnJob!=null )
{
prnJob.cancel();
prnJob = null;
}
loadingPreviews = false;
rendererListeners.renderingFinished();
}
public void changePreviewScale(XPreviewContainer preview, int new_scale)
{
int w = (int)(pageWidth*new_scale/100);
int h = (int)(pageHeight*new_scale/100);
Component[] comps = preview.getComponents();
for( int i=0; i<comps.length; i++ )
{
if( !(comps[i] instanceof XPagePreview) )
continue;
((XPagePreview)comps[i]).setScaledSize(w, h);
Thread.yield();
}
preview.doLayout();
preview.getParent().getParent().validate();
}
public void loadPreviews(final XPreviewContainer preview, int scale) throws Exception
{
PrinterJob prn_job = PrinterJob.getPrinterJob();
PageFormat page_format = prn_job.defaultPage();
if( page_format.getHeight()==0 || page_format.getWidth()==0 )
throw new Exception(XRendererSupport.getContext().getResourceManager().getProperty(this, "PageSizeError"));
pageWidth = (int)(page_format.getWidth());
pageHeight = (int)(page_format.getHeight());
final int w = (int)(pageWidth*scale/100);
final int h = (int)(pageHeight*scale/100);
int page_index = 0;
loadingPreviews = true;
Thread.sleep(1000);
try
{
while( loadingPreviews )
{
final BufferedImage img = new BufferedImage(pageWidth, pageHeight, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, pageWidth, pageHeight);
if( print(g, page_format, page_index)!=Printable.PAGE_EXISTS )
break;
System.gc();
SwingUtilities.invokeAndWait( new Runnable() {
public void run()
{
preview.add(new XPagePreview(w, h, img));
preview.doLayout();
preview.getParent().getParent().validate();
}
});
page_index++;
Thread.yield();
}
}
catch (PrinterException e)
{
throw new Exception(XRendererSupport.getContext().getResourceManager().getProperty(this, "PreviewError"));
}
finally
{
loadingPreviews = false;
}
}
private void addToPageHistory(String url)
{
pageHistory.add(url);
if( pageHistory.size()>MAX_HISTORY_LENGTH )
pageHistory.remove(0);
rendererListeners.pageAddedToHistory(url);
}
void showDocument(URL url, String target)
{
if( target.equalsIgnoreCase("_parent") || target.equalsIgnoreCase("_top") || target.equalsIgnoreCase("_blank") )
XRendererSupport.getContext().getBrowser().showInNewDocument(url.toString());
else
processXHyperLink(url.toString(), true);
}
void showAppletStatusInternal(String status)
{
rendererListeners.showAppletStatus(status);
}
void showAppletLifeCycle(Applet applet, int status)
{
rendererListeners.showAppletLifeCycle(applet, status);
}
public int print(Graphics pg, PageFormat page_format, int page_index) throws PrinterException
{
rendererListeners.renderingPage(page_index);
pg.translate((int)page_format.getImageableX(),(int)page_format.getImageableY());
int page_width = (int)page_format.getImageableWidth();
int page_height = (int)page_format.getImageableHeight();
pg.setClip(0, 0, page_width, page_height);
// Only do this once per print
if( printView == null )
{
View root = getUI().getRootView(this);
if( getContentType().equals("text/html") )
printView = new XPrintView(getDocument().getDefaultRootElement().getElement(1), root, page_width, page_height);
else
printView = new XPrintView(getDocument().getDefaultRootElement(), root, page_width, page_height);
}
System.gc();
if( printView.paintPage(pg, page_height, page_index) )
return PAGE_EXISTS;
else
{
rendererListeners.renderingFinished();
printView = null;
return NO_SUCH_PAGE;
}
}
// Needed by JavaScript
public void showStatus(String status)
{
rendererListeners.showStatus(status);
}
public XPageProperties getPageProperties()
{
return properties;
}
protected InputStream getStream(URL page) throws IOException
{
getDocument().putProperty(Document.StreamDescriptionProperty, page);
URLConnection conn = page.openConnection();
boolean was_cached = false;
File cache_file = null;
if( page.getProtocol().equalsIgnoreCase( "http"))
{
conn.setRequestProperty("User-Agent", XRendererSupport.getContext().getUserAgent());
conn.setRequestProperty("Accept-Language", XRendererSupport.getContext().getAcceptLanguages());
was_cached = XRendererSupport.getContext().getCacheManager().isCached(page.toString());
cache_file = XRendererSupport.getContext().getCacheManager().getFileToCache(page.toString());
if( was_cached)
XRendererSupport.setIfModified(conn, cache_file.lastModified());
XRendererSupport.setCookies(page, conn);
}
String type = conn.getContentType();
if( type!=null )
setContentType(type);
InputStream is = conn.getInputStream();
boolean need_cache = true;
saved = null;
properties = null;
if( conn instanceof HttpURLConnection) {
HttpURLConnection c = (HttpURLConnection) conn;
int response = c.getResponseCode();
if( response != HttpURLConnection.HTTP_OK)
XRendererSupport.getContext().getLogger().message(this, "Resp: " + response + "/" + c.getResponseMessage());
if( was_cached) {
int contentLength = conn.getContentLength();
boolean badCacheLen = ( contentLength > 0 && cache_file.length() != contentLength);
if( badCacheLen) {
XRendererSupport.getContext().getLogger().message(this, "Cache file is corrupted!");
XRendererSupport.getContext().getCacheManager().removeFromCache( page.toString());
return getStream( page); // Give recursive try.
}
if( response == HttpURLConnection.HTTP_NOT_MODIFIED) {
is.close();
need_cache = false;
is = new FileInputStream(cache_file);
String contType = XRendererSupport.getContext().getCacheManager().getContentType(page.toString());
setContentType( contType);
properties = new XPageProperties(page.toString(), contType, cache_file.length(), cache_file.lastModified());
saved = new XRendererSupport.XInputSave(cache_file);
XRendererSupport.getContext().getLogger().message(this, "Cache used from " + cache_file.getAbsolutePath());
} // otherwise, update file
}
if( need_cache) {
boolean cache_ok = XRendererSupport.isCacheable( c, response);
if( cache_ok) {
XRendererSupport.getContext().getLogger().message(this, "Caching " + page + " to " + cache_file.getAbsoluteFile());
XRendererSupport.getContext().getCacheManager().setContentType(page.toString(), type);
XTeeInputStream cip = new XTeeInputStream(is);
cip.setFileOutputStream( new FileOutputStream(cache_file) );
// Needed for fast saving.
saved = new XRendererSupport.XInputSave(cache_file);
is = cip;
} else
XRendererSupport.getContext().getLogger().message(this, "Nocache " + page);
}
}
if( properties == null)
properties = new XPageProperties(conn, page);
properties.setCachingInfo(cache_file, was_cached && !need_cache);
encoding = conn.getContentEncoding();
if( saved == null) { // Need to keep in memory!
saved = new XRendererSupport.XInputSave();
is = saved.getSavingStream(is);
}
myStream = new XInputStream(is);
// When redirected, this will be redirected URL.
URL base = conn.getURL();
Document doc = getDocument();
XRendererSupport.getCookies(base, conn);
if( doc instanceof HTMLDocument )
((HTMLDocument)doc).setBase(base);
doc.putProperty(Document.StreamDescriptionProperty, base);
return myStream;
}
private class XInputStream extends FilterInputStream
{
public XInputStream(InputStream in)
{
super(in);
try
{
entireSize = available();
}
catch( Exception e )
{
}
pageSource = new StringBuffer();
}
public void unread( byte b[])
{
if( unread_buf==null )
unread_buf = b;
else
{
int new_length = unread_buf.length + b.length;
byte[] new_buf = new byte[ new_length];
System.arraycopy( unread_buf, 0, new_buf, 0, unread_buf.length);
System.arraycopy( b, 0, new_buf, unread_buf.length, b.length);
unread_buf = new_buf;
}
}
public int read() throws IOException
{
int result = super.read();
if( result!=-1 )
{
byte[] bytes = {(byte)result};
pageSource.append( new String(bytes) );
}
return result;
}
public int read(byte[] b) throws IOException
{
int result = super.read(b);
if( result!=-1 )
pageSource.append( new String(b) );
return result;
}
public int read(byte b[], int off, int len) throws IOException
{
if( unread_buf != null)
{
XRendererSupport.getContext().getLogger().message(this, "unread_buf != null !");
int unread_length = unread_buf.length;
if( len >= unread_length) {
System.arraycopy( unread_buf, 0, b, off, unread_length);
unread_buf = null;
return unread_length;
}
System.arraycopy( unread_buf, 0, b, off, len);
int new_length = unread_length-len;
byte[] new_buf = new byte[ new_length];
System.arraycopy( unread_buf, 0, new_buf, 0, new_length);
unread_buf = new_buf;
return len;
}
int result = super.read(b, off, len);
if( result!=-1 )
{
readSize += result;
pageSource.append( new String(b, off, len) );
rendererListeners.pageLoadingProgress(readSize, entireSize);
}
return result;
}
public void close() throws IOException
{
rendererListeners.pageLoadingFinished(null);
}
// Attributes:
private long entireSize = 0;
private long readSize = 0;
private byte[] unread_buf = null;
}
static
{
javax.swing.JEditorPane.registerEditorKitForContentType("text/html", "xbrowser.renderer.custom.XHTMLEditorKit", XCustomRenderer.class.getClassLoader());
}
// Attributes:
private static final char[] WORD_SEPARATORS = {' ', '\t', '\n',
'\r', '\f', '.', ',', ':', '-', '(', ')', '[', ']', '{',
'}', '<', '>', '/', '|', '\\', '\'', '\"'};
private XPageProperties properties = null;
private String encoding = "";
private StringBuffer pageSource = new StringBuffer();
private InputStream myStream = null;
private XRendererListenerSupport rendererListeners = new XRendererListenerSupport();
private String currentFocusedLink = null;
private String currentURL = null;
private XPrintView printView = null;
private PrinterJob prnJob = null;
private boolean loadingPreviews = false;
private int pageWidth;
private int pageHeight;
private static final int MAX_HISTORY_LENGTH = 40;
private int currentPageIndex = -1;
private LinkedList pageHistory = new LinkedList();
private LinkedList urlList = new LinkedList();
private Thread loaderThread = null;
private XRendererSupport.XInputSave saved = null;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -