Class: Pirka::App::Highlight

Inherits:
Object
  • Object
show all
Includes:
Subcommand
Defined in:
app/highlight.rb

Constant Summary collapse

PROGRAM_NAME =
"highlight"
DESCRIPTION =
_("Highlights source code in EPUB file")
ARGS =
%w[EPUB_FILE]
DUMMY_ORIGIN =
Addressable::URI.parse("file:///")
CSS_PATH =
"pirka/style.css"
CSS_CLASS_NAME =
"pirka"
SCOPE =
".#{CSS_CLASS_NAME}"
THEME =
"github"

Instance Method Summary collapse

Methods included from Subcommand

included

Constructor Details

#initialize(config) ⇒ Highlight

Returns a new instance of Highlight.



26
27
28
29
# File 'app/highlight.rb', line 26

def initialize(config)
  super
  @library_path = nil
end

Instance Method Details

#add_css_file(epub) ⇒ EPUB::Publication::Package::Manifest::Item

Returns item indicating added CSS file.

Parameters:

  • epub (EPUB::Book, EPUB::Book::Features)

Returns:

  • (EPUB::Publication::Package::Manifest::Item)

    item indicating added CSS file



51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/highlight.rb', line 51

def add_css_file(epub)
  rootfile_path = DUMMY_ORIGIN + epub.ocf.container.rootfile.full_path
  style = Rouge::Theme.find(THEME).new(scope: SCOPE).render

  epub.package.manifest.make_item {|item|
    item.href = (DUMMY_ORIGIN + CSS_PATH).route_from(rootfile_path)
    # IMPROVEMENT: Want to call item.entry_name = css_path
    item.media_type = 'text/css'
    item.id = CSS_PATH.gsub('/', '-') # @todo Avoid conflict with existing items
    item.content = style
  }
end


157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'app/highlight.rb', line 157

def embed_stylesheet_link(doc, item, css_item)
  link = doc.at('#pirka') # @todo Avoid conflict with existing link
  unless link
    item_entry_name = DUMMY_ORIGIN + item.entry_name
    entry_name = DUMMY_ORIGIN + css_item.entry_name
    href = entry_name.route_from(item_entry_name)
    link = Nokogiri::XML::Node.new('link', doc)
    link['href'] = href
    link['type'] = 'text/css'
    link['rel'] = 'stylesheet'
    link['id'] = 'pirka'
    head = (doc/'head').first
    head << link
  end
end

#find_library(epub) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'app/highlight.rb', line 76

def find_library(epub)
  library = @library_path ? Library.load_file(@library_path) :
    Library.find_by_release_identifier(epub.release_identifier)
  unless library
    message_template = _("Cannot find code list %{library_file} for %{release_identifier}(%{epub_file}) in any directory of:\n%{search_dirs}")
                         .encode(__ENCODING__) # Needed for Windows non-ascii environment such as code page 932 a.k.a Windiws-31J a Shift_JIS variant encoding
    message = message_template % {
      library_file: Library.filename(epub.release_identifier),
      release_identifier: epub.release_identifier,
      epub_file: epub.epub_file,
      search_dirs: Library.directories.collect {|path| "- #{path}"}.join("\n")
    }
    raise RuntimeError, message
  end
  library
end

#highlight_contents(epub, css_item, library) ⇒ Object



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
# File 'app/highlight.rb', line 94

def highlight_contents(epub, css_item, library)
  need_save = []

  highlighter = Highlighter::Middleware::ClassName.new(
    Highlighter::Middleware::Rouge.new(
      Highlighter.new),
    class_name: CSS_CLASS_NAME)
  middleware = library.["middleware"]
  if middleware && !middleware.empty?
    highlighter = middleware.reduce(highlighter) {|highlighter, desc|
      params = desc["params"] || {}
      Highlighter::Middleware.const_get(desc["name"]).new(highlighter, params)
    }
  end

  library.reverse_each do |(cfi, data)|
    lang = data["language"]
    unless lang
      warn _("Language for %{cfi} is not detected") % {cfi: cfi}
      next
    end
    itemref, elem, _ = EPUB::Searcher.search_by_cfi(epub, cfi)
    item = itemref.item
    doc = elem.document

    if data["middleware"] && !data["middleware"].empty?
      additional_highlighter = data["middleware"].reduce(highlighter) {|highlighter, desc|
        params = desc["params"] || {}
        Highlighter::Middleware.const_get(desc["name"]).new(highlighter, params)
      }
      additional_highlighter.markup elem, lang
    else
      highlighter.markup elem, lang
    end

    embed_stylesheet_link doc, item, css_item
    item.content = doc.to_xml
    need_save << item
  end

  need_save
end

#prepare_epub(path) ⇒ Object

TODO:

Make this optional

Raises:

  • (ArgumentError)


65
66
67
68
69
70
71
72
73
# File 'app/highlight.rb', line 65

def prepare_epub(path)
  raise ArgumentError, _('Specify EPUB file') unless path
  begin
    require 'epub/maker/ocf/physical_container/zipruby'
    EPUB::OCF::PhysicalContainer.adapter = :Zipruby
  rescue LoadError
  end
  EPUB::Parser.parse(path)
end

#run(argv) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'app/highlight.rb', line 32

def run(argv)
  parse_options! argv

  epub_path = argv.shift
  epub = prepare_epub(epub_path)

  library = find_library(epub)

  css_item = add_css_file(epub)
  need_save = highlight_contents(epub, css_item, library)
  need_save << css_item
  need_save.uniq!
  update_modified_date(epub, Time.now)

  save_file epub, need_save
end

#save_file(epub, need_save) ⇒ Object



149
150
151
152
153
154
155
# File 'app/highlight.rb', line 149

def save_file(epub, need_save)
  need_save.each do |item|
    item.save
    epub.package.manifest << item
  end
  epub.package.edit
end

#update_modified_date(epub, time = Time.now) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
# File 'app/highlight.rb', line 137

def update_modified_date(epub, time = Time.now)
  modified = epub.modified
  unless modified
    modified = EPUB::Publication::Package::Metadata::Meta.new
    modified.property = 'dcterms:modified'
    epub.package..metas << modified
  end
  modified.content = time.utc.iso8601

  modified
end