Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / browser / ui / libgtk2ui / print_dialog_gtk2.cc
blob06cb926339632f7f694dc6fe47626745694b7468
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/libgtk2ui/print_dialog_gtk2.h"
7 #include <gtk/gtkunixprint.h>
9 #include <string>
10 #include <vector>
12 #include "base/bind.h"
13 #include "base/file_util.h"
14 #include "base/files/file_util_proxy.h"
15 #include "base/lazy_instance.h"
16 #include "base/logging.h"
17 #include "base/message_loop/message_loop_proxy.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/values.h"
20 #include "chrome/browser/ui/libgtk2ui/printing_gtk2_util.h"
21 #include "printing/metafile.h"
22 #include "printing/print_job_constants.h"
23 #include "printing/print_settings.h"
25 using content::BrowserThread;
26 using printing::PageRanges;
27 using printing::PrintSettings;
29 namespace {
31 // CUPS Duplex attribute and values.
32 const char kCUPSDuplex[] = "cups-Duplex";
33 const char kDuplexNone[] = "None";
34 const char kDuplexTumble[] = "DuplexTumble";
35 const char kDuplexNoTumble[] = "DuplexNoTumble";
37 class StickyPrintSettingGtk {
38 public:
39 StickyPrintSettingGtk() : last_used_settings_(gtk_print_settings_new()) {
41 ~StickyPrintSettingGtk() {
42 NOTREACHED(); // Intended to be used with a Leaky LazyInstance.
45 GtkPrintSettings* settings() {
46 return last_used_settings_;
49 void SetLastUsedSettings(GtkPrintSettings* settings) {
50 DCHECK(last_used_settings_);
51 g_object_unref(last_used_settings_);
52 last_used_settings_ = gtk_print_settings_copy(settings);
55 private:
56 GtkPrintSettings* last_used_settings_;
58 DISALLOW_COPY_AND_ASSIGN(StickyPrintSettingGtk);
61 base::LazyInstance<StickyPrintSettingGtk>::Leaky g_last_used_settings =
62 LAZY_INSTANCE_INITIALIZER;
64 // Helper class to track GTK printers.
65 class GtkPrinterList {
66 public:
67 GtkPrinterList() : default_printer_(NULL) {
68 gtk_enumerate_printers(SetPrinter, this, NULL, TRUE);
71 ~GtkPrinterList() {
72 for (std::vector<GtkPrinter*>::iterator it = printers_.begin();
73 it < printers_.end(); ++it) {
74 g_object_unref(*it);
78 // Can return NULL if there's no default printer. E.g. Printer on a laptop
79 // is "home_printer", but the laptop is at work.
80 GtkPrinter* default_printer() {
81 return default_printer_;
84 // Can return NULL if the printer cannot be found due to:
85 // - Printer list out of sync with printer dialog UI.
86 // - Querying for non-existant printers like 'Print to PDF'.
87 GtkPrinter* GetPrinterWithName(const std::string& name) {
88 if (name.empty())
89 return NULL;
91 for (std::vector<GtkPrinter*>::iterator it = printers_.begin();
92 it < printers_.end(); ++it) {
93 if (gtk_printer_get_name(*it) == name) {
94 return *it;
98 return NULL;
101 private:
102 // Callback function used by gtk_enumerate_printers() to get all printer.
103 static gboolean SetPrinter(GtkPrinter* printer, gpointer data) {
104 GtkPrinterList* printer_list = reinterpret_cast<GtkPrinterList*>(data);
105 if (gtk_printer_is_default(printer))
106 printer_list->default_printer_ = printer;
108 g_object_ref(printer);
109 printer_list->printers_.push_back(printer);
111 return FALSE;
114 std::vector<GtkPrinter*> printers_;
115 GtkPrinter* default_printer_;
118 } // namespace
120 // static
121 printing::PrintDialogGtkInterface* PrintDialogGtk2::CreatePrintDialog(
122 PrintingContextLinux* context) {
123 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
124 return new PrintDialogGtk2(context);
127 PrintDialogGtk2::PrintDialogGtk2(PrintingContextLinux* context)
128 : context_(context),
129 dialog_(NULL),
130 gtk_settings_(NULL),
131 page_setup_(NULL),
132 printer_(NULL) {
135 PrintDialogGtk2::~PrintDialogGtk2() {
136 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
138 if (dialog_) {
139 gtk_widget_destroy(dialog_);
140 dialog_ = NULL;
142 if (gtk_settings_) {
143 g_object_unref(gtk_settings_);
144 gtk_settings_ = NULL;
146 if (page_setup_) {
147 g_object_unref(page_setup_);
148 page_setup_ = NULL;
150 if (printer_) {
151 g_object_unref(printer_);
152 printer_ = NULL;
156 void PrintDialogGtk2::UseDefaultSettings() {
157 DCHECK(!page_setup_);
158 DCHECK(!printer_);
160 // |gtk_settings_| is a new copy.
161 gtk_settings_ =
162 gtk_print_settings_copy(g_last_used_settings.Get().settings());
163 page_setup_ = gtk_page_setup_new();
165 PrintSettings settings;
166 InitPrintSettings(&settings);
169 bool PrintDialogGtk2::UpdateSettings(printing::PrintSettings* settings) {
170 if (!gtk_settings_) {
171 gtk_settings_ =
172 gtk_print_settings_copy(g_last_used_settings.Get().settings());
175 scoped_ptr<GtkPrinterList> printer_list(new GtkPrinterList);
176 printer_ = printer_list->GetPrinterWithName(
177 base::UTF16ToUTF8(settings->device_name()));
178 if (printer_) {
179 g_object_ref(printer_);
180 gtk_print_settings_set_printer(gtk_settings_,
181 gtk_printer_get_name(printer_));
182 if (!page_setup_) {
183 page_setup_ = gtk_printer_get_default_page_size(printer_);
187 gtk_print_settings_set_n_copies(gtk_settings_, settings->copies());
188 gtk_print_settings_set_collate(gtk_settings_, settings->collate());
190 #if defined(USE_CUPS)
191 std::string color_value;
192 std::string color_setting_name;
193 printing::GetColorModelForMode(settings->color(), &color_setting_name,
194 &color_value);
195 gtk_print_settings_set(gtk_settings_, color_setting_name.c_str(),
196 color_value.c_str());
198 if (settings->duplex_mode() != printing::UNKNOWN_DUPLEX_MODE) {
199 const char* cups_duplex_mode = NULL;
200 switch (settings->duplex_mode()) {
201 case printing::LONG_EDGE:
202 cups_duplex_mode = kDuplexNoTumble;
203 break;
204 case printing::SHORT_EDGE:
205 cups_duplex_mode = kDuplexTumble;
206 break;
207 case printing::SIMPLEX:
208 cups_duplex_mode = kDuplexNone;
209 break;
210 default: // UNKNOWN_DUPLEX_MODE
211 NOTREACHED();
212 break;
214 gtk_print_settings_set(gtk_settings_, kCUPSDuplex, cups_duplex_mode);
216 #endif
217 if (!page_setup_)
218 page_setup_ = gtk_page_setup_new();
220 gtk_print_settings_set_orientation(
221 gtk_settings_,
222 settings->landscape() ? GTK_PAGE_ORIENTATION_LANDSCAPE :
223 GTK_PAGE_ORIENTATION_PORTRAIT);
225 InitPrintSettings(settings);
226 return true;
229 void PrintDialogGtk2::ShowDialog(
230 gfx::NativeView parent_view,
231 bool has_selection,
232 const PrintingContextLinux::PrintSettingsCallback& callback) {
233 callback_ = callback;
235 // TODO(mukai): take care of parent as select_file_dialog_impl_gtk2.
236 dialog_ = gtk_print_unix_dialog_new(NULL, NULL);
237 g_signal_connect(dialog_, "delete-event",
238 G_CALLBACK(gtk_widget_hide_on_delete), NULL);
241 // Set modal so user cannot focus the same tab and press print again.
242 gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE);
244 // Since we only generate PDF, only show printers that support PDF.
245 // TODO(thestig) Add more capabilities to support?
246 GtkPrintCapabilities cap = static_cast<GtkPrintCapabilities>(
247 GTK_PRINT_CAPABILITY_GENERATE_PDF |
248 GTK_PRINT_CAPABILITY_PAGE_SET |
249 GTK_PRINT_CAPABILITY_COPIES |
250 GTK_PRINT_CAPABILITY_COLLATE |
251 GTK_PRINT_CAPABILITY_REVERSE);
252 gtk_print_unix_dialog_set_manual_capabilities(GTK_PRINT_UNIX_DIALOG(dialog_),
253 cap);
254 gtk_print_unix_dialog_set_embed_page_setup(GTK_PRINT_UNIX_DIALOG(dialog_),
255 TRUE);
256 gtk_print_unix_dialog_set_support_selection(GTK_PRINT_UNIX_DIALOG(dialog_),
257 TRUE);
258 gtk_print_unix_dialog_set_has_selection(GTK_PRINT_UNIX_DIALOG(dialog_),
259 has_selection);
260 gtk_print_unix_dialog_set_settings(GTK_PRINT_UNIX_DIALOG(dialog_),
261 gtk_settings_);
262 g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this);
263 gtk_widget_show(dialog_);
266 void PrintDialogGtk2::PrintDocument(const printing::Metafile* metafile,
267 const base::string16& document_name) {
268 // This runs on the print worker thread, does not block the UI thread.
269 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
271 // The document printing tasks can outlive the PrintingContext that created
272 // this dialog.
273 AddRef();
275 bool error = false;
276 if (!base::CreateTemporaryFile(&path_to_pdf_)) {
277 LOG(ERROR) << "Creating temporary file failed";
278 error = true;
281 if (!error && !metafile->SaveTo(path_to_pdf_)) {
282 LOG(ERROR) << "Saving metafile failed";
283 base::DeleteFile(path_to_pdf_, false);
284 error = true;
287 if (error) {
288 // Matches AddRef() above.
289 Release();
290 } else {
291 // No errors, continue printing.
292 BrowserThread::PostTask(
293 BrowserThread::UI, FROM_HERE,
294 base::Bind(&PrintDialogGtk2::SendDocumentToPrinter, this,
295 document_name));
299 void PrintDialogGtk2::AddRefToDialog() {
300 AddRef();
303 void PrintDialogGtk2::ReleaseDialog() {
304 Release();
307 void PrintDialogGtk2::OnResponse(GtkWidget* dialog, int response_id) {
308 int num_matched_handlers = g_signal_handlers_disconnect_by_func(
309 dialog_, reinterpret_cast<gpointer>(&OnResponseThunk), this);
310 CHECK_EQ(1, num_matched_handlers);
312 gtk_widget_hide(dialog_);
314 switch (response_id) {
315 case GTK_RESPONSE_OK: {
316 if (gtk_settings_)
317 g_object_unref(gtk_settings_);
318 gtk_settings_ = gtk_print_unix_dialog_get_settings(
319 GTK_PRINT_UNIX_DIALOG(dialog_));
321 if (printer_)
322 g_object_unref(printer_);
323 printer_ = gtk_print_unix_dialog_get_selected_printer(
324 GTK_PRINT_UNIX_DIALOG(dialog_));
325 g_object_ref(printer_);
327 if (page_setup_)
328 g_object_unref(page_setup_);
329 page_setup_ = gtk_print_unix_dialog_get_page_setup(
330 GTK_PRINT_UNIX_DIALOG(dialog_));
331 g_object_ref(page_setup_);
333 // Handle page ranges.
334 PageRanges ranges_vector;
335 gint num_ranges;
336 bool print_selection_only = false;
337 switch (gtk_print_settings_get_print_pages(gtk_settings_)) {
338 case GTK_PRINT_PAGES_RANGES: {
339 GtkPageRange* gtk_range =
340 gtk_print_settings_get_page_ranges(gtk_settings_, &num_ranges);
341 if (gtk_range) {
342 for (int i = 0; i < num_ranges; ++i) {
343 printing::PageRange range;
344 range.from = gtk_range[i].start;
345 range.to = gtk_range[i].end;
346 ranges_vector.push_back(range);
348 g_free(gtk_range);
350 break;
352 case GTK_PRINT_PAGES_SELECTION:
353 print_selection_only = true;
354 break;
355 case GTK_PRINT_PAGES_ALL:
356 // Leave |ranges_vector| empty to indicate print all pages.
357 break;
358 case GTK_PRINT_PAGES_CURRENT:
359 default:
360 NOTREACHED();
361 break;
364 PrintSettings settings;
365 settings.set_ranges(ranges_vector);
366 settings.set_selection_only(print_selection_only);
367 InitPrintSettingsGtk(gtk_settings_, page_setup_, &settings);
368 context_->InitWithSettings(settings);
369 callback_.Run(PrintingContextLinux::OK);
370 callback_.Reset();
371 return;
373 case GTK_RESPONSE_DELETE_EVENT: // Fall through.
374 case GTK_RESPONSE_CANCEL: {
375 callback_.Run(PrintingContextLinux::CANCEL);
376 callback_.Reset();
377 return;
379 case GTK_RESPONSE_APPLY:
380 default: {
381 NOTREACHED();
386 void PrintDialogGtk2::SendDocumentToPrinter(
387 const base::string16& document_name) {
388 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
390 // If |printer_| is NULL then somehow the GTK printer list changed out under
391 // us. In which case, just bail out.
392 if (!printer_) {
393 // Matches AddRef() in PrintDocument();
394 Release();
395 return;
398 // Save the settings for next time.
399 g_last_used_settings.Get().SetLastUsedSettings(gtk_settings_);
401 GtkPrintJob* print_job = gtk_print_job_new(
402 base::UTF16ToUTF8(document_name).c_str(),
403 printer_,
404 gtk_settings_,
405 page_setup_);
406 gtk_print_job_set_source_file(print_job, path_to_pdf_.value().c_str(), NULL);
407 gtk_print_job_send(print_job, OnJobCompletedThunk, this, NULL);
410 // static
411 void PrintDialogGtk2::OnJobCompletedThunk(GtkPrintJob* print_job,
412 gpointer user_data,
413 GError* error) {
414 static_cast<PrintDialogGtk2*>(user_data)->OnJobCompleted(print_job, error);
417 void PrintDialogGtk2::OnJobCompleted(GtkPrintJob* print_job, GError* error) {
418 if (error)
419 LOG(ERROR) << "Printing failed: " << error->message;
420 if (print_job)
421 g_object_unref(print_job);
422 base::FileUtilProxy::DeleteFile(
423 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE).get(),
424 path_to_pdf_,
425 false,
426 base::FileUtilProxy::StatusCallback());
427 // Printing finished. Matches AddRef() in PrintDocument();
428 Release();
431 void PrintDialogGtk2::InitPrintSettings(PrintSettings* settings) {
432 InitPrintSettingsGtk(gtk_settings_, page_setup_, settings);
433 context_->InitWithSettings(*settings);