2008-11-01 Sebastien Pouliot <sebastien@ximian.com>
[mono.git] / mcs / class / System.Drawing / System.Drawing.Printing / PrintingServicesUnix.cs
1 //#define PrintDebug
2 //
3 // Copyright (C) 2005, 2007 Novell, Inc. http://www.novell.com
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining
6 // a copy of this software and associated documentation files (the
7 // "Software"), to deal in the Software without restriction, including
8 // without limitation the rights to use, copy, modify, merge, publish,
9 // distribute, sublicense, and/or sell copies of the Software, and to
10 // permit persons to whom the Software is furnished to do so, subject to
11 // the following conditions:
12 //
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 //
24 // Author:
25 //
26 //      Jordi Mas i Hernandez, jordimash@gmail.com
27 //
28
29 using System.Runtime.InteropServices;
30 using System.Collections;
31 using System.Collections.Specialized;
32 using System.Drawing.Printing;
33 using System.ComponentModel;
34 using System.Drawing.Imaging;
35 using System.Text;
36 using System.IO;
37
38 namespace System.Drawing.Printing
39 {
40         internal class PrintingServicesUnix : PrintingServices
41         {
42                 #region Private Fields
43                 
44                 private static Hashtable doc_info = new Hashtable ();
45                 private static bool cups_installed;
46                 
47                 //private string printer_name;
48                 
49                 private static Hashtable installed_printers;
50                 private static string default_printer = String.Empty;
51                                 
52                 #endregion
53
54                 #region Constructor
55
56                 internal PrintingServicesUnix () {
57                 }
58                 
59                 static PrintingServicesUnix () {
60                         installed_printers = new Hashtable ();
61                         CheckCupsInstalled ();
62                 }
63                 
64                 #endregion
65
66                 #region Properties
67
68                 internal static PrinterSettings.StringCollection InstalledPrinters {
69                         get {
70                                 LoadPrinters();
71                                 PrinterSettings.StringCollection list = new PrinterSettings.StringCollection (new string[] {});
72                                 foreach (object key in installed_printers.Keys) {
73                                         list.Add (key.ToString());
74                                 }
75                                 return list;
76                         }
77                 }
78
79                 internal override string DefaultPrinter {
80                         get {
81                                 if (installed_printers.Count == 0)
82                                         LoadPrinters();
83                                 return default_printer;
84                         }
85                 }
86                 
87                 #endregion
88
89
90                 #region Methods
91
92                 /// <summary>
93                 /// Do a cups call to check if it is installed
94                 /// </summary>
95                 private static void CheckCupsInstalled ()
96                 {
97                         try {
98                                 cupsGetDefault ();
99                         }
100                         catch (DllNotFoundException) {
101                                 Console.WriteLine("libcups not found. To have printing support, you need cups installed");
102                                 cups_installed = false;
103                                 return;
104                         }
105
106                         cups_installed = true;
107                 }
108
109                 /// <summary>
110                 /// Open the printer's PPD file
111                 /// </summary>
112                 /// <param name="printer">Printer name, returned from cupsGetDests</param>
113                 private IntPtr OpenPrinter (string printer)
114                 {
115                         try {
116                                 IntPtr ptr = cupsGetPPD (printer);
117                                 string ppd_filename = Marshal.PtrToStringAnsi (ptr);
118                                 IntPtr ppd_handle = ppdOpenFile (ppd_filename);
119                                 return ppd_handle;
120                         }
121                         catch (Exception) {
122                                 Console.WriteLine ("There was an error opening the printer {0}. Please check your cups installation.");
123                         }
124                         return IntPtr.Zero;
125                 }
126
127                 /// <summary>
128                 /// Close the printer file
129                 /// </summary>
130                 /// <param name="handle">PPD handle</param>
131                 private void ClosePrinter (ref IntPtr handle)
132                 {
133                         try {
134                                 if (handle != IntPtr.Zero)
135                                         ppdClose (handle);
136                         }
137                         finally {
138                                 handle = IntPtr.Zero;
139                         }
140                 }
141
142                 private static int OpenDests (ref IntPtr ptr) {
143                         try {
144                                 return cupsGetDests (ref ptr);
145                         }
146                         catch {
147                                 ptr = IntPtr.Zero;
148                         }
149                         return 0;
150                 }
151
152                 private static void CloseDests (ref IntPtr ptr, int count) {
153                         try {
154                                 if (ptr != IntPtr.Zero)
155                                         cupsFreeDests (count, ptr);
156                         }
157                         finally {
158                                 ptr = IntPtr.Zero;
159                         }
160                 }
161
162                 /// <summary>
163                 /// Checks if a printer has a valid PPD file. Caches the result unless force is true
164                 /// </summary>
165                 /// <param name="force">Does the check disregarding the last cached value if true</param>
166                 internal override bool IsPrinterValid(string printer)
167                 {
168                         if (!cups_installed || printer == null | printer == String.Empty)
169                                 return false;
170                                 
171                         return installed_printers.Contains (printer);
172 /*
173                         if (!force && this.printer_name != null && String.Intern(this.printer_name).Equals(printer))
174                                 return is_printer_valid;
175
176                         IntPtr ptr = cupsGetPPD (printer);
177                         string ppd_filename = Marshal.PtrToStringAnsi (ptr);
178                         is_printer_valid = ppd_filename != null;
179                         this.printer_name = printer; 
180                         return is_printer_valid;
181 */                      
182                 }
183         
184                 /// <summary>
185                 /// Loads the printer settings and initializes the PrinterSettings and PageSettings fields
186                 /// </summary>
187                 /// <param name="printer">Printer name</param>
188                 /// <param name="settings">PrinterSettings object to initialize</param>
189                 internal override void LoadPrinterSettings (string printer, PrinterSettings settings)
190                 {
191                         if (cups_installed == false || (printer == null) || (printer == String.Empty))
192                                 return;
193
194                         if (installed_printers.Count == 0)
195                                 LoadPrinters ();
196
197                         if (((SysPrn.Printer)installed_printers[printer]).Settings != null) {
198                                 SysPrn.Printer p = (SysPrn.Printer) installed_printers[printer];
199                                 settings.can_duplex = p.Settings.can_duplex;
200                                 settings.is_plotter = p.Settings.is_plotter;
201                                 settings.landscape_angle = p.Settings.landscape_angle;
202                                 settings.maximum_copies = p.Settings.maximum_copies;
203                                 settings.paper_sizes = p.Settings.paper_sizes;
204                                 settings.paper_sources = p.Settings.paper_sources;
205                                 settings.printer_capabilities = p.Settings.printer_capabilities;
206                                 settings.printer_resolutions = p.Settings.printer_resolutions;
207                                 settings.supports_color = p.Settings.supports_color;
208                                 return;
209                         }
210
211                         settings.PrinterCapabilities.Clear ();
212
213                         IntPtr dests = IntPtr.Zero, ptr = IntPtr.Zero, ptr_printer, ppd_handle = IntPtr.Zero;
214                         string name = String.Empty;
215                         CUPS_DESTS printer_dest;
216                         PPD_FILE ppd;
217                         int ret = 0, cups_dests_size;
218                         NameValueCollection options, paper_names, paper_sources;
219
220                         try {
221                                 ret = OpenDests (ref dests);
222                                 if (ret == 0)
223                                         return;
224
225                                 cups_dests_size = Marshal.SizeOf (typeof(CUPS_DESTS));
226                                 ptr = dests;
227                                 for (int i = 0; i < ret; i++) {
228                                         ptr_printer = (IntPtr) Marshal.ReadIntPtr (ptr);
229                                         if (Marshal.PtrToStringAnsi (ptr_printer).Equals(printer)) {
230                                                 name = printer;
231                                                 break;
232                                         }
233                                         ptr = (IntPtr) ((long)ptr + cups_dests_size);
234                                 }
235                         
236                                 if (!name.Equals(printer)) {
237                                         return;
238                                 }
239
240                                 ppd_handle = OpenPrinter (printer);
241                                 if (ppd_handle == IntPtr.Zero)
242                                         return;
243
244                                 printer_dest = (CUPS_DESTS) Marshal.PtrToStructure (ptr, typeof (CUPS_DESTS));
245                                 options = new NameValueCollection();
246                                 paper_names = new NameValueCollection();
247                                 paper_sources = new NameValueCollection();
248                                 LoadPrinterOptions(printer_dest.options, printer_dest.num_options, ppd_handle, options, paper_names, paper_sources);
249                         
250                                 if (settings.paper_sizes == null)
251                                         settings.paper_sizes = new PrinterSettings.PaperSizeCollection (new PaperSize [] {});
252                                 else
253                                         settings.paper_sizes.Clear();
254                         
255                                 if (settings.paper_sources == null)                             
256                                         settings.paper_sources = new PrinterSettings.PaperSourceCollection (new PaperSource [] {});
257                                 else
258                                         settings.paper_sources.Clear();
259                         
260                                 string defsource = options["InputSlot"];
261                                 string defsize = options["PageSize"];
262                         
263                                 settings.DefaultPageSettings.PaperSource = LoadPrinterPaperSources (settings, defsource, paper_sources);
264                                 settings.DefaultPageSettings.PaperSize = LoadPrinterPaperSizes (ppd_handle, settings, defsize, paper_names);
265                         
266                                 ppd = (PPD_FILE) Marshal.PtrToStructure (ppd_handle, typeof (PPD_FILE));
267                                 settings.landscape_angle = ppd.landscape;
268                                 settings.supports_color = (ppd.color_device == 0) ? false : true;
269                                 settings.can_duplex = options["Duplex"] != null;
270                         
271                                 ClosePrinter (ref ppd_handle);
272                         
273                                 ((SysPrn.Printer)installed_printers[printer]).Settings = settings;
274                         }
275                         finally {
276                                 CloseDests (ref dests, ret);
277                         }
278                 }
279                 
280                 /// <summary>
281                 /// Loads the global options of a printer plus the paper types and trays supported.
282                 /// </summary>
283                 /// <param name="options">The options field of a printer's CUPS_DESTS structure</param>
284                 /// <param name="numOptions">The number of options of the printer</param>
285                 /// <param name="ppd">A ppd handle for the printer, returned by ppdOpen</param>
286                 /// <param name="list">The list of options</param>
287                 /// <param name="paper_names">A list of types of paper (PageSize)</param>
288                 /// <param name="paper_sources">A list of trays(InputSlot) </param>
289                 private static void LoadPrinterOptions(IntPtr options, int numOptions, IntPtr ppd, 
290                                                                                  NameValueCollection list, 
291                                                                                  NameValueCollection paper_names,
292                                                                                  NameValueCollection paper_sources)
293                 {
294                         CUPS_OPTIONS cups_options;
295                         string option_name, option_value;
296                         int cups_size = Marshal.SizeOf(typeof(CUPS_OPTIONS));
297                         
298                         for (int j = 0; j < numOptions; j++)
299                         {
300                                 cups_options = (CUPS_OPTIONS) Marshal.PtrToStructure(options, typeof(CUPS_OPTIONS));
301                                 option_name = Marshal.PtrToStringAnsi(cups_options.name);
302                                 option_value = Marshal.PtrToStringAnsi(cups_options.val);
303
304                                 #if PrintDebug
305                                 Console.WriteLine("{0} = {1}", option_name, option_value);
306                                 #endif
307                                 
308                                 list.Add(option_name, option_value);
309
310                                 options = (IntPtr) ((long)options + cups_size);
311                         }
312                         
313                         LoadOptionList (ppd, "PageSize", paper_names);
314                         LoadOptionList (ppd, "InputSlot", paper_sources);
315                 }
316                 
317                 /// <summary>
318                 /// Loads the global options of a printer. 
319                 /// </summary>
320                 /// <param name="options">The options field of a printer's CUPS_DESTS structure</param>
321                 /// <param name="numOptions">The number of options of the printer</param>
322                 private static NameValueCollection LoadPrinterOptions(IntPtr options, int numOptions)
323                 {
324                         CUPS_OPTIONS cups_options;
325                         string option_name, option_value;
326                         int cups_size = Marshal.SizeOf (typeof(CUPS_OPTIONS));
327                         NameValueCollection list = new NameValueCollection ();
328                         for (int j = 0; j < numOptions; j++)
329                         {
330                                 cups_options = (CUPS_OPTIONS) Marshal.PtrToStructure(options, typeof(CUPS_OPTIONS));
331                                 option_name = Marshal.PtrToStringAnsi (cups_options.name);
332                                 option_value = Marshal.PtrToStringAnsi (cups_options.val);
333                                 
334                                 #if PrintDebug
335                                 Console.WriteLine("{0} = {1}", option_name, option_value);
336                                 #endif
337                                 
338                                 list.Add (option_name, option_value);
339
340                                 options = (IntPtr) ((long)options + cups_size);
341                         }
342                         return list;
343                 }
344
345                 /// <summary>
346                 /// Loads a printer's options (selection of paper sizes, paper sources, etc)
347                 /// </summary>
348                 /// <param name="ppd">Printer ppd file handle</param>
349                 /// <param name="option_name">Name of the option group to load</param>
350                 /// <param name="list">List of loaded options</param>
351                 private static void LoadOptionList(IntPtr ppd, string option_name, NameValueCollection list) {
352
353                         IntPtr ptr = IntPtr.Zero;
354                         PPD_OPTION ppd_option;
355                         PPD_CHOICE choice;
356                         int choice_size = Marshal.SizeOf(typeof(PPD_CHOICE)); 
357                         
358                         ptr = ppdFindOption (ppd, option_name);
359                         if (ptr != IntPtr.Zero)
360                         {
361                                 ppd_option = (PPD_OPTION) Marshal.PtrToStructure (ptr, typeof (PPD_OPTION));
362                                 #if PrintDebug
363                                 Console.WriteLine (" OPTION  key:{0} def:{1} text: {2}", ppd_option.keyword, ppd_option.defchoice, ppd_option.text);
364                                 #endif
365
366                                 ptr = ppd_option.choices;
367                                 for (int c = 0; c < ppd_option.num_choices; c++) {
368                                         choice = (PPD_CHOICE) Marshal.PtrToStructure (ptr, typeof (PPD_CHOICE));
369                                         list.Add(choice.choice, choice.text);
370                                         #if PrintDebug
371                                         Console.WriteLine ("       choice:{0} - text: {1}", choice.choice, choice.text);
372                                         #endif
373
374                                         ptr = (IntPtr) ((long)ptr + choice_size);
375                                 }
376                         }               
377                 }
378
379                 /// <summary>
380                 /// Loads a printer's available resolutions
381                 /// </summary>
382                 /// <param name="printer">Printer name</param>
383                 /// <param name="settings">PrinterSettings object to fill</param>
384                 internal override void LoadPrinterResolutions (string printer, PrinterSettings settings)
385                 {
386                         settings.PrinterResolutions.Clear ();
387                         LoadDefaultResolutions (settings.PrinterResolutions);
388                 }
389
390                 /// <summary>
391                 /// Loads a printer's paper sizes. Returns the default PaperSize, and fills a list of paper_names for use in dialogues
392                 /// </summary>
393                 /// <param name="ppd_handle">PPD printer file handle</param>
394                 /// <param name="settings">PrinterSettings object to fill</param>
395                 /// <param name="def_size">Default paper size, from the global options of the printer</param>
396                 /// <param name="paper_names">List of available paper sizes that gets filled</param>
397                 private PaperSize LoadPrinterPaperSizes(IntPtr ppd_handle, PrinterSettings settings, 
398                                                                                                 string def_size, NameValueCollection paper_names)
399                 {
400                         IntPtr ptr;
401                         string real_name;
402                         PPD_FILE ppd;
403                         PPD_SIZE size;
404                         PaperSize ps;
405
406                         PaperSize defsize = null;
407                         ppd = (PPD_FILE) Marshal.PtrToStructure (ppd_handle, typeof (PPD_FILE));
408                         ptr = ppd.sizes;
409                         float w, h;
410                         for (int i = 0; i < ppd.num_sizes; i++) {
411                                 size = (PPD_SIZE) Marshal.PtrToStructure (ptr, typeof (PPD_SIZE));
412                                 real_name = paper_names[size.name];
413                                 w = size.width * 100 / 72;
414                                 h = size.length * 100 / 72;
415                                 ps = new PaperSize (real_name, (int) w, (int) h, GetPaperKind ((int) w, (int) h), def_size == real_name);
416                                 if (def_size == real_name)
417                                         defsize = ps;
418                                 ps.SetKind (GetPaperKind ((int) w, (int) h));
419                                 settings.paper_sizes.Add (ps);
420                                 ptr = (IntPtr) ((long)ptr + Marshal.SizeOf (size));
421                         }
422                         
423                         return defsize;
424
425                 }
426                 
427                 /// <summary>
428                 /// Loads a printer's paper sources (trays). Returns the default PaperSource, and fills a list of paper_sources for use in dialogues
429                 /// </summary>
430                 /// <param name="settings">PrinterSettings object to fill</param>
431                 /// <param name="def_source">Default paper source, from the global options of the printer</param>
432                 /// <param name="paper_sources">List of available paper sizes that gets filled</param>
433                 private PaperSource LoadPrinterPaperSources (PrinterSettings settings, string def_source, 
434                                                                                                         NameValueCollection paper_sources)
435                 {
436                         PaperSourceKind kind;
437                         PaperSource defsource = null;
438                         foreach(string source in paper_sources) {
439                                 switch (source)
440                                 {
441                                         case "Tray":
442                                                 kind = PaperSourceKind.AutomaticFeed;
443                                                 break;
444                                         case "Envelope":
445                                                 kind = PaperSourceKind.Envelope;
446                                                 break;
447                                         case "Manual":
448                                                 kind = PaperSourceKind.Manual;
449                                                 break;
450                                         default:
451                                                 kind = PaperSourceKind.Custom;
452                                                 break;
453                                 }
454                                 settings.paper_sources.Add (new PaperSource (paper_sources[source], kind, def_source == source));
455                                 if (def_source == source)
456                                         defsource = settings.paper_sources[settings.paper_sources.Count-1];
457                         }
458                         
459                         if (defsource == null && settings.paper_sources.Count > 0)
460                                 return settings.paper_sources[0];
461                         return defsource;
462                 }
463
464                 /// <summary>
465                 /// </summary>
466                 /// <param name="load"></param>
467                 /// <param name="def_printer"></param>
468                 private static void LoadPrinters()
469                 {
470                         installed_printers.Clear ();            
471                         if (cups_installed == false)
472                                 return;
473                         
474                         IntPtr dests = IntPtr.Zero, ptr_printers;
475                         CUPS_DESTS printer;
476                         int n_printers = 0;
477                         int cups_dests_size = Marshal.SizeOf(typeof(CUPS_DESTS));
478                         string name, first, type, status, comment;
479                         first = type = status = comment = String.Empty;
480                         int state = 0;
481                         
482                         try {
483                                 n_printers = OpenDests (ref dests);
484
485                                 ptr_printers = dests;
486                                 for (int i = 0; i < n_printers; i++) {
487                                         printer = (CUPS_DESTS) Marshal.PtrToStructure (ptr_printers, typeof (CUPS_DESTS));
488                                         name = Marshal.PtrToStringAnsi (printer.name);
489
490                                         if (printer.is_default == 1)
491                                                 default_printer = name;
492                                 
493                                         if (first.Equals (String.Empty))
494                                                 first = name;
495                         
496                                         NameValueCollection options = LoadPrinterOptions(printer.options, printer.num_options);
497                                 
498                                         if (options["printer-state"] != null)
499                                                 state = Int32.Parse(options["printer-state"]);
500                                 
501                                         if (options["printer-comment"] != null)
502                                                 comment = options["printer-state"];
503
504                                         switch(state) {
505                                                 case 4:
506                                                         status = "Printing";
507                                                         break;
508                                                 case 5:
509                                                         status = "Stopped";
510                                                         break;
511                                                 default:
512                                                         status =  "Ready";
513                                                         break;
514                                         }
515                                 
516                                         installed_printers.Add (name, new SysPrn.Printer (String.Empty, type, status, comment));
517
518                                         ptr_printers = (IntPtr) ((long)ptr_printers + cups_dests_size);
519                                 }
520                         
521                         }
522                         finally {
523                                 CloseDests (ref dests, n_printers);
524                         }
525                         
526                         if (default_printer.Equals (String.Empty))
527                                 default_printer = first;
528                 }
529
530                 /// <summary>
531                 /// Gets a printer's settings for use in the print dialogue
532                 /// </summary>
533                 /// <param name="printer"></param>
534                 /// <param name="port"></param>
535                 /// <param name="type"></param>
536                 /// <param name="status"></param>
537                 /// <param name="comment"></param>
538                 internal override void GetPrintDialogInfo (string printer, ref string port, ref string type, ref string status, ref string comment) {
539                         int count = 0, state = -1;
540                         bool found = false;
541                         CUPS_DESTS cups_dests;
542                         IntPtr dests = IntPtr.Zero, ptr_printers, ptr_printer;
543                         int cups_dests_size = Marshal.SizeOf(typeof(CUPS_DESTS));
544                         
545                         if (cups_installed == false)
546                                 return;
547
548                         try {
549                                 count = OpenDests (ref dests);
550
551                                 if (count == 0)
552                                         return;
553
554                                 ptr_printers = dests;
555
556                                 for (int i = 0; i < count; i++) {
557                                         ptr_printer = (IntPtr) Marshal.ReadIntPtr (ptr_printers);
558                                         if (Marshal.PtrToStringAnsi (ptr_printer).Equals(printer)) {
559                                                 found = true;
560                                                 break;
561                                         }
562                                         ptr_printers = (IntPtr) ((long)ptr_printers + cups_dests_size);                         
563                                 }
564                         
565                                 if (!found)
566                                         return;
567                         
568                                 cups_dests = (CUPS_DESTS) Marshal.PtrToStructure (ptr_printers, typeof (CUPS_DESTS));
569                         
570                                 NameValueCollection options = LoadPrinterOptions(cups_dests.options, cups_dests.num_options);
571
572                                 if (options["printer-state"] != null)
573                                         state = Int32.Parse(options["printer-state"]);
574                         
575                                 if (options["printer-comment"] != null)
576                                         comment = options["printer-state"];
577
578                                 switch(state) {
579                                         case 4:
580                                                 status = "Printing";
581                                                 break;
582                                         case 5:
583                                                 status = "Stopped";
584                                                 break;
585                                         default:
586                                                 status =  "Ready";
587                                                 break;
588                                 }
589                         }
590                         finally {
591                                 CloseDests (ref dests, count);
592                         }
593                 }
594
595                 /// <summary>
596                 /// Returns the appropriate PaperKind for the width and height
597                 /// </summary>
598                 /// <param name="width"></param>
599                 /// <param name="height"></param>
600                 private PaperKind GetPaperKind (int width, int height)
601                 {
602                         if (width == 827 && height == 1169)
603                                 return PaperKind.A4;
604                         if (width == 583 && height == 827)
605                                 return PaperKind.A5;
606                         if (width == 717 && height == 1012)
607                                 return PaperKind.B5;
608                         if (width == 693 && height == 984)
609                                 return PaperKind.B5Envelope;
610                         if (width == 638 && height == 902)
611                                 return PaperKind.C5Envelope;
612                         if (width == 449 && height == 638)
613                                 return PaperKind.C6Envelope;
614                         if (width == 1700 && height == 2200)
615                                 return PaperKind.CSheet;
616                         if (width == 433 && height == 866)
617                                 return PaperKind.DLEnvelope;
618                         if (width == 2200 && height == 3400)
619                                 return PaperKind.DSheet;
620                         if (width == 3400 && height == 4400)
621                                 return PaperKind.ESheet;
622                         if (width == 725 && height == 1050)
623                                 return PaperKind.Executive;
624                         if (width == 850 && height == 1300)
625                                 return PaperKind.Folio;
626                         if (width == 850 && height == 1200)
627                                 return PaperKind.GermanStandardFanfold;
628                         if (width == 1700 && height == 1100)
629                                 return PaperKind.Ledger;
630                         if (width == 850 && height == 1400)
631                                 return PaperKind.Legal;
632                         if (width == 927 && height == 1500)
633                                 return PaperKind.LegalExtra;
634                         if (width == 850 && height == 1100)
635                                 return PaperKind.Letter;
636                         if (width == 927 && height == 1200)
637                                 return PaperKind.LetterExtra;
638                         if (width == 850 && height == 1269)
639                                 return PaperKind.LetterPlus;
640                         if (width == 387 && height == 750)
641                                 return PaperKind.MonarchEnvelope;
642                         if (width == 387 && height == 887)
643                                 return PaperKind.Number9Envelope;
644                         if (width == 413 && height == 950)
645                                 return PaperKind.Number10Envelope;
646                         if (width == 450 && height == 1037)
647                                 return PaperKind.Number11Envelope;
648                         if (width == 475 && height == 1100)
649                                 return PaperKind.Number12Envelope;
650                         if (width == 500 && height == 1150)
651                                 return PaperKind.Number14Envelope;
652                         if (width == 363 && height == 650)
653                                 return PaperKind.PersonalEnvelope;
654                         if (width == 1000 && height == 1100)
655                                 return PaperKind.Standard10x11;
656                         if (width == 1000 && height == 1400)
657                                 return PaperKind.Standard10x14;
658                         if (width == 1100 && height == 1700)
659                                 return PaperKind.Standard11x17;
660                         if (width == 1200 && height == 1100)
661                                 return PaperKind.Standard12x11;
662                         if (width == 1500 && height == 1100)
663                                 return PaperKind.Standard15x11;
664                         if (width == 900 && height == 1100)
665                                 return PaperKind.Standard9x11;
666                         if (width == 550 && height == 850)
667                                 return PaperKind.Statement;
668                         if (width == 1100 && height == 1700)
669                                 return PaperKind.Tabloid;
670                         if (width == 1487 && height == 1100)
671                                 return PaperKind.USStandardFanfold;
672
673                         return PaperKind.Custom;
674                 }
675
676                 #endregion
677
678                 #region Print job methods
679
680                 static string tmpfile;
681
682                 /// <summary>
683                 /// Gets a pointer to an options list parsed from the printer's current settings, to use when setting up the printing job
684                 /// </summary>
685                 /// <param name="printer_settings"></param>
686                 /// <param name="page_settings"></param>
687                 /// <param name="options"></param>
688                 internal static int GetCupsOptions (PrinterSettings printer_settings, PageSettings page_settings, out IntPtr options)
689                 {
690                         options = IntPtr.Zero;
691
692                         PaperSize size = page_settings.PaperSize;
693                         int width = size.Width * 72 / 100;
694                         int height = size.Height * 72 / 100;
695
696                         StringBuilder sb = new StringBuilder();
697                         sb.Append(
698                                 "copies=" + printer_settings.Copies + " " + 
699                                 "Collate=" + printer_settings.Collate + " " +
700                                 "ColorModel=" + (page_settings.Color ? "Color" : "Black") + " " +
701                                 "PageSize=" + String.Format ("Custom.{0}x{1}", width, height) + " " +
702                                 "landscape=" + page_settings.Landscape
703                         );
704                         
705                         if (printer_settings.CanDuplex)
706                         {
707                                 if (printer_settings.Duplex == Duplex.Simplex)
708                                         sb.Append(" Duplex=None");
709                                 else
710                                         sb.Append(" Duplex=DuplexNoTumble");                            
711                         }
712
713                         return cupsParseOptions (sb.ToString(), 0, ref options);
714                 }
715
716                 internal static bool StartDoc (GraphicsPrinter gr, string doc_name, string output_file)
717                 {
718                         DOCINFO doc = (DOCINFO) doc_info[gr.Hdc];
719                         doc.title = doc_name;
720                         return true;
721                 }
722
723                 internal static bool EndDoc (GraphicsPrinter gr)
724                 {
725                         DOCINFO doc = (DOCINFO) doc_info[gr.Hdc];
726
727                         gr.Graphics.Dispose (); // Dispose object to force surface finish
728                         
729                         IntPtr options;
730                         int options_count = GetCupsOptions (doc.settings, doc.default_page_settings, out options);
731
732                         cupsPrintFile (doc.settings.PrinterName, doc.filename, doc.title, options_count, options);
733                         cupsFreeOptions (options_count, options);
734                         doc_info.Remove (gr.Hdc);
735                         if (tmpfile != null) {
736                                 try { File.Delete (tmpfile); }
737                                 catch { }
738                         }
739                         return true;
740                 }
741
742                 internal static bool StartPage (GraphicsPrinter gr)
743                 {
744                         return true;
745                 }
746
747                 internal static bool EndPage (GraphicsPrinter gr)
748                 {
749                         GdipGetPostScriptSavePage (gr.Hdc);
750                         return true;
751                 }
752
753                 // Unfortunately, PrinterSettings and PageSettings couldn't be referencing each other,
754                 // thus we need to pass them separately
755                 internal static IntPtr CreateGraphicsContext (PrinterSettings settings, PageSettings default_page_settings)
756                 {
757                         IntPtr graphics = IntPtr.Zero;
758                         string name;
759                         if (!settings.PrintToFile) {
760                                 StringBuilder sb = new StringBuilder (1024);
761                                 int length = sb.Capacity;
762                                 cupsTempFile (sb, length);
763                                 name = sb.ToString ();
764                                 tmpfile = name;
765                         }
766                         else
767                                 name = settings.PrintFileName;
768
769                         PaperSize psize = default_page_settings.PaperSize;
770                         int width, height;
771                         if (default_page_settings.Landscape) { // Swap in case of landscape
772                                 width = psize.Height;
773                                 height = psize.Width;
774                         } else {
775                                 width = psize.Width;
776                                 height = psize.Height;
777                         }
778
779                         GdipGetPostScriptGraphicsContext (name,
780                                 width * 72 / 100,
781                                 height * 72 / 100, 
782                                 default_page_settings.PrinterResolution.X,
783                                 default_page_settings.PrinterResolution.Y, ref graphics);
784
785                         DOCINFO doc = new DOCINFO ();
786                         doc.filename = name;
787                         doc.settings = settings;
788                         doc.default_page_settings = default_page_settings;
789                         doc_info.Add (graphics, doc);
790
791                         return graphics;
792                 }
793
794                 #endregion
795
796                 #region DllImports
797
798                 [DllImport("libcups", CharSet=CharSet.Ansi)]
799                 static extern int cupsGetDests (ref IntPtr dests);
800
801 //              [DllImport("libcups", CharSet=CharSet.Ansi)]
802 //              static extern void cupsGetDest (string name, string instance, int num_dests, ref IntPtr dests);
803
804                 [DllImport("libcups")]
805                 static extern void cupsFreeDests (int num_dests, IntPtr dests);
806
807                 [DllImport("libcups", CharSet=CharSet.Ansi)]
808                 static extern IntPtr cupsTempFile (StringBuilder sb, int len);
809
810                 [DllImport("libcups", CharSet=CharSet.Ansi)]
811                 static extern IntPtr cupsGetDefault ();
812
813                 [DllImport("libcups", CharSet=CharSet.Ansi)]
814                 static extern int cupsPrintFile (string printer, string filename, string title, int num_options, IntPtr options);
815
816                 [DllImport("libcups", CharSet=CharSet.Ansi)]
817                 static extern IntPtr cupsGetPPD (string printer);
818
819                 [DllImport("libcups", CharSet=CharSet.Ansi)]
820                 static extern IntPtr ppdOpenFile (string filename);
821
822                 [DllImport("libcups", CharSet=CharSet.Ansi)]
823                 static extern IntPtr ppdFindOption (IntPtr ppd_file, string keyword);
824
825                 [DllImport("libcups")]
826                 static extern void ppdClose (IntPtr ppd);
827
828                 [DllImport ("libcups", CharSet=CharSet.Ansi)]
829                 static extern int cupsParseOptions (string arg, int number_of_options, ref IntPtr options);
830
831                 [DllImport("libcups")]
832                 static extern void cupsFreeOptions (int number_options, IntPtr options);
833
834                 [DllImport("gdiplus.dll", CharSet=CharSet.Ansi)]
835                 static extern int GdipGetPostScriptGraphicsContext (string filename, int with, int height, double dpix, double dpiy, ref IntPtr graphics);
836
837                 [DllImport("gdiplus.dll")]
838                 static extern int GdipGetPostScriptSavePage (IntPtr graphics);
839
840                 #endregion
841
842                 #region Struct
843                 public struct DOCINFO
844                 {
845                         public PrinterSettings settings;
846                         public PageSettings default_page_settings;
847                         public string title;
848                         public string filename;
849                 }
850
851                 public struct PPD_SIZE
852                 {
853                         public  int marked;
854                         [MarshalAs(UnmanagedType.ByValTStr, SizeConst=42)]
855                         public  string name;
856                         public  float width;
857                         public  float length;
858                         public  float left;
859                         public  float bottom;
860                         public  float right;
861                         public  float top;
862                 }
863
864                 public struct PPD_GROUP
865                 {
866                         [MarshalAs(UnmanagedType.ByValTStr, SizeConst=40)]
867                         public string text;
868                         [MarshalAs(UnmanagedType.ByValTStr, SizeConst=42)]
869                         public string name;
870                         public int num_options;
871                         public IntPtr options;
872                         public int num_subgroups;
873                         public IntPtr subgrups;
874                 }
875
876                 public struct PPD_OPTION
877                 {
878                         public byte     conflicted;
879                         [MarshalAs(UnmanagedType.ByValTStr, SizeConst=41)]
880                         public string   keyword;
881                         [MarshalAs(UnmanagedType.ByValTStr, SizeConst=41)]
882                         public string   defchoice;
883                         [MarshalAs(UnmanagedType.ByValTStr, SizeConst=81)]
884                         public string   text;
885                         public int      ui;
886                         public int      section;
887                         public float    order;
888                         public int      num_choices;
889                         public IntPtr   choices;
890                 }
891
892                 public struct PPD_CHOICE
893                 {
894                         public byte     marked;
895                         [MarshalAs(UnmanagedType.ByValTStr, SizeConst=41)]
896                         public string   choice;
897                         [MarshalAs(UnmanagedType.ByValTStr, SizeConst=81)]
898                         public string   text;
899                         public IntPtr   code;
900                         public IntPtr   option;
901                 }
902
903                 public struct PPD_FILE
904                 {
905                         public int      language_level;
906                         public int      color_device;
907                         public int      variable_sizes;
908                         public int      accurate_screens;
909                         public int      contone_only;
910                         public int      landscape;
911                         public int      model_number;
912                         public int      manual_copies;
913                         public int      throughput;
914                         public int      colorspace;
915                         public IntPtr   patches;
916                         public int      num_emulations;
917                         public IntPtr   emulations;
918                         public IntPtr   jcl_begin;
919                         public IntPtr   jcl_ps;
920                         public IntPtr   jcl_end;
921                         public IntPtr   lang_encoding;
922                         public IntPtr   lang_version;
923                         public IntPtr   modelname;
924                         public IntPtr   ttrasterizer;
925                         public IntPtr   manufacturer;
926                         public IntPtr   product;
927                         public IntPtr   nickname;
928                         public IntPtr   shortnickname;
929                         public int      num_groups;
930                         public IntPtr   groups;
931                         public int      num_sizes;
932                         public IntPtr   sizes;
933
934                         /* There is more data after this that we are not using*/
935                 }
936
937
938                 public struct CUPS_OPTIONS
939                 {
940                         public IntPtr name;
941                         public IntPtr val;
942                 }
943                 
944                 public struct CUPS_DESTS
945                 {
946                         public IntPtr   name;
947                         public IntPtr   instance;
948                         public int      is_default;
949                         public int      num_options;
950                         public IntPtr   options;
951                 }
952                 
953                 #endregion
954         }
955
956         class GlobalPrintingServicesUnix : GlobalPrintingServices
957         {
958                 internal override PrinterSettings.StringCollection InstalledPrinters {
959                         get {
960                                 return PrintingServicesUnix.InstalledPrinters;
961                         }
962                 }
963
964                 internal override IntPtr CreateGraphicsContext (PrinterSettings settings, PageSettings default_page_settings)
965                 {
966                         return PrintingServicesUnix.CreateGraphicsContext (settings, default_page_settings);
967                 }
968
969                 internal override bool StartDoc (GraphicsPrinter gr, string doc_name, string output_file)
970                 {
971                         return PrintingServicesUnix.StartDoc (gr, doc_name, output_file);
972                 }
973
974                 internal override bool EndDoc (GraphicsPrinter gr)
975                 {
976                         return PrintingServicesUnix.EndDoc (gr);
977                 }
978
979                 internal override bool StartPage (GraphicsPrinter gr)
980                 {
981                         return PrintingServicesUnix.StartPage (gr);
982                 }
983
984                 internal override bool EndPage (GraphicsPrinter gr)
985                 {
986                         return PrintingServicesUnix.EndPage (gr);
987                 }
988         }
989 }
990