summaryrefslogtreecommitdiff
path: root/platform/winrt/gsview/ghostsharp.cs
blob: 4b0cf311d16dae45822795b365570b974473ade2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;using System.Runtime.InteropServices;
using System.IO;
using System.Security;
using System.ComponentModel;

namespace gsview
{
	/* Warning. This list is in a particular order. The devices before 
	 * psdrgb do not support multiple pages.  Those including psdrgb do 
	 * support multiple pages.  This is used in the conversion process.
	 * Also note that mupdf devices go at the beginning of the list */

	public enum gsDevice_t
	{
		svg, 
		pnm,
		pclbitmap,
		pwg,
		bmp16,  /* Add mupdf devices before this one */
		bmp16m,
		bmp256,
		bmp32b,
		bmpgray,
		bmpmono,
		eps2write,
		jpeg,
		jpegcmyk,
		jpeggray,
		pamcmyk32,
		pamcmyk4,
		pbm,
		pgm,
		png16,
		png16m,
		png256,
		pngalpha,
		pnggray,
		pngmono,
		psdcmyk,
		psdrgb,  /* Add single page gs devices before this device */
		pdfwrite,
		ps2write,
		pxlcolor,
		pxlmono,
		tiff12nc,
		tiff24nc,
		tiff32nc,
		tiff64nc,
		tiffcrle,
		tiffg3,
		tiffg32d,
		tiffg4,
		tiffgray,
		tifflzw,
		tiffpack,
		tiffsep,
		txtwrite,
		xpswrite
	};

	public enum GS_Task_t
	{
		PS_DISTILL,
		CREATE_XPS,
		SAVE_RESULT
	}

	public enum GS_Result_t
	{
		gsOK,
		gsFAILED,
		gsCANCELLED
	}

	/* Parameters */
	public struct gsParams_t
	{
		public String init_string;
		public String init_file;
		public int resolution;
		public gsDevice_t device;
		public String devicename;
		public String outputfile;
		public String inputfile;
		public GS_Task_t task;
		public GS_Result_t result;
		public int num_pages;
		public String options;
		public bool need_multi_page;
		public System.Collections.IList pages;
		public int firstpage;
		public int lastpage;
		public int currpage; /* valid only when pages != null */
	};

	public class gsEventArgs : EventArgs
	{
		private bool m_completed;
		private int m_progress;
		private gsParams_t m_param;

		public bool Completed
		{
			get { return m_completed; }
		}

		public gsParams_t Params
		{
			get { return m_param; }
		}

		public int Progress
		{
			get { return m_progress; }
		}

		public gsEventArgs(bool completed, int progress, gsParams_t param)
		{
			m_completed = completed;
			m_progress = progress;
			m_param = param;
		}
	}

	/* from gs */
	public struct gsapi_revision_t 
	{
		public IntPtr product;
		public IntPtr copyright;
		public int revision;
		public int revisiondate;
	}

	public enum gsEncoding {
		GS_ARG_ENCODING_LOCAL = 0,
		GS_ARG_ENCODING_UTF8 = 1,
		GS_ARG_ENCODING_UTF16LE = 2
	};

	public enum gsStatus
	{
		GS_READY,
		GS_BUSY,
		GS_ERROR
	};

	static class gsConstants
	{
		public const int E_QUIT = -101;
		public const int GS_READ_BUFFER = 32768;
	}

	[SuppressUnmanagedCodeSecurity]
	class ghostsharp
	{
		/* Callback proto for stdio */
		public delegate int gsStdIOHandler(IntPtr caller_handle, IntPtr buffer, 
			int len);

		/* Ghostscript API */
		[DllImport("gsdll64.dll", CharSet = CharSet.Ansi,
			CallingConvention = CallingConvention.StdCall)]
		public static extern int gsapi_revision(ref gsapi_revision_t vers, int size);

		[DllImport("gsdll64.dll", CharSet = CharSet.Ansi,
			CallingConvention = CallingConvention.StdCall)]
		public static extern int gsapi_new_instance(out IntPtr pinstance, 
			IntPtr caller_handle);

		[DllImport("gsdll64.dll", CharSet = CharSet.Ansi,
			CallingConvention = CallingConvention.StdCall)]
		public static extern void gsapi_delete_instance(IntPtr instance);

		[DllImport("gsdll64.dll", CharSet = CharSet.Ansi,
			CallingConvention = CallingConvention.StdCall)]
		public static extern int gsapi_init_with_args(IntPtr instance, int argc, 
			IntPtr argv);

		[DllImport("gsdll64.dll", CharSet = CharSet.Ansi,
			CallingConvention = CallingConvention.StdCall)]
		public static extern int gsapi_exit(IntPtr instance);

		[DllImport("gsdll64.dll", CharSet = CharSet.Ansi,
			CallingConvention = CallingConvention.StdCall)]
		public static extern int gsapi_set_arg_encoding(IntPtr instance, 
			int encoding);

		[DllImport("gsdll64.dll", CharSet = CharSet.Ansi,
			CallingConvention = CallingConvention.StdCall)]
			public static extern int gsapi_set_stdio(IntPtr instance, 
			gsStdIOHandler stdin, gsStdIOHandler stdout, gsStdIOHandler stderr);

		[DllImport("gsdll64.dll", CharSet = CharSet.Ansi,
			CallingConvention = CallingConvention.StdCall)]
		public static extern void gsapi_run_string_begin(IntPtr instance,
			int usererr, ref int exitcode);

		[DllImport("gsdll64.dll", CharSet = CharSet.Ansi,
		CallingConvention = CallingConvention.StdCall)]
		public static extern void gsapi_run_string_continue(IntPtr instance, 
			IntPtr command, int count, int usererr, ref int exitcode);

		[DllImport("gsdll64.dll", CharSet = CharSet.Ansi,
			CallingConvention = CallingConvention.StdCall)]
		public static extern void gsapi_run_string_end(IntPtr instance,
			int usererr, ref int exitcode);


		/* In case the DLL is not found we need to wrap the methods up with
		 * a try/catch */
		private int tc_gsapi_revision(ref gsapi_revision_t vers, int size)
		{
			int code = 0;
			try
			{
				code = gsapi_revision(ref vers, size);
			}
			catch (DllNotFoundException)
			{
				/* DLL not found */
				String output = "DllNotFoundException: Ghostscript DLL not found";
				gsDLLProblemMain(this, output);
				return -1;
			}
			catch (BadImageFormatException)
			{
				/* Using 32 bit with 64 or vice versa */
				String output = "BadImageFormatException: Incorrect Ghostscript DLL";
				gsDLLProblemMain(this, output);
				return -1;
			}
			return code;
		}

		private int tc_gsapi_new_instance(out IntPtr pinstance, IntPtr caller_handle)
		{
			int code = 0;
			pinstance = IntPtr.Zero;
			try
			{
				code = gsapi_new_instance(out pinstance, caller_handle);
			}
			catch (DllNotFoundException)
			{
				/* DLL not found */
				String output = "DllNotFoundException: Ghostscript DLL not found";
				gsDLLProblemMain(this, output);
				return -1;
			}
			catch (BadImageFormatException)
			{
				/* Using 32 bit with 64 or vice versa */
				String output = "BadImageFormatException: Incorrect Ghostscript DLL";
				gsDLLProblemMain(this, output);
				return -1;
			}
			return code;
		}

		private int tc_gsapi_delete_instance(IntPtr instance)
		{
			try
			{
				gsapi_delete_instance(instance);
			}
			catch (DllNotFoundException)
			{
				/* DLL not found */
				String output = "DllNotFoundException: Ghostscript DLL not found";
				gsDLLProblemMain(this, output);
				return -1;
			}
			catch (BadImageFormatException)
			{
				/* Using 32 bit with 64 or vice versa */
				String output = "BadImageFormatException: Incorrect Ghostscript DLL";
				gsDLLProblemMain(this, output);
				return -1;
			}
			return 0;
		}

		private int tc_gsapi_init_with_args(IntPtr instance, int argc, IntPtr argv)
		{
			int code;
			try
			{
				code = gsapi_init_with_args(instance, argc, argv);
			}
			catch (DllNotFoundException)
			{
				/* DLL not found */
				String output = "DllNotFoundException: Ghostscript DLL not found";
				gsDLLProblemMain(this, output);
				return -1;
			}
			catch (BadImageFormatException)
			{
				/* Using 32 bit with 64 or vice versa */
				String output = "BadImageFormatException: Incorrect Ghostscript DLL";
				gsDLLProblemMain(this, output);
				return -1;
			}
			return code;
		}

		private int tc_gsapi_exit(IntPtr instance)
		{
			int code;
			try
			{
				code = gsapi_exit(instance);
			}
			catch (DllNotFoundException)
			{
				/* DLL not found */
				String output = "DllNotFoundException: Ghostscript DLL not found";
				gsDLLProblemMain(this, output);
				return -1;
			}
			catch (BadImageFormatException)
			{
				/* Using 32 bit with 64 or vice versa */
				String output = "BadImageFormatException: Incorrect Ghostscript DLL";
				gsDLLProblemMain(this, output);
				return -1;
			}
			return code;
		}

		private int tc_gsapi_set_arg_encoding(IntPtr instance, int encoding)
		{
			int code;
			try
			{
				code = gsapi_set_arg_encoding(instance, encoding);
			}
			catch (DllNotFoundException)
			{
				/* DLL not found */
				String output = "DllNotFoundException: Ghostscript DLL not found";
				gsDLLProblemMain(this, output);
				return -1;
			}
			catch (BadImageFormatException)
			{
				/* Using 32 bit with 64 or vice versa */
				String output = "BadImageFormatException: Incorrect Ghostscript DLL";
				gsDLLProblemMain(this, output);
				return -1;
			}
			return code;
		}

		private int tc_gsapi_set_stdio(IntPtr instance, gsStdIOHandler stdin, 
			gsStdIOHandler stdout, gsStdIOHandler stderr)
		{
			int code;
			try
			{
				code = gsapi_set_stdio(instance, stdin, stdout, stderr);
			}
			catch (DllNotFoundException)
			{
				/* DLL not found */
				String output = "DllNotFoundException: Ghostscript DLL not found";
				gsDLLProblemMain(this, output);
				return -1;
			}
			catch (BadImageFormatException)
			{
				/* Using 32 bit with 64 or vice versa */
				String output = "BadImageFormatException: Incorrect Ghostscript DLL";
				gsDLLProblemMain(this, output);
				return -1;
			}
			return code;
		}

		private int tc_gsapi_run_string_begin(IntPtr instance, int usererr, 
			ref int exitcode)
		{
			try
			{
				gsapi_run_string_begin(instance, usererr, ref exitcode);
			}
			catch (DllNotFoundException)
			{
				/* DLL not found */
				String output = "DllNotFoundException: Ghostscript DLL not found";
				gsDLLProblemMain(this, output);
				return -1;
			}
			catch (BadImageFormatException)
			{
				/* Using 32 bit with 64 or vice versa */
				String output = "BadImageFormatException: Incorrect Ghostscript DLL";
				gsDLLProblemMain(this, output);
				return -1;
			}
			return 0;
		}

		private int tc_gsapi_run_string_continue(IntPtr instance, IntPtr command, 
			int count, int usererr, ref int exitcode)
		{
			try
			{
				gsapi_run_string_continue(instance, command, count, usererr, 
					ref exitcode);
			}
			catch (DllNotFoundException)
			{
				/* DLL not found */
				String output = "DllNotFoundException: Ghostscript DLL not found";
				gsDLLProblemMain(this, output);
				return -1;
			}
			catch (BadImageFormatException)
			{
				/* Using 32 bit with 64 or vice versa */
				String output = "BadImageFormatException: Incorrect Ghostscript DLL";
				gsDLLProblemMain(this, output);
				return -1;
			}
			return 0;
		}

		private int tc_gsapi_run_string_end(IntPtr instance, int usererr, 
			ref int exitcode)
		{
			try
			{
				gsapi_run_string_end(instance, usererr, ref exitcode);
			}
			catch (DllNotFoundException)
			{
				/* DLL not found */
				String output = "DllNotFoundException: Ghostscript DLL not found";
				gsDLLProblemMain(this, output);
				return -1;
			}
			catch (BadImageFormatException)
			{
				/* Using 32 bit with 64 or vice versa */
				String output = "BadImageFormatException: Incorrect Ghostscript DLL";
				gsDLLProblemMain(this, output);
				return -1;
			}
			return 0;
		}

		private int StdInCallback(IntPtr handle, IntPtr pointer, int count)
		{
			String output = Marshal.PtrToStringAnsi(pointer);
			return count;
		}

		private int StdOutCallback(IntPtr handle, IntPtr pointer, int count)
		{
			String output = Marshal.PtrToStringAnsi(pointer);
			gsIOUpdateMain(this, output, count);
			if (m_params.task != GS_Task_t.PS_DISTILL)
			{
				/* See if we have a page number */
				if (count >= 7 && output.Substring(0, 4) == "Page")
				{
					String page = output.Substring(5, count - 6);
					int numVal;
					try
					{
						double perc = 0.0;
						numVal = System.Convert.ToInt32(page);
						if (m_params.firstpage == -1 && m_params.lastpage == -1 &&
							m_params.pages == null)
						{
							/* Doing full document */
							perc = 100.0 * (double)numVal / (double)m_params.num_pages;
						}
						else
						{
							if (m_params.pages != null)
							{
								perc = 100.0 * ((double)numVal - m_params.currpage) / (double)m_params.num_pages;
								m_params.currpage = m_params.currpage + 1;
							}
							else
							{
								/* continugous set of pages */
								perc = 100.0 * ((double)numVal - m_params.firstpage + 1) / (double)m_params.num_pages;
							}
						}
						m_worker.ReportProgress((int)perc);
					}
					catch (FormatException e)
					{
						Console.WriteLine("XPSPrint Error: Input string is not a sequence of digits.");
					}
					catch (OverflowException e)
					{
						Console.WriteLine("XPSPrint Error: The number cannot fit in an Int32.");
					}
					
				}
			}
			return count;
		}

		private int StdErrCallback(IntPtr handle, IntPtr pointer, int count)
		{
			String output = Marshal.PtrToStringAnsi(pointer);
			gsIOUpdateMain(this, output, count);
			return count;
		}

		IntPtr gsInstance;
		BackgroundWorker m_worker;
		gsParams_t m_params;
		/* Callbacks to Main */
		internal delegate void gsDLLProblem(object gsObject, String mess);
		internal event gsDLLProblem gsDLLProblemMain;
		internal delegate void gsIOCallBackMain(object gsObject, String mess, int len);
		internal event gsIOCallBackMain gsIOUpdateMain;
		internal delegate void gsCallBackMain(object gsObject, gsEventArgs info);
		internal event gsCallBackMain gsUpdateMain;

		public ghostsharp()
		{
			m_worker = null;
			gsInstance = IntPtr.Zero;
		}

		private List<String> GetOptions(String options)
		{
			List<String> optionlist = new List<String>();

			if (options != "")
			{
				string[] words = options.Split(' ');
				for (int k = 0; k < words.Length; k++)
				{
					if (words[k].Length > 0)
					{
						optionlist.Add(words[k]);
					}
				}
			}
			return optionlist;
		}

		/* A standard command line approach to using gs API */
		private void gsWork1(object sender, DoWorkEventArgs e)
		{
			gsParams_t gsparams = (gsParams_t) e.Argument;
			String out_file = gsparams.outputfile;
			String in_file = gsparams.inputfile;
			int num_params = 8;  /* base number */
			int rend_count = 1;
			String options;
			int count;
			List<String> optionlist;

			optionlist = GetOptions(gsparams.options);
			num_params = num_params + optionlist.Count;
			if (gsparams.pages != null)
			{
				rend_count = gsparams.pages.Count;
				num_params = num_params + 2;
			}
			if (gsparams.init_file != null)
				num_params = num_params + 1;
			if (gsparams.init_string != null)
				num_params = num_params + 2;

			var argParam = new GCHandle[num_params];
			var argPtrs = new IntPtr[num_params];
			String[] strParams = new String[num_params];
			List<byte[]> CharacterArray = new List<byte[]>(num_params);
			GCHandle argPtrsStable;

			/* New instance */
			int code = tc_gsapi_new_instance(out gsInstance, IntPtr.Zero);
			if (code < 0)
			{
				gsparams.result = GS_Result_t.gsFAILED;
				e.Result = gsparams;
				return;
			}

			var RaiseStdInCallback = new gsStdIOHandler(StdInCallback);
			var RaiseStdOutCallback = new gsStdIOHandler(StdOutCallback);
			var RaiseStdErrCallback = new gsStdIOHandler(StdErrCallback);

			var stdInPtr = Marshal.GetFunctionPointerForDelegate(RaiseStdInCallback);
			var stdOutPtr = Marshal.GetFunctionPointerForDelegate(RaiseStdOutCallback);
			var stdErrPtr = Marshal.GetFunctionPointerForDelegate(RaiseStdErrCallback);

			// Setup stdio callback functions
			code = tc_gsapi_set_stdio(gsInstance, RaiseStdInCallback, RaiseStdOutCallback, RaiseStdErrCallback);

			code = tc_gsapi_set_arg_encoding(gsInstance, (int)gsEncoding.GS_ARG_ENCODING_UTF8);

			if (code == 0)
			{
				for (int jj = 0; jj < rend_count; jj++)
				{
					strParams[0] = "gs";   /* This does not matter */
					strParams[1] = "-dNOPAUSE";
					strParams[2] = "-dBATCH";
					if (gsparams.devicename != null)
					{
						strParams[3] = "-sDEVICE=" + gsparams.devicename;
					}
					else
					{
						strParams[3] = "-sDEVICE=" + Enum.GetName(typeof(gsDevice_t), gsparams.device);
					}
					strParams[4] = "-r" + gsparams.resolution;
					/* Create temp file if file not specified */
					if (out_file == null)
					{
						out_file = Path.GetTempFileName();
						gsparams.outputfile = out_file;
					}
					count = 5;
					/* Add in the options */
					for (int kk = 0; kk < optionlist.Count; kk++)
					{
						strParams[count] = optionlist[kk];
						count++;
					}
					/* We have discontinuous page selection */
					if (gsparams.pages != null)
					{
						String firstpage, lastpage;
						options = gsparams.options;
						SelectPage curr_page = (SelectPage)(gsparams.pages[jj]);
						firstpage = "-dFirstPage=" + curr_page.Page;
						lastpage =  "-dLastPage=" + curr_page.Page;
						strParams[count] = firstpage;
						count++;
						strParams[count] = lastpage;
						count++;
						/* Look for file extension. */
						string extension = System.IO.Path.GetExtension(out_file);
						int len = extension.Length;
						String new_out_file = out_file.Substring(0, out_file.Length - len);
						strParams[count] = "-o" + new_out_file + "_page" + curr_page.Page + extension;
					}
					else
					{
						if (gsparams.need_multi_page)
						{
							/* Look for file extension. */
							string extension = System.IO.Path.GetExtension(out_file);
							int len = extension.Length;
							String new_out_file = out_file.Substring(0, out_file.Length - len);
							strParams[count] = "-o" + new_out_file + "_page%d" + extension;
						}
						else
							strParams[count] = "-o" + out_file;
					}
					if (gsparams.init_string != null)
					{
						count++;
						strParams[count] = "-c";
						count++;
						strParams[count] = gsparams.init_string;
					}
					count++;
					strParams[count] = "-f";
					if (gsparams.init_file != null)
					{
						count++;
						strParams[count] = gsparams.init_file;
					}
					count++;
					strParams[count] = in_file;

					/* Now convert our Strings to char* and get pinned handles to these.
					 * This keeps the c# GC from moving stuff around on us */
					for (int k = 0; k < num_params; k++)
					{
						CharacterArray.Add(System.Text.Encoding.UTF8.GetBytes(strParams[k].ToCharArray()));
						argParam[k] = GCHandle.Alloc(CharacterArray[k], GCHandleType.Pinned);
						argPtrs[k] = argParam[k].AddrOfPinnedObject();
					}
					/* Also stick the array of pointers into memory that will not be GCd */
					argPtrsStable = GCHandle.Alloc(argPtrs, GCHandleType.Pinned);

					code = tc_gsapi_init_with_args(gsInstance, num_params, argPtrsStable.AddrOfPinnedObject());

					/* All the pinned items need to be freed so the GC can do its job */
					for (int k = 0; k < num_params; k++)
					{
						argParam[k].Free();
					}
					argPtrsStable.Free();
					/* Free the character array list in case we have multiple runs */
					CharacterArray.Clear();
					
					if (code < 0)
						break;
				}
			}

			int code1 = tc_gsapi_exit(gsInstance);
			if ((code == 0) || (code == gsConstants.E_QUIT))
				code = code1;

			RaiseStdInCallback = null;
			RaiseStdOutCallback = null;
			RaiseStdErrCallback = null;

			tc_gsapi_delete_instance(gsInstance);
			if ((code == 0) || (code == gsConstants.E_QUIT))
			{
				gsparams.result = GS_Result_t.gsOK;
				e.Result = gsparams;
				return;
			}

			gsparams.result = GS_Result_t.gsFAILED;
			e.Result = gsparams;
			return;
		}

		/* Feeding gs piecemeal so that we can have some progress callback */
		private void gsWork2(object sender, DoWorkEventArgs e)
		{
			gsParams_t Params = (gsParams_t)e.Argument;
			String out_file = Params.outputfile;
			String in_file = Params.inputfile;
			int num_params = 6;
			if (Params.options.Length > 0)
				num_params = num_params + 1;

			int exitcode = 0;
			var argParam = new GCHandle[num_params];
			var argPtrs = new IntPtr[num_params];
			var Feed = new GCHandle();
			var FeedPtr = new IntPtr();
			String[] strParams = new String[num_params];
			List<byte[]> CharacterArray = new List<byte[]>(num_params);
			GCHandle argPtrsStable;
			Byte[] Buffer = new Byte[gsConstants.GS_READ_BUFFER];
			BackgroundWorker worker = sender as BackgroundWorker;

			/* Open the file */
			var fs = new FileStream(in_file, FileMode.Open);
			var len = (int) fs.Length;
			/* New instance */
			int code = tc_gsapi_new_instance(out gsInstance, IntPtr.Zero);
			if (code < 0)
			{
				Params.result = GS_Result_t.gsFAILED;
				e.Result = Params;
				return;
			}

			var RaiseStdInCallback = new gsStdIOHandler(StdInCallback);
			var RaiseStdOutCallback = new gsStdIOHandler(StdOutCallback);
			var RaiseStdErrCallback = new gsStdIOHandler(StdErrCallback);

			var stdInPtr = Marshal.GetFunctionPointerForDelegate(RaiseStdInCallback);
			var stdOutPtr = Marshal.GetFunctionPointerForDelegate(RaiseStdOutCallback);
			var stdErrPtr = Marshal.GetFunctionPointerForDelegate(RaiseStdErrCallback);

			// Setup stdio callback functions
			code = tc_gsapi_set_stdio(gsInstance, RaiseStdInCallback, RaiseStdOutCallback, RaiseStdErrCallback);

			code = tc_gsapi_set_arg_encoding(gsInstance, (int)gsEncoding.GS_ARG_ENCODING_UTF8);

			if (code == 0)
			{
				strParams[0] = "gs";   /* This does not matter */
				strParams[1] = "-dNOPAUSE";
				strParams[2] = "-dBATCH";
				if (Params.devicename != null)
				{
					strParams[3] = "-sDEVICE=" + Params.devicename;
				}
				else
				{
					strParams[3] = "-sDEVICE=" + Enum.GetName(typeof(gsDevice_t), Params.device);
				}
				strParams[4] = "-r" + Params.resolution;
				/* Create temp file if file not specified */
				if (out_file == null)
				{
					out_file = Path.GetTempFileName();
					Params.outputfile = out_file;
				}
				if (Params.options.Length > 0)
				{
					strParams[5] = Params.options;
					strParams[6] = "-o" + out_file;
				} else 
					strParams[5] = "-o" + out_file;

				/* Now convert our Strings to char* and get pinned handles to these.
					* This keeps the c# GC from moving stuff around on us */
				for (int k = 0; k < num_params; k++)
				{
					CharacterArray.Add(System.Text.Encoding.UTF8.GetBytes(strParams[k].ToCharArray()));
					argParam[k] = GCHandle.Alloc(CharacterArray[k], GCHandleType.Pinned);
					argPtrs[k] = argParam[k].AddrOfPinnedObject();
				}
				/* Also stick the array of pointers into memory that will not be GCd */
				argPtrsStable = GCHandle.Alloc(argPtrs, GCHandleType.Pinned);

				code = tc_gsapi_init_with_args(gsInstance, num_params, argPtrsStable.AddrOfPinnedObject());

				/* First pin the data buffer */
				Feed = GCHandle.Alloc(Buffer, GCHandleType.Pinned);
				FeedPtr = Feed.AddrOfPinnedObject();

				/* Now start feeding the input piece meal and do a call back
					* with our progress */
				if (code == 0)
				{
					int count;
					double perc;
					int total = 0;

					tc_gsapi_run_string_begin(gsInstance, 0, ref exitcode);
					while ((count = fs.Read(Buffer, 0, gsConstants.GS_READ_BUFFER)) > 0)
					{
						tc_gsapi_run_string_continue(gsInstance, FeedPtr, count, 0, ref exitcode);
						if (exitcode < 0)
						{
							code = exitcode;
							break;
						}
						total =  total + count;
						perc = 100.0 * (double) total / (double) len;
						worker.ReportProgress((int)perc);
						if (worker.CancellationPending == true)
						{
							e.Cancel = true;
							break;
						}
					}
					tc_gsapi_run_string_end(gsInstance, 0, ref exitcode);
					if (code == 0)
						code = exitcode;
				}

				/* All the pinned items need to be freed so the GC can do its job */
				for (int k = 0; k < num_params; k++)
				{
					argParam[k].Free();
				}
				argPtrsStable.Free();
				Feed.Free();
			}

			int code1 = tc_gsapi_exit(gsInstance);
			if ((code == 0) || (code == gsConstants.E_QUIT))
				code = code1;

			tc_gsapi_delete_instance(gsInstance);
			if ((code == 0) || (code == gsConstants.E_QUIT))
			{
				Params.result = GS_Result_t.gsOK;
				e.Result = Params;
				return;
			}
			Params.result = GS_Result_t.gsFAILED;
			e.Result = Params;
			return;
		}

		/* Callback */
		private void gsCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			gsParams_t Value;
			gsEventArgs info;
			gsParams_t Params = (gsParams_t) e.Result;

			if (Params.task == GS_Task_t.PS_DISTILL)
				m_worker.DoWork -= new DoWorkEventHandler(gsWork2);
			else
				m_worker.DoWork -= new DoWorkEventHandler(gsWork1);

			if (e.Cancelled)
			{
				Value = new gsParams_t();
				Value.result = GS_Result_t.gsCANCELLED;
				info = new gsEventArgs(true, 100, Value);
			} 
			else
			{
				Value = (gsParams_t)e.Result;
				info = new gsEventArgs(true, 100, Value);
			}
			gsUpdateMain(this, info);
		}

		private void gsProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			/* Callback with progress */
			gsParams_t Value = new gsParams_t();
			gsEventArgs info = new gsEventArgs(false, e.ProgressPercentage, Value);
			gsUpdateMain(this, info);
		}

		public gsStatus DistillPS(String fileName, int resolution)
		{
			gsParams_t gsparams = new gsParams_t(); ;

			gsparams.init_file = null;
			gsparams.init_string = null;
			gsparams.device = gsDevice_t.pdfwrite;
			gsparams.devicename = null;
			gsparams.outputfile = null;
			gsparams.resolution = resolution;
			gsparams.inputfile = fileName;
			gsparams.num_pages = -1;
			gsparams.task = GS_Task_t.PS_DISTILL;
			gsparams.options = "";
			gsparams.need_multi_page = false;
			gsparams.pages = null;
			gsparams.firstpage = -1;
			gsparams.lastpage = -1;
			gsparams.currpage = -1;
			return RunGhostscript(gsparams);
		}

		public gsStatus CreateXPS(String fileName, int resolution, int num_pages)
		{
			gsParams_t gsparams = new gsParams_t();

			gsparams.init_file = null;
			gsparams.init_string = null;
			gsparams.device = gsDevice_t.xpswrite;
			gsparams.outputfile = null;
			gsparams.resolution = resolution;
			gsparams.inputfile = fileName;
			gsparams.task = GS_Task_t.CREATE_XPS;
			gsparams.num_pages = num_pages;
			gsparams.options = "";
			gsparams.need_multi_page = false;
			gsparams.pages = null;
			gsparams.firstpage = -1;
			gsparams.lastpage = -1;
			gsparams.currpage = -1;
			return RunGhostscript(gsparams);
		}

		public gsStatus Convert(String fileName, String options, String device, 
								String outputFile, int num_pages, int resolution,
								bool multi_page_needed, System.Collections.IList pages, 
								int firstpage, int lastpage, String init_file, String init_string)
		{
			gsParams_t gsparams = new gsParams_t();

			gsparams.init_file = init_file;
			gsparams.init_string = init_string;
			gsparams.devicename = device;
			gsparams.outputfile = outputFile;
			gsparams.inputfile = fileName;
			gsparams.task = GS_Task_t.SAVE_RESULT;
			gsparams.num_pages = num_pages;
			gsparams.options = options;
			gsparams.resolution = resolution;
			gsparams.need_multi_page = multi_page_needed;
			gsparams.pages = pages;
			gsparams.firstpage = firstpage;
			gsparams.lastpage = lastpage;
			gsparams.currpage = 1;
			return RunGhostscript(gsparams);
		}

		public gsStatus GetStatus()
		{
			if (m_worker != null && m_worker.IsBusy)
				return gsStatus.GS_BUSY;
			else
				return gsStatus.GS_READY;
		}

		public String GetVersion()
		{
			gsapi_revision_t vers;
			vers.copyright = IntPtr.Zero;
			vers.product = IntPtr.Zero;
			vers.revision = 0;
			vers.revisiondate = 0;
			int size = System.Runtime.InteropServices.Marshal.SizeOf(vers);

			if (tc_gsapi_revision(ref vers, size) == 0)
			{
				String product = Marshal.PtrToStringAnsi(vers.product);
				String output;
				int major = vers.revision / 100;
				int minor = vers.revision - major * 100;
				String versnum = major + "." + minor;
				output = product + " " + versnum;
				return output;
			}
			else
				return null;
		}

		private gsStatus RunGhostscript(gsParams_t Params)
		{
			try
			{
				if (m_worker != null && m_worker.IsBusy)
				{
					m_worker.CancelAsync();
					return gsStatus.GS_BUSY;
				}
				if (m_worker == null)
				{
					m_worker = new BackgroundWorker();
					m_worker.WorkerReportsProgress = true;
					m_worker.WorkerSupportsCancellation = true;
					m_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(gsCompleted);
					m_worker.ProgressChanged += new ProgressChangedEventHandler(gsProgressChanged);
				}
				if (Params.task == GS_Task_t.PS_DISTILL)
					m_worker.DoWork += new DoWorkEventHandler(gsWork2);
				else
					m_worker.DoWork += new DoWorkEventHandler(gsWork1);

				m_params = Params;
				m_worker.RunWorkerAsync(Params);
				return gsStatus.GS_READY;
			}
			catch (OutOfMemoryException e)
			{
				Console.WriteLine("Memory allocation failed during gs rendering\n");
				return gsStatus.GS_ERROR;
			}
		}

		public void Cancel()
		{
			m_worker.CancelAsync();
		}
	}
}