#!/usr/bin/env python # -*- coding: utf-8 -*- """ Create image galleries with GalleriaJS """ import os from typing import Dict, Any from sphinx.application import Sphinx from sphinx.environment import BuildEnvironment from sphinx.util.osutil import ensuredir, copyfile from PIL import Image from . import directive from . import collector __version_info__ = (1, 0, 0) __version__ = '.'.join([str(val) for val in __version_info__]) def copy_images_files(app: Sphinx, env: BuildEnvironment) -> None: if hasattr(env, 'galleria') and env.galleria: for source in env.galleria: relpath = os.path.relpath(source, env.srcdir) dest = os.path.join(app.outdir, relpath) ensuredir(os.path.dirname(dest)) copyfile(source, dest) if hasattr(env, 'galleriathumbs') and env.galleriathumbs: for thumb in env.galleriathumbs: relpath = os.path.relpath(thumb, env.srcdir) dest = os.path.join(app.outdir, relpath) basename, ext = os.path.splitext(dest) thumbsize = basename.split('-')[-1].split('x') thumbsize = [int(size) for size in thumbsize] original = '.'.join(basename.split('.')[:-1]) + ext dest = basename + '.jpg' ensuredir(os.path.dirname(dest)) with Image.open(original) as im: im.thumbnail(thumbsize) im.save(dest, "JPEG") def install_static_files(app: Sphinx, env: BuildEnvironment) -> None: path = os.path.join( app.builder.outdir, '_static', 'sphinxgalleria' ) source = os.path.join( os.path.dirname(__file__), 'static', 'sphinxgalleria', ) statics = [] for dirpath, dirs, files in os.walk(source): source_path = os.path.relpath(dirpath, source) for static in files: statics.append(os.path.join(source_path, static)) for static in statics: static_path = os.path.join(path, static) source_path = os.path.join(source, static) if not os.path.exists(os.path.dirname(static_path)): ensuredir(os.path.dirname(static_path)) copyfile(source_path, static_path) if static.endswith('.js'): app.add_js_file(os.path.join('sphinxgalleria', static)) elif static.endswith('.css'): app.add_css_file(os.path.join('sphinxgalleria', static)) def setup(app: Sphinx) -> Dict[str, Any]: app.add_node( directive.galleria, html=(directive.html_visit_galleria, None), epub=(directive.html_visit_galleria, None), latex=(directive.latex_visit_galleria, None), texinfo=(directive.texinfo_visit_galleria, None), text=(directive.text_visit_galleria, None), man=(directive.man_visit_galleria, None), gemini=(directive.gemini_visit_galleria, None), ) app.add_directive('galleria', directive.GalleriaDirective) app.add_env_collector(collector.GalleriaCollector) app.connect('env-updated', install_static_files) app.connect('env-updated', copy_images_files) return {'version': __version__}