class Redwood::Chunk::Attachment
  def view!
    HookManager.run "mime-decode", :content_type => @content_type,
                    :filename => lambda { write_to_disk },
                    :sibling_types => :explicit_view # hijack!
  end
end

def run(command)
  system "#{command} 2>/dev/null >/dev/null"
  $? == 0 ? "" : nil
end

def quicklook(filename, type)
  uti = `mime2uti #{type}`.chomp
  run "qlmanage -c #{uti} -p #{filename}"
  true # so ^C to quit qlmanage doesn't look like a failure
end

if sibling_types == :explicit_view
  case content_type
  when "text/html"
    run "view_attachment #{filename} html"
  when %r{^text/}
    false # show with internal viewer
  when %r{^image/}, "application/pdf"
    quicklook filename, content_type
  else
    run "view_attachment #{filename}"
  end
elsif !sibling_types.member? "text/plain"
  case content_type
  when "text/html"
    `/opt/local/bin/w3m -dump -T #{content_type} '#{filename}'`
  end
end
