1/**
2 * Copyright (C) 2013 Google Inc.
3 * Licensed to The Android Open Source Project.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.mail.print;
19
20import android.annotation.SuppressLint;
21import android.content.Context;
22import android.content.res.Resources;
23import android.print.PrintAttributes;
24import android.print.PrintManager;
25import android.text.TextUtils;
26import android.webkit.WebSettings;
27import android.webkit.WebView;
28
29import com.android.emailcommon.mail.Address;
30import com.android.mail.FormattedDateBuilder;
31import com.android.mail.R;
32import com.android.mail.browse.MessageCursor;
33
34import com.android.mail.providers.Attachment;
35import com.android.mail.providers.Conversation;
36import com.android.mail.providers.Message;
37import com.android.mail.providers.UIProvider;
38import com.android.mail.utils.AttachmentUtils;
39import com.android.mail.utils.Utils;
40
41import java.util.List;
42import java.util.Map;
43
44/**
45 * Utility class that provides utility functions to print
46 * either a conversation or message.
47 */
48public class PrintUtils {
49    private static final String DIV_START = "<div>";
50    private static final String REPLY_TO_DIV_START = "<div class=\"replyto\">";
51    private static final String DIV_END = "</div>";
52
53    /**
54     * Prints an entire conversation.
55     */
56    public static void printConversation(Context context,
57            MessageCursor cursor, Map<String, Address> addressCache,
58            String baseUri, boolean useJavascript) {
59        if (cursor == null) {
60            return;
61        }
62        final String convHtml = buildConversationHtml(context, cursor,
63                        addressCache, useJavascript);
64        printHtml(context, convHtml, baseUri, cursor.getConversation().subject, useJavascript);
65    }
66
67    /**
68     * Prints one message.
69     */
70    public static void printMessage(Context context, Message message, String subject,
71            Map<String, Address> addressCache, String baseUri, boolean useJavascript) {
72        final String msgHtml = buildMessageHtml(context, message,
73                subject, addressCache, useJavascript);
74        printHtml(context, msgHtml, baseUri, subject, useJavascript);
75    }
76
77    public static String buildPrintJobName(Context context, String name) {
78        return TextUtils.isEmpty(name)
79                ? context.getString(R.string.app_name)
80                : context.getString(R.string.print_job_name, name);
81    }
82
83    /**
84     * Prints the html provided using the framework printing APIs.
85     *
86     * Sets up a webview to perform the printing work.
87     */
88    @SuppressLint("NewApi")
89    private static void printHtml(Context context, String html,
90            String baseUri, String subject, boolean useJavascript) {
91        final WebView webView = new WebView(context);
92        final WebSettings settings = webView.getSettings();
93        settings.setBlockNetworkImage(false);
94        settings.setJavaScriptEnabled(useJavascript);
95        webView.loadDataWithBaseURL(baseUri, html,
96                "text/html", "utf-8", null);
97        final PrintManager printManager =
98                (PrintManager) context.getSystemService(Context.PRINT_SERVICE);
99
100        final String printJobName = buildPrintJobName(context, subject);
101        printManager.print(printJobName,
102                webView.createPrintDocumentAdapter(),
103                new PrintAttributes.Builder().build());
104    }
105
106    /**
107     * Builds an html document that is suitable for printing and returns it as a {@link String}.
108     */
109    private static String buildConversationHtml(Context context,
110            MessageCursor cursor, Map<String, Address> addressCache, boolean useJavascript) {
111        final HtmlPrintTemplates templates = new HtmlPrintTemplates(context);
112        final FormattedDateBuilder dateBuilder = new FormattedDateBuilder(context);
113
114        if (!cursor.moveToFirst()) {
115            throw new IllegalStateException("trying to print without a conversation");
116        }
117
118        final Conversation conversation = cursor.getConversation();
119        templates.startPrintConversation(conversation.subject, conversation.getNumMessages());
120
121        // for each message in the conversation, add message html
122        final Resources res = context.getResources();
123        do {
124            final Message message = cursor.getMessage();
125            appendSingleMessageHtml(context, res, message, addressCache, templates, dateBuilder);
126        } while (cursor.moveToNext());
127
128        // only include JavaScript if specifically requested
129        return useJavascript ?
130                templates.endPrintConversation() : templates.endPrintConversationNoJavascript();
131    }
132
133    /**
134     * Builds an html document suitable for printing and returns it as a {@link String}.
135     */
136    private static String buildMessageHtml(Context context, Message message,
137            String subject, Map<String, Address> addressCache, boolean useJavascript) {
138        final HtmlPrintTemplates templates = new HtmlPrintTemplates(context);
139        final FormattedDateBuilder dateBuilder = new FormattedDateBuilder(context);
140
141        templates.startPrintConversation(subject, 1 /* numMessages */);
142
143        // add message html
144        final Resources res = context.getResources();
145        appendSingleMessageHtml(context, res, message, addressCache, templates, dateBuilder);
146
147        // only include JavaScript if specifically requested
148        return useJavascript ?
149                templates.endPrintConversation() : templates.endPrintConversationNoJavascript();
150    }
151
152    /**
153     * Adds the html for a single message to the
154     * {@link HtmlPrintTemplates} provided.
155     */
156    private static void appendSingleMessageHtml(Context context, Resources res,
157            Message message, Map<String, Address> addressCache,
158            HtmlPrintTemplates templates, FormattedDateBuilder dateBuilder) {
159        final Address fromAddress = Utils.getAddress(addressCache, message.getFrom());
160        final long when = message.dateReceivedMs;
161        final String date = dateBuilder.formatDateTimeForPrinting(when);
162
163        templates.appendMessage(fromAddress.getPersonal(), fromAddress.getAddress(), date,
164                renderRecipients(res, addressCache, message), message.getBodyAsHtml(),
165                renderAttachments(context, res, message));
166    }
167
168    /**
169     * Builds html for the message header. Specifically, the (optional) lists of
170     * reply-to, to, cc, and bcc.
171     */
172    private static String renderRecipients(Resources res,
173            Map<String, Address> addressCache, Message message) {
174        final StringBuilder recipients = new StringBuilder();
175
176        // reply-to
177        final String replyTo = renderEmailList(res, message.getReplyToAddresses(), addressCache);
178        buildEmailDiv(res, recipients, replyTo, REPLY_TO_DIV_START, DIV_END,
179                R.string.replyto_heading);
180
181        // to
182        // To has special semantics since the message can be a draft.
183        // If it is a draft and there are no to addresses, we just print "Draft".
184        // If it is a draft and there are to addresses, we print "Draft To: "
185        // If not a draft, we just use "To: ".
186        final boolean isDraft = message.draftType != UIProvider.DraftType.NOT_A_DRAFT;
187        final String to = renderEmailList(res, message.getToAddresses(), addressCache);
188        if (isDraft && to == null) {
189            recipients.append(DIV_START).append(res.getString(R.string.draft_heading))
190                    .append(DIV_END);
191        } else {
192            buildEmailDiv(res, recipients, to, DIV_START, DIV_END,
193                    isDraft ? R.string.draft_to_heading : R.string.to_heading_no_space);
194        }
195
196        // cc
197        final String cc = renderEmailList(res, message.getCcAddresses(), addressCache);
198        buildEmailDiv(res, recipients, cc, DIV_START, DIV_END,
199                R.string.cc_heading);
200
201        // bcc
202        final String bcc = renderEmailList(res, message.getBccAddresses(), addressCache);
203        buildEmailDiv(res, recipients, bcc, DIV_START, DIV_END,
204                R.string.bcc_heading);
205
206        return recipients.toString();
207    }
208
209    /**
210     * Appends an html div containing a list of emails based on the passed in data.
211     */
212    private static void buildEmailDiv(Resources res, StringBuilder recipients, String emailList,
213            String divStart, String divEnd, int headingId) {
214        if (emailList != null) {
215            recipients.append(divStart).append(res.getString(headingId))
216                    .append('\u0020').append(emailList).append(divEnd);
217        }
218    }
219
220    /**
221     * Builds and returns a list of comma-separated emails of the form "Name &lt;email&gt;".
222     * If the email does not contain a name, "email" is used instead.
223     */
224    private static String renderEmailList(Resources resources, String[] emails,
225            Map<String, Address> addressCache) {
226        if (emails == null || emails.length == 0) {
227            return null;
228        }
229        final String[] formattedEmails = new String[emails.length];
230        for (int i = 0; i < emails.length; i++) {
231            final Address email = Utils.getAddress(addressCache, emails[i]);
232            final String name = email.getPersonal();
233            final String address = email.getAddress();
234
235            if (TextUtils.isEmpty(name)) {
236                formattedEmails[i] = address;
237            } else {
238                formattedEmails[i] = resources.getString(R.string.address_print_display_format,
239                        name, address);
240            }
241        }
242
243        return TextUtils.join(resources.getString(R.string.enumeration_comma), formattedEmails);
244    }
245
246    /**
247     * Builds and returns html for a message's attachments.
248     */
249    private static String renderAttachments(
250            Context context, Resources resources, Message message) {
251        if (!message.hasAttachments) {
252            return "";
253        }
254
255        final int numAttachments = message.getAttachmentCount(false /* includeInline */);
256
257        // if we have no attachments after filtering out inline attachments, return.
258        if (numAttachments == 0) {
259            return "";
260        }
261
262        final StringBuilder sb = new StringBuilder("<br clear=all>"
263                + "<div style=\"width:50%;border-top:2px #AAAAAA solid\"></div>"
264                + "<table class=att cellspacing=0 cellpadding=5 border=0>");
265
266        // If the message has more than one attachment, list the number of attachments.
267        if (numAttachments > 1) {
268            sb.append("<tr><td colspan=2><b style=\"padding-left:3\">")
269                    .append(resources.getQuantityString(
270                            R.plurals.num_attachments, numAttachments, numAttachments))
271                    .append("</b></td></tr>");
272        }
273
274        final List<Attachment> attachments = message.getAttachments();
275        for (int i = 0, size = attachments.size(); i < size; i++) {
276            final Attachment attachment = attachments.get(i);
277            // skip inline attachments
278            if (attachment.isInlineAttachment()) {
279                continue;
280            }
281            sb.append("<tr><td><table cellspacing=\"0\" cellpadding=\"0\"><tr>");
282
283            // TODO - thumbnail previews of images
284            sb.append("<td><img width=\"16\" height=\"16\" src=\"file:///android_asset/images/")
285                    .append(getIconFilename(attachment.getContentType()))
286                    .append("\"></td><td width=\"7\"></td><td><b>")
287                    .append(attachment.getName())
288                    .append("</b><br>").append(
289                    AttachmentUtils.convertToHumanReadableSize(context, attachment.size))
290                    .append("</td></tr></table></td></tr>");
291        }
292
293        sb.append("</table>");
294
295        return sb.toString();
296    }
297
298    /**
299     * Returns an appropriate filename for various attachment mime types.
300     */
301    private static String getIconFilename(String mimeType) {
302        if (mimeType.startsWith("application/msword") ||
303                mimeType.startsWith("application/vnd.oasis.opendocument.text") ||
304                mimeType.equals("application/rtf") ||
305                mimeType.equals("application/"
306                        + "vnd.openxmlformats-officedocument.wordprocessingml.document")) {
307            return "doc.gif";
308        } else if (mimeType.startsWith("image/")) {
309            return "graphic.gif";
310        } else if (mimeType.startsWith("text/html")) {
311            return "html.gif";
312        } else if (mimeType.startsWith("application/pdf")) {
313            return "pdf.gif";
314        } else if (mimeType.endsWith("powerpoint") ||
315                mimeType.equals("application/vnd.oasis.opendocument.presentation") ||
316                mimeType.equals("application/"
317                        + "vnd.openxmlformats-officedocument.presentationml.presentation")) {
318            return "ppt.gif";
319        } else if ((mimeType.startsWith("audio/")) ||
320                (mimeType.startsWith("music/"))) {
321            return "sound.gif";
322        } else if (mimeType.startsWith("text/plain")) {
323            return "txt.gif";
324        } else if (mimeType.endsWith("excel") ||
325                mimeType.equals("application/vnd.oasis.opendocument.spreadsheet") ||
326                mimeType.equals("application/"
327                        + "vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
328            return "xls.gif";
329        } else if ((mimeType.endsWith("zip")) ||
330                (mimeType.endsWith("/x-compress")) ||
331                (mimeType.endsWith("/x-compressed"))) {
332            return "zip.gif";
333        } else {
334            return "generic.gif";
335        }
336    }
337}
338