Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

# -*- coding: utf-8 -*- 

""" 

@file 

@brief :epkg:`Sphinx` extension for images. 

""" 

__author__ = 'Tomasz Czyż <tomaszczyz@gmail.com>' 

__license__ = "Apache 2" 

 

import os 

import sys 

import copy 

import uuid 

import hashlib 

import functools 

import logging 

import sphinx 

from sphinx.util.osutil import copyfile 

from sphinx.util import status_iterator 

from sphinx.util.console import brown 

try: 

from docutils.parsers.rst import Directive 

except ImportError: 

from sphinx.util.compat import Directive 

from sphinx.util.osutil import ensuredir 

from docutils import nodes 

from docutils.parsers.rst import directives 

import requests 

from .. import LightBox2 

 

 

STATICS_DIR_NAME = '_static' 

 

 

DEFAULT_CONFIG = dict( 

backend='LightBox2', 

default_image_width='100%', 

default_image_height='auto', 

default_group=None, 

default_show_title=False, 

download=False, 

requests_kwargs={}, 

cache_path='_images', 

override_image_directive=False, 

show_caption=False, 

) 

 

 

class image_node(nodes.image, nodes.General, nodes.Element): 

":epkg:`sphinx` node" 

pass 

 

 

class gallery_node(nodes.image, nodes.General, nodes.Element): 

":epkg:`sphinx` node" 

pass 

 

 

def directive_boolean(value): 

"local function" 

if not value.strip(): 

raise ValueError("No argument provided but required") 

if value.lower().strip() in ["yes", "1", 1, "true", "ok"]: 

return True 

elif value.lower().strip() in ['no', '0', 0, 'false', 'none']: 

return False 

else: 

raise ValueError(u"Please use on of: yes, true, no, false. " 

u"Do not use `{}` as boolean.".format(value)) 

 

 

def get_image_extension(uri): 

""" 

Guesses an extension for an image. 

""" 

exts = {'.jpg', '.png', '.svg', '.bmp'} 

for ext in exts: 

if uri.endswith(ext): 

return ext 

for ext in exts: 

if ext in uri: 

return ext 

for ext in exts: 

if (ext[1:] + "=true") in uri: 

return ext 

if ('?' + ext[1:]) in uri: 

return ext 

logger = logging.getLogger('image') 

logger.warning("[image] unable to guess extension for '{0}'".format(uri)) 

return '' 

 

 

class ImageDirective(Directive): 

''' 

Directive which overrides default sphinx directive. 

It's backward compatibile and it's adding more cool stuff. 

''' 

 

align_values = ('left', 'center', 'right') 

 

def align(self): 

# This is not callable as self.align. It cannot make it a 

# staticmethod because we're saving an unbound method in 

# option_spec below. 

return directives.choice(self, ImageDirective.align_values) 

 

has_content = True 

required_arguments = True 

 

option_spec = { 

'width': directives.length_or_percentage_or_unitless, 

'height': directives.length_or_unitless, 

'strech': directives.choice, 

 

'group': directives.unchanged, 

'class': directives.class_option, # or str? 

'alt': directives.unchanged, 

'target': directives.unchanged, 

'download': directive_boolean, 

'title': directives.unchanged, 

'align': align, 

'show_caption': directive_boolean, 

'legacy_class': directives.class_option, 

} 

 

def run(self): 

env = self.state.document.settings.env 

conf = env.app.config.images_config 

 

# TODO get defaults from config 

group = self.options.get('group', 

conf['default_group'] if conf['default_group'] else uuid.uuid4()) 

classes = self.options.get('class', '') 

width = self.options.get('width', conf['default_image_width']) 

height = self.options.get('height', conf['default_image_height']) 

alt = self.options.get('alt', '') 

target = self.options.get('target', '') 

title = self.options.get( 

'title', '' if conf['default_show_title'] else None) 

align = self.options.get('align', '') 

show_caption = self.options.get('show_caption', False) 

legacy_classes = self.options.get('legacy_class', '') 

 

# TODO get default from config 

download = self.options.get('download', conf['download']) 

 

# parse nested content 

# TODO: something is broken here, not parsed as expected 

description = nodes.paragraph() 

content = nodes.paragraph() 

content += [nodes.Text("%s" % x) for x in self.content] 

self.state.nested_parse(content, 0, description) 

 

img = image_node() 

 

try: 

is_remote = self.is_remote(self.arguments[0]) 

except ValueError as e: 

this = os.path.abspath(os.path.dirname(__file__)) 

repl = os.path.join(this, "missing.png") 

self.arguments[0] = repl 

is_remote = self.is_remote(self.arguments[0]) 

logger = logging.getLogger('image') 

logger.warning("[image] {0}, replaced by '{1}'".format(e, repl)) 

 

if is_remote: 

img['remote'] = True 

if download: 

img['uri'] = os.path.join('_images', hashlib.sha1( 

self.arguments[0].encode()).hexdigest()) 

img['uri'] += get_image_extension(self.arguments[0]) 

img['remote_uri'] = self.arguments[0] 

env.remote_images[img['remote_uri']] = img['uri'] 

env.images.add_file('', img['uri']) 

else: 

img['uri'] = self.arguments[0] 

img['remote_uri'] = self.arguments[0] 

else: 

img['uri'] = self.arguments[0] 

img['remote'] = False 

env.images.add_file('', img['uri']) 

 

img['content'] = description.astext() 

img['target'] = target 

 

if title is None: 

img['title'] = '' 

elif title: 

img['title'] = title 

else: 

img['title'] = img['content'] 

img['content'] = '' 

 

img['show_caption'] = show_caption 

img['legacy_classes'] = legacy_classes 

img['group'] = group 

img['size'] = (width, height) 

img['width'] = width 

img['height'] = height 

img['classes'] += classes 

img['alt'] = alt 

img['align'] = align 

img['download'] = download 

return [img] 

 

def is_remote(self, uri): 

"local function" 

uri = uri.strip() 

env = self.state.document.settings.env 

if self.state.document.settings._source is not None: 

app_directory = os.path.dirname( 

os.path.abspath(self.state.document.settings._source)) 

else: 

app_directory = None 

 

if uri[0] == '/': 

return False 

if uri[0:7] == 'file://': 

return False 

if os.path.isfile(os.path.join(env.srcdir, uri)): 

return False 

if app_directory and os.path.isfile(os.path.join(app_directory, uri)): 

return False 

if '://' in uri: 

return True 

raise ValueError('Image URI `{}` have to be local relative or ' 

'absolute path to image, or remote address.' 

.format(uri)) 

 

 

def install_backend_static_files(app, env): 

"local function" 

STATICS_DIR_PATH = os.path.join(app.builder.outdir, STATICS_DIR_NAME) 

dest_path = os.path.join(STATICS_DIR_PATH, 'sphinxtrib-images', 

app.sphinxtrib_images_backend.__class__.__name__) 

files_to_copy = app.sphinxtrib_images_backend.STATIC_FILES 

 

for source_file_path in status_iterator(files_to_copy, 

'Copying static files for images...', brown, len(files_to_copy)): 

 

dest_file_path = os.path.join(dest_path, source_file_path) 

 

if not os.path.exists(os.path.dirname(dest_file_path)): 

ensuredir(os.path.dirname(dest_file_path)) 

 

source_file_path = os.path.join(os.path.dirname( 

sys.modules[app.sphinxtrib_images_backend.__class__.__module__].__file__), 

source_file_path) 

 

copyfile(source_file_path, dest_file_path) 

 

if dest_file_path.endswith('.js'): 

name = os.path.relpath(dest_file_path, STATICS_DIR_PATH) 

try: 

# Sphinx >= 1.8 

app.add_js_file(name) 

except AttributeError: 

# Sphinx < 1.8 

app.add_javascript(name) 

elif dest_file_path.endswith('.css'): 

name = os.path.relpath(dest_file_path, STATICS_DIR_PATH) 

try: 

# Sphinx >= 1.8 

app.add_css_file(name) 

except AttributeError: 

# Sphinx < 1.8 

app.add_stylesheet(name) 

 

 

def download_images(app, env): 

""" 

Downloads images before running the documentation. 

 

@param app :epkg:`Sphinx` application 

@param env environment 

""" 

logger = logging.getLogger("image") 

conf = app.config.images_config 

for src in status_iterator(env.remote_images, 

'Downloading remote images...', brown, 

len(env.remote_images)): 

dst = os.path.join(env.srcdir, env.remote_images[src]) 

dirn = os.path.dirname(dst) 

ensuredir(dirn) 

if not os.path.isfile(dst): 

 

logger.info('{} -> {} (downloading)'.format(src, dst)) 

with open(dst, 'wb') as f: 

# TODO: apply reuqests_kwargs 

try: 

f.write(requests.get(src, 

**conf['requests_kwargs']).content) 

except requests.ConnectionError: 

logger.info("Cannot download `{}`".format(src)) 

else: 

logger.info('{} -> {} (already in cache)'.format(src, dst)) 

 

 

def configure_backend(app): 

"local function" 

global DEFAULT_CONFIG 

 

config = copy.deepcopy(DEFAULT_CONFIG) 

config.update(app.config.images_config) 

app.config.images_config = config 

 

# ensuredir(os.path.join(app.env.srcdir, config['cache_path'])) 

 

# html builder 

# self.relfn2path(imguri, docname) 

 

backend_name_or_callable = config['backend'] 

if callable(backend_name_or_callable): 

pass 

elif backend_name_or_callable == "LightBox2": 

backend = LightBox2 

else: 

raise TypeError("images backend is configured improperly. It is `{}` (type:`{}`).".format( 

backend_name_or_callable, type(backend_name_or_callable))) 

 

backend = backend(app) 

 

# remember the chosen backend for processing. Env and config cannot be used 

# because sphinx try to make a pickle from it. 

app.sphinxtrib_images_backend = backend 

 

logger = logging.getLogger("image") 

logger.info('Initiated images backend: ', nonl=True) 

logger.info('`{}`'.format( 

str(backend.__class__.__module__ + ':' + backend.__class__.__name__))) 

 

def backend_methods(node, output_type): 

"local function" 

def backend_method(f): 

"local function" 

@functools.wraps(f) 

def inner_wrapper(writer, node): 

"local function" 

return f(writer, node) 

return inner_wrapper 

signature = '_{}_{}'.format(node.__name__, output_type) 

return (backend_method(getattr(backend, 'visit' + signature, getattr(backend, 'visit_' + node.__name__ + '_fallback'))), 

backend_method(getattr(backend, 'depart' + signature, getattr(backend, 'depart_' + node.__name__ + '_fallback')))) 

 

# add new node to the stack 

# connect backend processing methods to this node 

app.add_node(image_node, **{output_type: backend_methods(image_node, output_type) 

for output_type in ('html', 'latex', 'man', 'texinfo', 'text', 'epub')}) 

 

app.add_directive('thumbnail', ImageDirective) 

if config['override_image_directive']: 

app.add_directive('image', ImageDirective) 

app.env.remote_images = {} 

 

 

def setup(app): 

"""setup for :epkg:`sphinx` extension""" 

global DEFAULT_CONFIG 

app.add_config_value('images_config', DEFAULT_CONFIG, 'env') 

app.connect('builder-inited', configure_backend) 

app.connect('env-updated', download_images) 

app.connect('env-updated', install_backend_static_files) 

return {'version': sphinx.__version__, 'parallel_read_safe': True}