📄 htmldisplay.py
字号:
import refrom objc import YES, NO, nilfrom AppKit import *from WebKit import *from Foundation import *import appimport prefsimport configimport resourcesimport platformutils################################################################################ These are used by the channel guide. This platform uses the# old-style 'magic URL' guide API, so we just return None. See# ChannelGuideToDtvApi in the Trac wiki for the full writeup.###############################################################################def getDTVAPICookie(): return Nonedef getDTVAPIURL(): return None###############################################################################class HTMLDisplay (app.Display): "HTML browser that can be shown in a MainFrame's right-hand pane."# sharedWebView = None # We don't need to override onSelected, onDeselected def __init__(self, html, existingView=None, frameHint=None, areaHint=None, baseURL=None): """'html' is the initial contents of the display, as a string. If frameHint is provided, it is used to guess the initial size the HTML display will be rendered at, which might reduce flicker when the display is installed.""" self.readyToDisplayHook = None self.readyToDisplay = False # The template system currently generates UTF-8. For now, we # just convert that back to unicode as necessary. See #3708 html = html.decode('utf-8') self.web = ManagedWebView.alloc().init(html, None, self.nowReadyToDisplay, lambda x:self.onURLLoad(x), frameHint and areaHint and frameHint.getDisplaySizeHint(areaHint) or None, baseURL) app.Display.__init__(self) def getEventCookie(self): return '' def getDTVPlatformName(self): return 'webkit' def getBodyTagExtra(self): return 'ondragstart="handleDragStart(event);" ondragover="return handleDragOver(event);" ondragleave="return handleDragLeave(event);" ondrop="return handleDrop(event);" ' def getView(self): return self.web.getView() def execJS(self, js): """Execute the given Javascript code (provided as a string) in the context of this HTML document.""" js = js.decode('utf-8') try: self.web.execJS(js) except AttributeError: print "Couldn't exec javascript! Web view not initialized" #print "DISP: %s with %s" % (self.view, js) # DOM hooks used by the dynamic template code -- do they need a # try..except wrapper like the above? def addItemAtEnd(self, xml, id): xml = xml.decode('utf-8') return self.web.addItemAtEnd(xml, id) def addItemBefore(self, xml, id): xml = xml.decode('utf-8') return self.web.addItemBefore(xml, id) def removeItem(self, id): return self.web.removeItem(id) def removeItems(self, ids): return self.web.removeItems(ids) def changeItem(self, id, xml, changedAttrs, newInnerHTML): xml = xml.decode('utf-8') return self.web.changeItem(id, xml, changedAttrs, newInnerHTML) def changeItems(self, args): newArgs = [] for id, xml, changedAttrs, newInnerHTML in args: newArgs.append((id, xml.decode('utf-8'), changedAttrs, newInnerHTML)) return self.web.changeItems(newArgs) def hideItem(self, id): return self.web.hideItem(id) def showItem(self, id): return self.web.showItem(id) def onURLLoad(self, url): """Called when this HTML browser attempts to load a URL (either through user action or Javascript.) The URL is provided as a string. Return true to allow the URL to load, or false to cancel the load (for example, because it was a magic URL that marks an item to be downloaded.) Implementation in HTMLDisplay always returns true; override in a subclass to implement special behavior.""" # For overriding pass def callWhenReadyToDisplay(self, hook): if self.readyToDisplay: hook() else: assert self.readyToDisplayHook == None self.readyToDisplayHook = hook # Called (via callback established in constructor) def nowReadyToDisplay(self): self.readyToDisplay = True if self.readyToDisplayHook: hook = self.readyToDisplayHook self.readyToDisplayHook = None hook() def unlink(self): webView = self.web.getView() if webView is not nil: platformutils.warnIfNotOnMainThread('HTMLDisplay.unlink') webView.setHostWindow_(self.currentFrame.obj.window()) # not very pretty @platformutils.onMainThreadWaitingUntilDone def cancel(self): print "DTV: Canceling load of WebView %s" % self.web.getView() self.web.getView().stopLoading_(nil) self.readyToDisplay = False self.readyToDisplayHook = None ###############################################################################class ManagedWebHTMLView (WebHTMLView): def rightMouseDown_(self, event): # We want a right click to also select what's underneath so we intercept # the event here, force the left click handler first and reschedule the # right click handler. platformutils.callOnMainThread(self.mouseDown_, event) platformutils.callOnMainThreadAfterDelay(0.2, WebHTMLView.rightMouseDown_, self, event)###############################################################################class ManagedWebView (NSObject): WebView.registerViewClass_representationClass_forMIMEType_(ManagedWebHTMLView, WebHTMLRepresentation, 'text/html') def init(self, initialHTML, existingView=nil, onInitialLoadFinished=None, onLoadURL=None, sizeHint=None, baseURL=None): self.onInitialLoadFinished = onInitialLoadFinished self.onLoadURL = onLoadURL self.initialLoadFinished = False self.view = existingView platformutils.callOnMainThreadAndWaitUntilDone(self.initWebView, initialHTML, sizeHint, baseURL) return self def initWebView(self, initialHTML, sizeHint, baseURL): platformutils.warnIfNotOnMainThread('ManagedWebView.initWebView') if not self.view: self.view = WebView.alloc().init() #print "***** Creating new WebView %s" % self.view if sizeHint: # We have an estimate of the size that will be assigned to # the view when it is actually inserted in the MainFrame. # Use this to size the view we just created so the HTML # is hopefully rendered to the correct dimensions, instead # of having to be corrected after being displayed. self.view.setFrame_(sizeHint) self.view.setCustomUserAgent_("%s/%s (%s)" % \ (config.get(prefs.SHORT_APP_NAME), config.get(prefs.APP_VERSION), config.get(prefs.PROJECT_URL),)) else: #print "***** Using existing WebView %s" % self.view if sizeHint: self.view.setFrame_(sizeHint) self.execQueue = [] self.view.setPolicyDelegate_(self) self.view.setResourceLoadDelegate_(self) self.view.setFrameLoadDelegate_(self) self.view.setUIDelegate_(self) html = NSString.stringWithString_(unicode(initialHTML)) data = html.dataUsingEncoding_(NSUTF8StringEncoding) if baseURL is not None: baseURL = NSURL.URLWithString_(baseURL) self.view.mainFrame().loadData_MIMEType_textEncodingName_baseURL_(data, 'text/html', 'utf-8', baseURL) def isKeyExcludedFromWebScript_(self,key):
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -