Class: ReVIEW::EPUBMaker

Inherits:
Object show all
Includes:
EPUBMaker, REXML
Defined in:
lib/review/epubmaker.rb

Defined Under Namespace

Classes: ReVIEWHeaderListener

Instance Method Summary collapse

Constructor Details

#initializeEPUBMaker

Returns a new instance of EPUBMaker.



33
34
35
36
37
# File 'lib/review/epubmaker.rb', line 33

def initialize
  @producer = nil
  @htmltoc = nil
  @buildlogtxt = "build-log.txt"
end

Instance Method Details

#build_body(basetmpdir, yamlfile) ⇒ Object



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
# File 'lib/review/epubmaker.rb', line 222

def build_body(basetmpdir, yamlfile)
  @precount = 0
  @bodycount = 0
  @postcount = 0

  @manifeststr = ""
  @ncxstr = ""
  @tocdesc = Array.new

  basedir = File.dirname(yamlfile)
  base_path = Pathname.new(basedir)
  book = ReVIEW::Book.load(basedir)
  book.config = @params
  @converter = ReVIEW::Converter.new(book, ReVIEW::HTMLBuilder.new)
  @compile_errors = nil
  book.parts.each do |part|
    htmlfile = nil
    if part.name.present?
      if part.file?
        build_chap(part, base_path, basetmpdir, true)
      else
        htmlfile = "part_#{part.number}.#{@params["htmlext"]}"
        build_part(part, basetmpdir, htmlfile)
        title = ReVIEW::I18n.t("part", part.number)
        title += ReVIEW::I18n.t("chapter_postfix") + part.name.strip if part.name.strip.present?
        @htmltoc.add_item(0, htmlfile, title, {:chaptype => "part"})
        write_buildlogtxt(basetmpdir, htmlfile, "")
      end
    end

    part.chapters.each do |chap|
      build_chap(chap, base_path, basetmpdir, false)
    end

  end
  check_compile_status()
end

#build_chap(chap, base_path, basetmpdir, ispart) ⇒ Object



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
# File 'lib/review/epubmaker.rb', line 287

def build_chap(chap, base_path, basetmpdir, ispart)
  filename = ""

  chaptype = "body"
  if ispart
    chaptype = "part"
  elsif chap.on_PREDEF?
    chaptype = "pre"
  elsif chap.on_APPENDIX?
    chaptype = "post"
  end

  if ispart.present?
    filename = chap.path
  else
    filename = Pathname.new(chap.path).relative_path_from(base_path).to_s
  end
  id = filename.sub(/\.re\Z/, "")

  if @params["epubmaker"]["rename_for_legacy"] && ispart.nil?
    if chap.on_PREDEF?
      @precount += 1
      id = sprintf("pre%02d", @precount)
    elsif chap.on_APPENDIX?
      @postcount += 1
      id = sprintf("post%02d", @postcount)
    else
      @bodycount += 1
      id = sprintf("chap%02d", @bodycount)
    end
  end

  htmlfile = "#{id}.#{@params["htmlext"]}"
  write_buildlogtxt(basetmpdir, htmlfile, filename)
  log("Create #{htmlfile} from #{filename}.")

  if @params["params"].present?
    warn "'params:' in config.yml is obsoleted."
    if @params["params"] =~ /stylesheet=/
      warn "stylesheets should be defined in 'stylesheet:', not in 'params:'"
    end
  end
  begin
    @converter.convert(filename, File.join(basetmpdir, htmlfile))
    write_info_body(basetmpdir, id, htmlfile, ispart, chaptype)
    remove_hidden_title(basetmpdir, htmlfile)
  rescue => e
    @compile_errors = true
    warn "compile error in #{filename} (#{e.class})"
    warn e.message
  end
end

#build_part(part, basetmpdir, htmlfile) ⇒ Object



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/review/epubmaker.rb', line 260

def build_part(part, basetmpdir, htmlfile)
  log("Create #{htmlfile} from a template.")
  File.open("#{basetmpdir}/#{htmlfile}", "w") do |f|
    @body = ""
    @body << "<div class=\"part\">\n"
    @body << "<h1 class=\"part-number\">#{CGI.escapeHTML(ReVIEW::I18n.t("part", part.number))}</h1>\n"
    if part.name.strip.present?
      @body << "<h2 class=\"part-title\">#{CGI.escapeHTML(part.name.strip)}</h2>\n"
    end
    @body << "</div>\n"

    @language = @producer.params['language']
    @stylesheets = @producer.params["stylesheet"]
    tmplfile = File.expand_path(template_name, ReVIEW::Template::TEMPLATE_DIR)
    tmpl = ReVIEW::Template.load(tmplfile)
    f.write tmpl.result(binding)
  end
end

#build_pathObject



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/review/epubmaker.rb', line 52

def build_path
  if @params["debug"]
    path = File.expand_path("#{@params["bookname"]}-epub", Dir.pwd)
    if File.exist?(path)
      FileUtils.rm_rf(path, :secure => true)
    end
    Dir.mkdir(path)
    return path
  else
    return Dir.mktmpdir("#{@params["bookname"]}-epub-")
  end
end

#build_titlepage(basetmpdir, htmlfile) ⇒ Object



437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/review/epubmaker.rb', line 437

def build_titlepage(basetmpdir, htmlfile)
  # TODO: should be created via epubcommon
  @title = CGI.escapeHTML(@params.name_of("booktitle"))
  File.open("#{basetmpdir}/#{htmlfile}", "w") do |f|
    @body = ""
    @body << "<div class=\"titlepage\">\n"
    @body << "<h1 class=\"tp-title\">#{CGI.escapeHTML(@params.name_of("booktitle"))}</h1>\n"
    if @params["aut"]
      @body << "<h2 class=\"tp-author\">#{CGI.escapeHTML(@params.names_of("aut").join(ReVIEW::I18n.t("names_splitter")))}</h2>\n"
    end
    if @params["prt"]
      @body << "<h3 class=\"tp-publisher\">#{CGI.escapeHTML(@params.names_of("prt").join(ReVIEW::I18n.t("names_splitter")))}</h3>\n"
    end
    @body << "</div>"

    @language = @producer.params['language']
    @stylesheets = @producer.params["stylesheet"]
    tmplfile = File.expand_path(template_name, ReVIEW::Template::TEMPLATE_DIR)
    tmpl = ReVIEW::Template.load(tmplfile)
    f.write tmpl.result(binding)
  end
end

#call_hook(hook_name, *params) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
# File 'lib/review/epubmaker.rb', line 134

def call_hook(hook_name, *params)
  filename = @params["epubmaker"][hook_name]
  log("Call #{hook_name}. (#{filename})")
  if filename.present? && File.exist?(filename) && FileTest.executable?(filename)
    if ENV["REVIEW_SAFE_MODE"].to_i & 1 > 0
      warn "hook is prohibited in safe mode. ignored."
    else
      system(filename, *params)
    end
  end
end

#check_compile_statusObject



215
216
217
218
219
220
# File 'lib/review/epubmaker.rb', line 215

def check_compile_status
  return unless @compile_errors

  $stderr.puts "compile error, No EPUB file output."
  exit 1
end

#copy_backmatter(basetmpdir) ⇒ Object



460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'lib/review/epubmaker.rb', line 460

def copy_backmatter(basetmpdir)
  if @params["profile"]
    FileUtils.cp(@params["profile"], "#{basetmpdir}/#{File.basename(@params["profile"])}")
    @htmltoc.add_item(1, File.basename(@params["profile"]), @producer.res.v("profiletitle"), {:chaptype => "post"})
  end

  if @params["advfile"]
    FileUtils.cp(@params["advfile"], "#{basetmpdir}/#{File.basename(@params["advfile"])}")
    @htmltoc.add_item(1, File.basename(@params["advfile"]), @producer.res.v("advtitle"), {:chaptype => "post"})
  end

  if @params["colophon"]
    if @params["colophon"].kind_of?(String) # FIXME:このやり方はやめる?
      FileUtils.cp(@params["colophon"], "#{basetmpdir}/colophon.#{@params["htmlext"]}")
    else
      File.open("#{basetmpdir}/colophon.#{@params["htmlext"]}", "w") {|f| @producer.colophon(f) }
    end
    @htmltoc.add_item(1, "colophon.#{@params["htmlext"]}", @producer.res.v("colophontitle"), {:chaptype => "post"})
  end

  if @params["backcover"]
    FileUtils.cp(@params["backcover"], "#{basetmpdir}/#{File.basename(@params["backcover"])}")
    @htmltoc.add_item(1, File.basename(@params["backcover"]), @producer.res.v("backcovertitle"), {:chaptype => "post"})
  end
end

#copy_frontmatter(basetmpdir) ⇒ Object



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/review/epubmaker.rb', line 414

def copy_frontmatter(basetmpdir)
  FileUtils.cp(@params["cover"], "#{basetmpdir}/#{File.basename(@params["cover"])}") if @params["cover"].present? && File.exist?(@params["cover"])

  if @params["titlepage"]
    if @params["titlefile"].nil?
      build_titlepage(basetmpdir, "titlepage.#{@params["htmlext"]}")
    else
      FileUtils.cp(@params["titlefile"], "#{basetmpdir}/titlepage.#{@params["htmlext"]}")
    end
    @htmltoc.add_item(1, "titlepage.#{@params['htmlext']}", @producer.res.v("titlepagetitle"), {:chaptype => "pre"})
  end

  if @params["originaltitlefile"].present? && File.exist?(@params["originaltitlefile"])
    FileUtils.cp(@params["originaltitlefile"], "#{basetmpdir}/#{File.basename(@params["originaltitlefile"])}")
    @htmltoc.add_item(1, File.basename(@params["originaltitlefile"]), @producer.res.v("originaltitle"), {:chaptype => "pre"})
  end

  if @params["creditfile"].present? && File.exist?(@params["creditfile"])
    FileUtils.cp(@params["creditfile"], "#{basetmpdir}/#{File.basename(@params["creditfile"])}")
    @htmltoc.add_item(1, File.basename(@params["creditfile"]), @producer.res.v("credittitle"), {:chaptype => "pre"})
  end
end

#copy_images(resdir, destdir, allow_exts = nil) ⇒ Object



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/review/epubmaker.rb', line 171

def copy_images(resdir, destdir, allow_exts=nil)
  return nil unless File.exist?(resdir)
  allow_exts = @params["image_ext"] if allow_exts.nil?
  FileUtils.mkdir_p(destdir)
  if @params["epubmaker"]["verify_target_images"].present?
    @params["epubmaker"]["force_include_images"].each do |file|
      unless File.exist?(file)
        warn "#{file} is not found, skip." if file !~ /\Ahttp[s]?:/
        next
      end
      basedir = File.dirname(file)
      FileUtils.mkdir_p("#{destdir}/#{basedir}")
      log("Copy #{file} to the temporary directory.")
      FileUtils.cp(file, "#{destdir}/#{basedir}")
    end
  else
    recursive_copy_files(resdir, destdir, allow_exts)
  end
end

#copy_resources(resdir, destdir, allow_exts = nil) ⇒ Object



191
192
193
194
195
196
# File 'lib/review/epubmaker.rb', line 191

def copy_resources(resdir, destdir, allow_exts=nil)
  return nil unless File.exist?(resdir)
  allow_exts = @params["image_ext"] if allow_exts.nil?
  FileUtils.mkdir_p(destdir)
  recursive_copy_files(resdir, destdir, allow_exts)
end

#copy_stylesheet(basetmpdir) ⇒ Object



405
406
407
408
409
410
411
412
# File 'lib/review/epubmaker.rb', line 405

def copy_stylesheet(basetmpdir)
  if @params["stylesheet"].size > 0
    @params["stylesheet"].each do |sfile|
      FileUtils.cp(sfile, basetmpdir)
      @producer.contents.push(Content.new("file" => sfile))
    end
  end
end

#detect_properties(path) ⇒ Object



351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/review/epubmaker.rb', line 351

def detect_properties(path)
  properties = []
  File.open(path) do |f|
    doc = REXML::Document.new(f)
    if REXML::XPath.first(doc, "//m:math", {'m' => 'http://www.w3.org/1998/Math/MathML'})
      properties<< "mathml"
    end
    if REXML::XPath.first(doc, "//s:svg", {'s' => 'http://www.w3.org/2000/svg'})
      properties<< "svg"
    end
  end
  properties
end

#load_yaml(yamlfile) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/review/epubmaker.rb', line 43

def load_yaml(yamlfile)
  loader = ReVIEW::YAMLLoader.new
  @params = ReVIEW::Configure.values.deep_merge(loader.load_file(yamlfile))
  @producer = Producer.new(@params)
  @producer.load(yamlfile)
  @params = @producer.params
  @params.maker = "epubmaker"
end

#log(s) ⇒ Object



39
40
41
# File 'lib/review/epubmaker.rb', line 39

def log(s)
  puts s if @params["debug"].present?
end

#produce(yamlfile, bookname = nil) ⇒ Object



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
# File 'lib/review/epubmaker.rb', line 65

def produce(yamlfile, bookname=nil)
  load_yaml(yamlfile)
  I18n.setup(@params["language"])
  bookname = @params["bookname"] if bookname.nil?
  booktmpname = "#{bookname}-epub"

  begin
    @params.check_version(ReVIEW::VERSION)
  rescue ReVIEW::ConfigError => e
    warn e.message
  end
  log("Loaded yaml file (#{yamlfile}). I will produce #{bookname}.epub.")

  FileUtils.rm_f("#{bookname}.epub")
  FileUtils.rm_rf(booktmpname) if @params["debug"]

  basetmpdir = build_path()
  begin
    log("Created first temporary directory as #{basetmpdir}.")

    call_hook("hook_beforeprocess", basetmpdir)

    @htmltoc = ReVIEW::HTMLToc.new(basetmpdir)
    ## copy all files into basetmpdir
    copy_stylesheet(basetmpdir)

    copy_frontmatter(basetmpdir)
    call_hook("hook_afterfrontmatter", basetmpdir)

    build_body(basetmpdir, yamlfile)
    call_hook("hook_afterbody", basetmpdir)

    copy_backmatter(basetmpdir)
    call_hook("hook_afterbackmatter", basetmpdir)

    ## push contents in basetmpdir into @producer
    push_contents(basetmpdir)

    if @params["epubmaker"]["verify_target_images"].present?
      verify_target_images(basetmpdir)
      copy_images(@params["imagedir"], basetmpdir)
    else
      copy_images(@params["imagedir"], "#{basetmpdir}/images")
    end

    copy_resources("covers", "#{basetmpdir}/images")
    copy_resources("adv", "#{basetmpdir}/images")
    copy_resources(@params["fontdir"], "#{basetmpdir}/fonts", @params["font_ext"])

    call_hook("hook_aftercopyimage", basetmpdir)

    @producer.import_imageinfo("#{basetmpdir}/images", basetmpdir)
    @producer.import_imageinfo("#{basetmpdir}/fonts", basetmpdir, @params["font_ext"])

    epubtmpdir = nil
    if @params["debug"].present?
      epubtmpdir = "#{basetmpdir}/#{booktmpname}"
      Dir.mkdir(epubtmpdir)
    end
    log("Call ePUB producer.")
    @producer.produce("#{bookname}.epub", basetmpdir, epubtmpdir)
    log("Finished.")
  ensure
    unless @params["debug"]
      FileUtils.remove_entry_secure basetmpdir
    end
  end
end

#push_contents(basetmpdir) ⇒ Object



386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/review/epubmaker.rb', line 386

def push_contents(basetmpdir)
  @htmltoc.each_item do |level, file, title, args|
    next if level.to_i > @params["toclevel"] && args[:force_include].nil?
    log("Push #{file} to ePUB contents.")

    hash = {"file" => file, "level" => level.to_i, "title" => title, "chaptype" => args[:chaptype]}
    if args[:id].present?
      hash["id"] = args[:id]
    end
    if args[:properties].present?
      hash["properties"] = args[:properties].split(" ")
    end
    if args[:notoc].present?
      hash["notoc"] = args[:notoc]
    end
    @producer.contents.push(Content.new(hash))
  end
end

#recursive_copy_files(resdir, destdir, allow_exts) ⇒ Object



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/review/epubmaker.rb', line 198

def recursive_copy_files(resdir, destdir, allow_exts)
  Dir.open(resdir) do |dir|
    dir.each do |fname|
      next if fname.start_with?('.')
      if FileTest.directory?("#{resdir}/#{fname}")
        recursive_copy_files("#{resdir}/#{fname}", "#{destdir}/#{fname}", allow_exts)
      else
        if fname =~ /\.(#{allow_exts.join("|")})\Z/i
          FileUtils.mkdir_p(destdir)
          log("Copy #{resdir}/#{fname} to the temporary directory.")
          FileUtils.cp("#{resdir}/#{fname}", destdir)
        end
      end
    end
  end
end

#remove_hidden_title(basetmpdir, htmlfile) ⇒ Object



340
341
342
343
344
345
346
347
348
349
# File 'lib/review/epubmaker.rb', line 340

def remove_hidden_title(basetmpdir, htmlfile)
  File.open("#{basetmpdir}/#{htmlfile}", "r+") do |f|
    body = f.read.
           gsub(/<h\d .*?hidden=['"]true['"].*?>.*?<\/h\d>\n/, '').
           gsub(/(<h\d .*?)\s*notoc=['"]true['"]\s*(.*?>.*?<\/h\d>\n)/, '\1\2')
    f.rewind
    f.print body
    f.truncate(f.tell)
  end
end

#template_nameObject



279
280
281
282
283
284
285
# File 'lib/review/epubmaker.rb', line 279

def template_name
  if @producer.params["htmlversion"].to_i == 5
    './html/layout-html5.html.erb'
  else
    './html/layout-xhtml1.html.erb'
  end
end

#verify_target_images(basetmpdir) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/review/epubmaker.rb', line 146

def verify_target_images(basetmpdir)
  @producer.contents.each do |content|
    if content.media == "application/xhtml+xml"

      File.open("#{basetmpdir}/#{content.file}") do |f|
        Document.new(File.new(f)).each_element("//img") do |e|
          @params["epubmaker"]["force_include_images"].push(e.attributes["src"])
          if e.attributes["src"] =~ /svg\Z/i
            content.properties.push("svg")
          end
        end
      end
    elsif content.media == "text/css"
      File.open("#{basetmpdir}/#{content.file}") do |f|
        f.each_line do |l|
          l.scan(/url\((.+?)\)/) do |m|
            @params["epubmaker"]["force_include_images"].push($1.strip)
          end
        end
      end
    end
  end
  @params["epubmaker"]["force_include_images"] = @params["epubmaker"]["force_include_images"].sort.uniq
end

#write_buildlogtxt(basetmpdir, htmlfile, reviewfile) ⇒ Object



486
487
488
489
490
# File 'lib/review/epubmaker.rb', line 486

def write_buildlogtxt(basetmpdir, htmlfile, reviewfile)
  File.open("#{basetmpdir}/#{@buildlogtxt}", "a") do |f|
    f.puts "#{htmlfile},#{reviewfile}"
  end
end

#write_info_body(basetmpdir, id, filename, ispart = nil, chaptype = nil) ⇒ Object



365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/review/epubmaker.rb', line 365

def write_info_body(basetmpdir, id, filename, ispart=nil, chaptype=nil)
  headlines = []
  path = File.join(basetmpdir, filename)
  Document.parse_stream(File.new(path), ReVIEWHeaderListener.new(headlines))
  properties = detect_properties(path)
  prop_str = ""
  if properties.present?
    prop_str = ",properties="+properties.join(" ")
  end
  first = true
  headlines.each do |headline|
    headline["level"] = 0 if ispart.present? && headline["level"] == 1
    if first.nil?
      @htmltoc.add_item(headline["level"], filename+"#"+headline["id"], headline["title"], {:chaptype => chaptype, :notoc => headline["notoc"]})
    else
      @htmltoc.add_item(headline["level"], filename, headline["title"], {:force_include => true, :chaptype => chaptype+prop_str, :notoc => headline["notoc"]})
      first = nil
    end
  end
end