def Title(title, sections=[], logo=None, logo_width=0, logo_padding=8, icon=None, icon_width=None): """Renders a title. sections: deprecated, used to be used for pre-registering section names for the bookmark bars, but this is now built automatically. """ # if type(sections) is str: # sections = [x.strip() for x in sections.split("|")] # for name in sections: # add_section(name) rootdir = radiopadre.ABSROOTDIR homedir = os.path.expanduser("~") if homedir[-1] != "/": homedir += "/" if rootdir.startswith(homedir): rootdir = rootdir[len(homedir):] global logo_image, icon_image if logo and os.path.exists(logo): mw = logo_width + logo_padding logo_width = f" width={logo_width}" if logo_width else "" logo = render.render_url(logo) logo_image = f"""<img src="{logo}" alt="" {logo_width}></img>""" logo_style = f"padding-right: {logo_padding}px; vertical-align: middle; min-width: {mw}px" else: logo_style = "" if icon: icon = render.render_url(icon) icon_width = f" width={icon_width}" if icon_width else "" icon_image = f"""<img src="{icon}" alt="" {icon_width}></img>""" display( HTML(f""" <div class="rp-title-block" style="display: table-row; margin-top: 0.5em; width: 100%"> <div style="display: table-cell; {logo_style}">{logo_image}</div> <div style="display: table-cell; vertical-align: middle; width: 100%"> <div style="display: table; width: 100%"> <div style="display: table-row"> <div style="display: table-cell"> <div class="rp-notebook-title">{title}</div> </div> </div> <div style="display: table-row;"> <div style="display: table-cell; width: 100%; padding-top: .2em"> <div class="rp-notebook-path">[{rootdir}]</div> </div> </div> </div> </div> </div> """))
def _show_thumbs(images, width=None, ncol=None, maxwidth=None, mincol=None, external_thumbs=None, maxcol=None, title=None, **kw): if not images: return None nrow, ncol, width = radiopadre.file.compute_thumb_geometry( len(images), ncol, mincol, maxcol, width, maxwidth) npix = int(radiopadre.DPI * width) # make list of basename, filename tuples filelist = sorted( [(os.path.basename(img.fullpath), img.fullpath) for img in images]) # keep track of thumbnail fails nfail = 0 html = render_preamble() + render_title(title) + \ """<br> <table style="border: 0px; text-align: left">\n """ for row in range(nrow): html += """<tr style="border: 0px; text-align: left">\n""" filelist_row = filelist[row * ncol:(row + 1) * ncol] for name, image in filelist_row: html += """<td style="border: 0px; text-align: center">""" html += "<a href=%s target='_blank'>%s</a>" % (render_url(image), name) html += "</td>\n" html += """</tr><tr style="border: 0px; text-align: left">\n""" for _, image in filelist_row: if external_thumbs is False: thumb = None # make thumbnail and record exceptions. Print the first one, as # they really shouldn't happen else: try: thumb = _make_thumbnail(image, npix) if not thumb and external_thumbs: nfail += 1 except: if not nfail: traceback.print_exc() nfail += 1 thumb = None html += """<td style="border: 0px; text-align: left">""" if thumb: html += "<a href=%s target='_blank'><img src=%s alt='?'></a>" % ( render_url(image), render_url(thumb)) else: html += "<a href=%s target='_blank'><img src=%s width=%d alt='?'></a>" % ( render_url(image), render_url(image), npix) html += "</td>\n" html += "</tr>\n" html += "</table>" if nfail: html += "(WARNING: %d thumbnails unexpectedly failed to generate, check console for errors)<br>\n" % nfail display(HTML(html))
def _render_thumbnail(imagepath, url=None, npix=None, mtime=0): npix_thumb = settings.thumb.width or settings.display.cell_width // settings.thumb.mincol npix = npix or npix_thumb url = url or render_url(imagepath) if mtime is not None: url += _mtime(mtime or os.path.getmtime(imagepath)) if is_svg_file(imagepath): thumb = None # SVG files rendered natively, no thumbnail needed else: _, thumb = _make_thumbnail(imagepath, npix_thumb) thumb_url = render_url(thumb) if thumb else url return f"<a href='{url}' target='_blank'><img src='{thumb_url}' width={npix} alt='?'></a>"
def render_html(self, width="99%", height=None): width = width or settings.display.cell_width height = height or settings.display.window_height url = render_url(self.fullpath) html = render_preamble() + render_title(self.title) html += """<IFRAME width={width} height={height} src={url}></IFRAME>""".format(**locals()) return html
def __init__(self, path, load=False, title=None): """Construct a datafile and set up standard attributes. Args: path: path to the file load: if True, will "load" detailed file content by calling self._load(). The meaning of this depends on the subclass. For example, when a DataDir loads, it will scan its content. In general, __init__ is meant to be fast, while slower operations are deferred to _load(). """ self.fullpath = path self.path = FileBase.get_display_path(path) if title is None: if os.path.isdir(self.fullpath): title = rich_string(self.path, bold=True) else: title = rich_string(self.path, "<A HREF='{}' target='_blank'><B>{}</B></A>".format(render_url(self.fullpath), self.path)) ItemBase.__init__(self, title=title) self.name = os.path.basename(self.fullpath) self.basepath, self.ext = os.path.splitext(self.path) self.basename = os.path.basename(self.basepath) # directory key set up for sorting purposes # directories sort themselves before files isdir = int(os.path.isdir(self.fullpath)) self._dirkey = 1-isdir, os.path.dirname(self.fullpath) self._scan_impl() # timestamp of file last time content was loaded self._loaded_mtime = None if load: self._load()
def _show_thumbs(images, title='', showpath=False, **kw): if images: images[0].message("Rendering thumbnails, please wait...", timeout=0) filelist = [(img.fullpath if showpath else os.path.basename(img.fullpath), img.fullpath, render_url(img.fullpath)) for img in images] html = render_thumbs(filelist, **kw) images[0].clear_message() display(HTML(render_preamble() + render_title(title) + html))
def html(self,tail=None,head=None,fs=.8): txt = render_preamble() txt += "<A HREF=%s target='_blank'>" % render_url(self.fullpath) + \ render_title(self.path) + "</A> modified %s:" % self.update_mtime(); txt += """\n<PRE style="font-size: %d%%; line-height: 110%%">"""%(fs*100) + \ (cgi.escape(self.head(head)) if head else "") + \ ("...\n" if head and tail else "") + \ (cgi.escape(self.tail(tail)) if tail else "") + \ "</PRE>" return txt
def _render_title_link(self, showpath=False, url=None, **kw): """Renders the name of the file, with a download link (if downloading should be supported)""" name = self.path if showpath else self.name url = url or self.downloadable_url if url: url = url or render_url(self.fullpath) return "<a href='{url}' target='_blank'>{name}</a>".format( **locals()) else: return "{name}".format(**locals())
def render_html(self, width="99%", context=None, height=None, title=None, collapsed=None, **kw): title_html = self._header_html(title=title) if collapsed is None and settings.gen.collapsible: collapsed = False width = width or settings.display.cell_width height = height or settings.display.window_height url = render_url(self.fullpath) content_html = f"""<IFRAME width={width} height={height} src={url}></IFRAME>""" return render_preamble() + \ render_titled_content(title_html=title_html, content_html=content_html, collapsed=collapsed)
def _render_thumb_impl(self, width=None, height=None, refresh=False, **kw): width = settings.html.get(width=width) height = settings.html.get(height=height) thumbnail, thumbnail_url, update = self._get_cache_file("html-render", "png", keydict=dict(width=width, height=height)) if update or refresh: url = "file://" + os.path.abspath(self.fullpath) try: _render_html(url, thumbnail, width, height, 200) except Exception as exc: return render_error(str(exc)) return imagefile.ImageFile._render_thumbnail(thumbnail, url=render_url(self.fullpath), npix=width) + "\n"
def _render_thumb_impl(self, npix=None, **kw): thumbnail, thumbnail_url, update = self._get_cache_file( "pdf-render", "png") npix = npix or 800 if update: cmd = "gs -sDEVICE=png16m -sOutputFile={thumbnail} -dLastPage=1 -r300 -dDownScaleFactor=4 -dBATCH " \ "-dNOPAUSE {self.fullpath}".format(**locals()) try: output = subprocess.check_output(cmd, shell=True) except subprocess.CalledProcessError as exc: print(f"{cmd}: {exc.output}") return render_error(f"phantomjs error (code {exc.returncode})") return imagefile.ImageFile._render_thumbnail( thumbnail, url=render_url(self.fullpath), npix=npix) + "\n"
def _render_thumb_impl(self, fs=0.5, head=None, tail=None, **kw): self.rescan(load=True) head = settings.text.get(head=head) tail = settings.text.get(tail=tail) head, tail = self._get_lines(head, tail) lh = fs * 1.2 # html = """<DIV style="display: table; width: 100%; font-size: {fs}em; line-height: {lh}em">""".format(**locals()) # # def render_line(line): # # background = "#f2f2f2" if line_num != "..." else "none" # line = unicode(line, "utf-8").encode("ascii", "xmlcharrefreplace") # return """ # <DIV style="display: table-row; height=1em"> # <DIV style="display: table-cell; height=1em; text-align: left"><PRE>{line}</PRE> # </DIV> # </DIV>\n""".format(**locals()) # # for line_num, line in head: # html += render_line(cgi.escape(line)) # if tail: # html += render_line("...") # for line_num, line in tail: # html += render_line(cgi.escape(line)) # html += "\n</DIV>\n" # return html text = "".join([h[1] for h in head]) if tail: text += " ⋯\n" text += "".join([t[1] for t in tail]) text = htmlize(text) text = """ <DIV style="display: table-cell; font-size: {fs}em; text-align: left; overflow: hidden; text-decoration: none !important"> <PRE style="white-space: pre-wrap; overflow: hidden; width=100%">{text}</PRE> </DIV> """.format(**locals()) url = render_url(getattr(self, 'fullpath', self.path)) return """<A HREF='{url}' target='_blank' style="text-decoration: none">{text}</A>""".format( **locals())
def __init__(self, path, load=False, title=None): """Construct a datafile and set up standard attributes. Args: path: path to the file load: if True, will "load" detailed file content by calling self._load(). The meaning of this depends on the subclass. For example, when a DataDir loads, it will scan its content. In general, __init__ is meant to be fast, while slower operations are deferred to _load(). """ self.fullpath = path self.path = FileBase.get_display_path(path) if title is None: if os.path.isdir(self.fullpath): title = rich_string(self.path, bold=True) else: title = rich_string( self.path, "<A HREF='{}' target='_blank'><B>{}</B></A>".format( render_url(self.fullpath), self.path)) ItemBase.__init__(self, title=title) self.name = os.path.basename(self.fullpath) self.basepath, self.ext = os.path.splitext(self.path) self.basename = os.path.basename(self.basepath) self._subproduct_cache = {} # directory key set up for sorting purposes # directories sort themselves before files isdir = int(os.path.isdir(self.fullpath)) self._dirkey = 1 - isdir, os.path.dirname(self.fullpath) self._scan_impl() # timestamp of file last time content was loaded self._loaded_mtime = None if load: self._load()
def downloadable_url(self): return render_url(self.fullpath, notebook=True)
def render_thumbs(name_path_url, width=None, ncol=None, maxwidth=None, mincol=None, maxcol=None, include_titles=True, external_thumbs=None, action_buttons={}): """ Renders a set of thumbnails in a table. Use by both ImageFIle and FITSFile. name_path_url is a list of (name, path, url) tuples """ if not name_path_url: return "" nrow, ncol, width = radiopadre.file.compute_thumb_geometry( len(name_path_url), ncol, mincol, maxcol, width, maxwidth) npix = int(settings.plot.screen_dpi * width) # keep track of thumbnail fails nfail = 0 html = """<table style="border: 0px; text-align: left">\n""" for row in range(nrow): filelist_row = name_path_url[row * ncol:(row + 1) * ncol] if include_titles: html += """<tr style="border: 0px; text-align: left">\n""" for name, image, url in filelist_row: html += """<td style="border: 0px; text-align: center">""" if type(name) is RichString: html += name.html elif url[0] != '#': html += "<a href='{}' target='_blank'>{}</a>".format(url, name) else: html += name html += "</td>\n" html += """</tr>\n""" html += """<tr style="border: 0px; text-align: left">\n""" for name, image, url in filelist_row: if url[0] == '#': html += """<td style="border: 0px; text-align: center">{}</td>""".format(url[1:]) else: if external_thumbs is False: thumb = None # make thumbnail and record exceptions. Print the first one, as # they really shouldn't happen else: try: thumb_realfile, thumb = _make_thumbnail(image, npix) if not thumb and external_thumbs: nfail += 1 except: if not nfail: traceback.print_exc() nfail += 1 thumb = None html += """<td style="border: 0px; text-align: left"><div style="position: relative"><div>""" mtime = os.path.getmtime(image) if thumb: html += "<a href='{}?mtime={}' target='_blank'><img src='{}' alt='?'></a>".format( url, mtime, render_url(thumb)) else: html += "<a href='{}?mtime={}' target='_blank'><img src='{}?mtime={}' width={} alt='?'></a>".format( url, mtime, url, mtime, npix) if image in action_buttons: html += """</div><div style="position: absolute; top: 0; left: 0">{}""".format(action_buttons[image]) html += "</div></div></td>\n" html += "</tr>\n" html += "</table>" if nfail: html += "(WARNING: %d thumbnails unexpectedly failed to generate, check console for errors)<br>\n" % nfail return html
def downloadable_url(self): """Returns downloadable URL for this file, or None if the file should not have a download link""" return render_url(self.fullpath)