File size: 11,883 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Management.Automation;
using System.Management.Automation.Internal;

namespace Microsoft.PowerShell.Commands.Internal.Format
{
    /// <summary>
    /// Implementation of the LineOutput interface for printer.
    /// </summary>
    internal sealed class PrinterLineOutput : LineOutput
    {
        #region LineOutput implementation

        /// <summary>
        /// Full buffering for printer.
        /// </summary>
        internal override bool RequiresBuffering { get { return true; } }

        /// <summary>
        /// Do the printing on playback.
        /// </summary>
        internal override void ExecuteBufferPlayBack(DoPlayBackCall playback)
        {
            _playbackCall = playback;
            DoPrint();
        }

        /// <summary>
        /// The # of columns for the printer.
        /// </summary>
        /// <value></value>
        internal override int ColumnNumber
        {
            get
            {
                CheckStopProcessing();
                return _deviceColumns;
            }
        }

        /// <summary>
        /// The # of rows for the printer.
        /// </summary>
        /// <value></value>
        internal override int RowNumber
        {
            get
            {
                CheckStopProcessing();
                return _deviceRows;
            }
        }

        /// <summary>
        /// Write a line to the output device.
        /// </summary>
        /// <param name="s">Line to write.</param>
        internal override void WriteLine(string s)
        {
            CheckStopProcessing();

            // Remove all ANSI escape sequences before sending out to the printer.
            s = new ValueStringDecorated(s).ToString(OutputRendering.PlainText);
            WriteRawText(s);
        }

        /// <summary>
        /// Write a raw text by delegating to the writer underneath, with no change to the text.
        /// For example, keeping VT escape sequences intact in it.
        /// </summary>
        /// <param name="s">The raw text to be written to the device.</param>
        internal override void WriteRawText(string s)
        {
            CheckStopProcessing();

            // Delegate the action to the helper, that will properly break the string into screen lines.
            _writeLineHelper.WriteLine(s, ColumnNumber);
        }

        #endregion

        /// <summary>
        /// Initializes static members of the <see cref="PrinterLineOutput"/> class.
        /// Used for static initializations like DefaultPrintFontName.
        /// </summary>
        static PrinterLineOutput()
        {
            // This default must be loaded from a resource file as different
            // cultures will have different defaults and the localizer would
            // know the default for different cultures.
            s_defaultPrintFontName = OutPrinterDisplayStrings.DefaultPrintFontName;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PrinterLineOutput"/> class.
        /// </summary>
        /// <param name="printerName">Name of printer, if null use default printer.</param>
        internal PrinterLineOutput(string printerName)
        {
            _printerName = printerName;

            // instantiate the helper to do the line processing when LineOutput.WriteXXX() is called
            WriteLineHelper.WriteCallback wl = new(this.OnWriteLine);
            WriteLineHelper.WriteCallback w = new(this.OnWrite);

            _writeLineHelper = new WriteLineHelper(true, wl, w, this.DisplayCells);
        }

        /// <summary>
        /// Callback to be called when IConsole.WriteLine() is called by WriteLineHelper.
        /// </summary>
        /// <param name="s">String to write.</param>
        private void OnWriteLine(string s)
        {
            _lines.Enqueue(s);
        }

        /// <summary>
        /// Callback to be called when Console.Write() is called by WriteLineHelper.
        /// This is called when the WriteLineHelper needs to write a line whose length
        /// is the same as the width of the screen buffer.
        /// </summary>
        /// <param name="s">String to write.</param>
        private void OnWrite(string s)
        {
            _lines.Enqueue(s);
        }

        /// <summary>
        /// Do the printing.
        /// </summary>
        private void DoPrint()
        {
            try
            {
                // create a new print document object and set the printer name, if available
                PrintDocument pd = new();

                if (!string.IsNullOrEmpty(_printerName))
                {
                    pd.PrinterSettings.PrinterName = _printerName;
                }

                // set up the callback mechanism
                pd.PrintPage += this.pd_PrintPage;

                // start printing
                pd.Print();
            }
            finally
            {
                // make sure we do not leak the font
                if (_printFont != null)
                {
                    _printFont.Dispose();
                    _printFont = null;
                }
            }
        }

        /// <summary>
        /// Helper to create a font.
        /// If the font object exists, it does nothing.
        /// Else, the a new object is created and verified.
        /// </summary>
        /// <param name="g">GDI+ graphics object needed for verification.</param>
        private void CreateFont(Graphics g)
        {
            if (_printFont != null)
                return;

            // create the font

            // do we have a specified font?
            if (string.IsNullOrEmpty(_printFontName))
            {
                _printFontName = s_defaultPrintFontName;
            }

            if (_printFontSize <= 0)
            {
                _printFontSize = DefaultPrintFontSize;
            }

            _printFont = new Font(_printFontName, _printFontSize);
            VerifyFont(g);
        }

        /// <summary>
        /// Internal helper to verify that the font is fixed pitch. If the test fails,
        /// it reverts to the default font.
        /// </summary>
        /// <param name="g">GDI+ graphics object needed for verification.</param>
        private void VerifyFont(Graphics g)
        {
            // check if the font is fixed pitch
            // HEURISTICS:
            // we compute the length of two strings, one made of "large" characters
            // one made of "narrow" ones. If they are the same length, we assume that
            // the font is fixed pitch.
            const string large = "ABCDEF";
            float wLarge = g.MeasureString(large, _printFont).Width / large.Length;
            const string narrow = ".;'}l|";
            float wNarrow = g.MeasureString(narrow, _printFont).Width / narrow.Length;

            if (Math.Abs((float)(wLarge - wNarrow)) < 0.001F)
            {
                // we passed the test
                return;
            }

            // just get back to the default, since it's not fixed pitch
            _printFont.Dispose();
            _printFont = new Font(s_defaultPrintFontName, DefaultPrintFontSize);
        }

        /// <summary>
        /// Event fired for each page to print.
        /// </summary>
        /// <param name="sender">Sender, not used.</param>
        /// <param name="ev">Print page event.</param>
        private void pd_PrintPage(object sender, PrintPageEventArgs ev)
        {
            float yPos = 0; // GDI+ coordinate down the page
            int linesPrinted = 0; // linesPrinted
            float leftMargin = ev.MarginBounds.Left;
            float topMargin = ev.MarginBounds.Top;

            CreateFont(ev.Graphics);

            // compute the height of a line of text
            float lineHeight = _printFont.GetHeight(ev.Graphics);

            // Work out the number of lines per page
            // Use the MarginBounds on the event to do this
            float linesPerPage = ev.MarginBounds.Height / _printFont.GetHeight(ev.Graphics);

            if (!_printingInitialized)
            {
                // on the first page we have to initialize the metrics for LineOutput

                // work out the number of columns per page assuming fixed pitch font
                const string s = "ABCDEF";
                float w = ev.Graphics.MeasureString(s, _printFont).Width / s.Length;
                float columnsPerPage = ev.MarginBounds.Width / w;

                _printingInitialized = true;
                _deviceRows = (int)linesPerPage;
                _deviceColumns = (int)columnsPerPage;

                // now that we initialized the column and row count for the LineOutput
                // interface we can tell the outputter to playback from cache to do the
                // proper computations of line widths
                // returning from this call, the string queue on this object is full of
                // lines of text to print
                _playbackCall();
            }

            // now iterate over the file printing out each line
            while ((linesPrinted < linesPerPage) && (_lines.Count > 0))
            {
                // get the string to be printed
                string line = _lines.Dequeue();

                // compute the Y position where to draw
                yPos = topMargin + (linesPrinted * lineHeight);

                // do the actual drawing
                ev.Graphics.DrawString(line, _printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
                linesPrinted++;
            }

            // If we have more lines then print another page
            ev.HasMorePages = _lines.Count > 0;
        }

        /// <summary>
        /// Flag for one-time initialization of the interface (columns, etc.).
        /// </summary>
        private bool _printingInitialized = false;

        /// <summary>
        /// Callback to ask the outputter to playback its cache.
        /// </summary>
        private DoPlayBackCall _playbackCall;

        /// <summary>
        /// Name of the printer to print to. Null means default printer.
        /// </summary>
        private readonly string _printerName = null;

        /// <summary>
        /// Name of the font to use, if null the default is used.
        /// </summary>
        private string _printFontName = null;

        /// <summary>
        /// Font size.
        /// </summary>
        private int _printFontSize = 0;

        /// <summary>
        /// Default font, used if the printFont is not specified or if the
        /// printFont is not fixed pitch.
        /// </summary>
        /// <remarks>
        /// This default must be loaded from a resource file as different
        /// cultures will have different defaults and the localizer would
        /// know the default for different cultures.
        /// </remarks>
        private static readonly string s_defaultPrintFontName;

        /// <summary>
        /// Default size for the default font.
        /// </summary>
        private const int DefaultPrintFontSize = 8;

        /// <summary>
        /// Number of columns on the sheet.
        /// </summary>
        private int _deviceColumns = 80;

        // number of rows per sheet
        private int _deviceRows = 40;

        /// <summary>
        /// Text lines ready to print (after output cache playback).
        /// </summary>
        private readonly Queue<string> _lines = new();

        /// <summary>
        /// Cached font object.
        /// </summary>
        private Font _printFont = null;

        private readonly WriteLineHelper _writeLineHelper;
    }
}