Class: ReVIEW::PDFMaker

Inherits:
Object show all
Includes:
FileUtils, LaTeXUtils
Defined in:
lib/review/pdfmaker.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from LaTeXUtils

#escape_index, #escape_latex, #escape_url, #initialize_metachars, #macro, #unescape_latex

Constructor Details

#initializePDFMaker

Returns a new instance of PDFMaker.



35
36
37
38
# File 'lib/review/pdfmaker.rb', line 35

def initialize
  @basedir = nil
  @input_files = Hash.new{|h, key| h[key] = ""}
end

Instance Attribute Details

#basedirObject

Returns the value of attribute basedir.



33
34
35
# File 'lib/review/pdfmaker.rb', line 33

def basedir
  @basedir
end

#configObject

Returns the value of attribute config.



33
34
35
# File 'lib/review/pdfmaker.rb', line 33

def config
  @config
end

Class Method Details

.execute(*args) ⇒ Object



84
85
86
# File 'lib/review/pdfmaker.rb', line 84

def self.execute(*args)
  self.new.execute(*args)
end

Instance Method Details

#build_pathObject



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/review/pdfmaker.rb', line 61

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

#call_hook(hookname) ⇒ Object



379
380
381
382
383
384
385
386
387
388
# File 'lib/review/pdfmaker.rb', line 379

def call_hook(hookname)
  if @config["pdfmaker"].instance_of?(Hash) && @config["pdfmaker"][hookname]
    hook = File.absolute_path(@config["pdfmaker"][hookname], @basedir)
    if ENV["REVIEW_SAFE_MODE"].to_i & 1 > 0
      warn "hook configuration is prohibited in safe mode. ignored."
    else
      system_or_raise("#{hook} #{Dir.pwd} #{@basedir}")
    end
  end
end

#check_compile_status(ignore_errors) ⇒ Object



74
75
76
77
78
79
80
81
82
# File 'lib/review/pdfmaker.rb', line 74

def check_compile_status(ignore_errors)
  return unless @compile_errors

  if ignore_errors
    $stderr.puts "compile error, but try to generate PDF file"
  else
    error "compile error, No PDF file output."
  end
end

#copy_images(from, to) ⇒ Object

PDFMaker#copy_images should copy image files AND execute extractbb (or ebb).



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/review/pdfmaker.rb', line 223

def copy_images(from, to)
  if File.exist?(from)
    Dir.mkdir(to)
    ReVIEW::MakerHelper.copy_images_to_dir(from, to)
    Dir.chdir(to) do
      images = Dir.glob("**/*").find_all{|f|
        File.file?(f) and f =~ /\.(jpg|jpeg|png|pdf)\z/
      }
      break if images.empty?
      system("extractbb", *images)
      unless system("extractbb", "-m", *images)
        system_or_raise("ebb", *images)
      end
    end
  end
end

#copyStyToDir(dirname, copybase, extname = "sty") ⇒ Object



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/review/pdfmaker.rb', line 363

def copyStyToDir(dirname, copybase, extname = "sty")
  unless File.directory?(dirname)
    warn "No such directory - #{dirname}"
    return
  end

  Dir.open(dirname) do |dir|
    dir.each do |fname|
      if File.extname(fname).downcase == "."+extname
        FileUtils.mkdir_p(copybase)
        FileUtils.cp File.join(dirname, fname), copybase
      end
    end
  end
end

#date_to_s(date) ⇒ Object



315
316
317
318
319
# File 'lib/review/pdfmaker.rb', line 315

def date_to_s(date)
  require 'date'
  d = Date.parse(date)
  d.strftime(ReVIEW::I18n.t("date_format"))
end

#error(msg) ⇒ Object



44
45
46
47
# File 'lib/review/pdfmaker.rb', line 44

def error(msg)
  $stderr.puts "#{File.basename($0, '.*')}: error: #{msg}"
  exit 1
end

#execute(*args) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/review/pdfmaker.rb', line 114

def execute(*args)
  @config = ReVIEW::Configure.values
  @config.maker = "pdfmaker"
  cmd_config, yamlfile = parse_opts(args)
  loader = ReVIEW::YAMLLoader.new
  @config.deep_merge!(loader.load_file(yamlfile))
  # YAML configs will be overridden by command line options.
  @config.merge!(cmd_config)
  I18n.setup(@config["language"])
  @basedir = File.dirname(yamlfile)

  begin
    @config.check_version(ReVIEW::VERSION)
  rescue ReVIEW::ConfigError => e
    warn e.message
  end
  generate_pdf(yamlfile)
end

#generate_pdf(yamlfile) ⇒ Object



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

def generate_pdf(yamlfile)
  remove_old_file
  @path = build_path()
  begin
    @compile_errors = nil

    book = ReVIEW::Book.load(@basedir)
    book.config = @config
    @converter = ReVIEW::Converter.new(book, ReVIEW::LATEXBuilder.new)
    book.parts.each do |part|
      if part.name.present?
        if part.file?
          output_chaps(part.name, yamlfile)
          @input_files["CHAPS"] << %Q|\\input{#{part.name}.tex}\n|
        else
          @input_files["CHAPS"] << %Q|\\part{#{part.name}}\n|
        end
      end

      part.chapters.each do |chap|
        filename = File.basename(chap.path, ".*")
        output_chaps(filename, yamlfile)
        @input_files["PREDEF"] << "\\input{#{filename}.tex}\n" if chap.on_PREDEF?
        @input_files["CHAPS"] << "\\input{#{filename}.tex}\n" if chap.on_CHAPS?
        @input_files["APPENDIX"] << "\\input{#{filename}.tex}\n" if chap.on_APPENDIX?
        @input_files["POSTDEF"] << "\\input{#{filename}.tex}\n" if chap.on_POSTDEF?
      end
    end

    check_compile_status(@config["ignore-errors"])

    @config["usepackage"] = ""
    if @config["texstyle"]
      @config["usepackage"] = "\\usepackage{#{@config['texstyle']}}"
    end

    copy_images("./images", File.join(@path, "images"))
    copyStyToDir(File.join(Dir.pwd, "sty"), @path)
    copyStyToDir(File.join(Dir.pwd, "sty"), @path, "fd")
    copyStyToDir(File.join(Dir.pwd, "sty"), @path, "cls")
    copyStyToDir(Dir.pwd, @path, "tex")

    template = get_template
    Dir.chdir(@path) do
      File.open("./book.tex", "wb"){|f| f.write(template)}

      call_hook("hook_beforetexcompile")

      ## do compile
      if ENV["REVIEW_SAFE_MODE"].to_i & 4 > 0
        warn "command configuration is prohibited in safe mode. ignored."
      else
        texcommand = @config["texcommand"] if @config["texcommand"]
        dvicommand = @config["dvicommand"] if @config["dvicommand"]
        dvioptions = @config["dvioptions"] if @config["dvioptions"]
        texoptions = @config["texoptions"] if @config["texoptions"]
      end
      3.times do
        system_or_raise("#{texcommand} #{texoptions} book.tex")
      end
      call_hook("hook_aftertexcompile")

      if File.exist?("book.dvi")
        system_or_raise("#{dvicommand} #{dvioptions} book.dvi")
      end
    end
    call_hook("hook_afterdvipdf")

    FileUtils.cp(File.join(@path, "book.pdf"), pdf_filepath)

  ensure
    unless @config["debug"]
      remove_entry_secure @path
    end
  end
end

#get_templateObject



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

def get_template
  dclass = @config["texdocumentclass"] || []
  @documentclass = dclass[0] || "jsbook"
  @documentclassoption = dclass[1] || "uplatex,oneside"

  @okuduke = make_colophon
  @authors = make_authors

  @custom_titlepage = make_custom_page(@config["cover"]) || make_custom_page(@config["coverfile"])
  @custom_originaltitlepage = make_custom_page(@config["originaltitlefile"])
  @custom_creditpage = make_custom_page(@config["creditfile"])

  @custom_profilepage = make_custom_page(@config["profile"])
  @custom_advfilepage = make_custom_page(@config["advfile"])
  if @config["colophon"] && @config["colophon"].kind_of?(String)
    @custom_colophonpage = make_custom_page(@config["colophon"])
  end
  @custom_backcoverpage = make_custom_page(@config["backcover"])

  if @config["pubhistory"]
    warn "pubhistory is oboleted. use history."
  else
    @config["pubhistory"] = make_history_list.join("\n")
  end
  if @documentclass == "ubook" || @documentclass == "utbook"
    @coverimageoption = "width=\\textheight,height=\\textwidth,keepaspectratio,angle=90"
  else
    @coverimageoption = "width=\\textwidth,height=\\textheight,keepaspectratio"
  end

  template = File.expand_path('./latex/layout.tex.erb', ReVIEW::Template::TEMPLATE_DIR)
  layout_file = File.join(@basedir, "layouts", "layout.tex.erb")
  if File.exist?(layout_file)
    template = layout_file
  end

  @texcompiler = File.basename(@config["texcommand"], ".*")

  erb = ReVIEW::Template.load(template, '-')
  erb.result(binding)
end

#join_with_separator(value, sep) ⇒ Object



249
250
251
252
253
254
255
# File 'lib/review/pdfmaker.rb', line 249

def join_with_separator(value, sep)
  if value.kind_of? Array
    value.join(sep)
  else
    value
  end
end

#make_authorsObject



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/review/pdfmaker.rb', line 274

def make_authors
  authors = ""
  if @config["aut"].present?
    author_names = join_with_separator(@config.names_of("aut"), ReVIEW::I18n.t("names_splitter"))
    authors = ReVIEW::I18n.t("author_with_label", author_names)
  end
  if @config["csl"].present?
    csl_names = join_with_separator(@config.names_of("csl"), ReVIEW::I18n.t("names_splitter"))
    authors += " \\\\\n"+ ReVIEW::I18n.t("supervisor_with_label", csl_names)
  end
  if @config["trl"].present?
    trl_names = join_with_separator(@config.names_of("trl"), ReVIEW::I18n.t("names_splitter"))
    authors += " \\\\\n"+ ReVIEW::I18n.t("translator_with_label", trl_names)
  end
  authors
end

#make_colophonObject



266
267
268
269
270
271
272
# File 'lib/review/pdfmaker.rb', line 266

def make_colophon
  colophon = ""
  @config["colophon_order"].each do |role|
    colophon += make_colophon_role(role)
  end
  colophon
end

#make_colophon_role(role) ⇒ Object



257
258
259
260
261
262
263
264
# File 'lib/review/pdfmaker.rb', line 257

def make_colophon_role(role)
  if @config[role].present?
    initialize_metachars(@config["texcommand"])
    return "#{ReVIEW::I18n.t(role)} & #{escape_latex(join_with_separator(@config.names_of(role), ReVIEW::I18n.t("names_splitter")))} \\\\\n"
  else
    ""
  end
end

#make_custom_page(file) ⇒ Object



240
241
242
243
244
245
246
247
# File 'lib/review/pdfmaker.rb', line 240

def make_custom_page(file)
  file_sty = file.to_s.sub(/\.[^.]+$/, ".tex")
  if File.exist?(file_sty)
    File.read(file_sty)
  else
    nil
  end
end

#make_history_listObject



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/review/pdfmaker.rb', line 291

def make_history_list
  buf = []
  if @config["history"]
    @config["history"].each_with_index do |items, edit|
      items.each_with_index do |item, rev|
        editstr = (edit == 0) ? ReVIEW::I18n.t("first_edition") : ReVIEW::I18n.t("nth_edition","#{edit+1}")
        revstr = ReVIEW::I18n.t("nth_impression", "#{rev+1}")
        if item =~ /\A\d+\-\d+\-\d+\Z/
          buf << ReVIEW::I18n.t("published_by1", [date_to_s(item), editstr+revstr])
        else
          # custom date with string
          item.match(/\A(\d+\-\d+\-\d+)[\s ](.+)/) do |m|
            buf << ReVIEW::I18n.t("published_by3", [date_to_s(m[1]), m[2]])
          end
        end
      end
    end
  elsif @config["date"]
    buf << ReVIEW::I18n.t("published_by2",
                          date_to_s(@config["date"]))
  end
  buf
end

#output_chaps(filename, yamlfile) ⇒ Object



210
211
212
213
214
215
216
217
218
219
# File 'lib/review/pdfmaker.rb', line 210

def output_chaps(filename, yamlfile)
  $stderr.puts "compiling #{filename}.tex"
  begin
    @converter.convert(filename+".re", File.join(@path, filename+".tex"))
  rescue => e
    @compile_errors = true
    warn "compile error in #{filename}.tex (#{e.class})"
    warn e.message
  end
end

#parse_opts(args) ⇒ Object



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

def parse_opts(args)
  cmd_config = Hash.new
  opts = OptionParser.new

  opts.banner = "Usage: review-pdfmaker configfile"
  opts.version = ReVIEW::VERSION
  opts.on('--help', 'Prints this message and quit.') do
    puts opts.help
    exit 0
  end
  opts.on('--[no-]debug', 'Keep temporary files.') do |debug|
    cmd_config["debug"] = debug
  end
  opts.on('--ignore-errors', 'Ignore review-compile errors.') do
    cmd_config["ignore-errors"] = true
  end

  opts.parse!(args)
  if args.size != 1
    puts opts.help
    exit 0
  end

  return cmd_config, args[0]
end

#pdf_filepathObject



53
54
55
# File 'lib/review/pdfmaker.rb', line 53

def pdf_filepath
  File.join(@basedir, @config["bookname"]+".pdf")
end

#remove_old_fileObject



57
58
59
# File 'lib/review/pdfmaker.rb', line 57

def remove_old_file
  FileUtils.rm_f(pdf_filepath)
end

#system_or_raise(*args) ⇒ Object



40
41
42
# File 'lib/review/pdfmaker.rb', line 40

def system_or_raise(*args)
  Kernel.system(*args) or raise("failed to run command: #{args.join(' ')}")
end

#warn(msg) ⇒ Object



49
50
51
# File 'lib/review/pdfmaker.rb', line 49

def warn(msg)
  $stderr.puts "#{File.basename($0, '.*')}: warning: #{msg}"
end