summaryrefslogtreecommitdiff
path: root/print/v4PrintDriverSamples/PrinterExtensionSample/ExtensionSample/PrintPreferenceWindow.xaml.cs
blob: a6266662c9e0b808f2c8478098016e0adada4a77 (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
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
//
//
// Abstract:
//
//     This file contains as the interaction logic and data-binding code/sources for the WPF print preferences window.

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

using System.Reflection;
using System.IO;

using System.Xml.Linq;

using System.Runtime.InteropServices;

using Microsoft.Samples.Printing.PrinterExtension.Types;
using Microsoft.Samples.Printing.PrinterExtension.Helpers;

namespace Microsoft.Samples.Printing.PrinterExtension
{
    /// <summary>
    /// Interaction logic for PrintPreferenceWindow.xaml.
    /// </summary>
    public partial class PrintPreferenceWindow : Window, INotifyPropertyChanged
    {
        public PrintPreferenceWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// This method sets up data binding sources and performs other initialization tasks.
        /// </summary>
        /// <param name="eventArgs"></param>
        public void Initialize(PrinterExtensionEventArgs eventArgs)
        {
            //
            // Populate the data binding sources.
            //

            DataContext = this;

            printerExtensionEventArgs = eventArgs;
            PrinterQueue = eventArgs.Queue;
            displayedPrintTicket = eventArgs.Ticket;

            //
            // Send a bidi query requesting ink levels.
            //
            // Please note: As this event will fire many times, it is recommended to maintain event
            // listeners for the life time of the application. Furthermore, the relationship to this
            // being invoked and the calling SendBidiQuery() is not 1:1; in fact, it is *:N, where the 
            // listener may be called several times with bidi updates.
            // 
            //

            PrinterQueue.OnBidiResponseReceived += OnBidiResponseReceived;
            PrinterQueue.SendBidiQuery("\\Printer.consumables");
        }

        #region UI code

        /// <summary>
        /// This event handler is invoked when the window is closing. It is important to Cancel or Complete the request when the window is closing.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void PrintPreferenceWindow_Closing(object sender, EventArgs e)
        {
            // Since we are a different process from the printing application we need to hand focus back when complete.
            WindowHelper.SetForegroundWindow(printerExtensionEventArgs.WindowParent);

            if (!requestCompleted)
            {
                printerExtensionEventArgs.Request.Cancel((int)HRESULT.S_FALSE, "The user canceled the operation.");
                requestCompleted = true;
            }
        }

        /// <summary>
        ///  Button click event handler.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button clickedButton = (Button)sender;

            switch (clickedButton.Name)
            {
                case "CancelButton":
                    CancelRequestAndCloseWindow();
                    break;

                case "OkButton":
                    //
                    // Validate the print ticket asynchronously. The event handler is invoked when the validation is completed.
                    //

                    IPrintSchemaAsyncOperation asyncOperation = displayedPrintTicket.ValidateAsync();

                    //
                    // Pop up a modal dialog that prevents the user from changing selections when validation is in progress.
                    // Since this dialog lives as long as the parent window, it is not mandatory to unregister the delegate for the
                    // 'Completed' event.
                    //

                    ValidationModalDialog.Completed += PrintTicketValidateCompleted; // This operation is idempotent.
                    ValidationModalDialog.StartAsyncOperation(asyncOperation);
                    break;

                case "VerifyButton":
                    //
                    // Force WPF Data binding to refresh the UI. This operation retrieves
                    // a fresh print capabilities for the print ticket based on the user selections.
                    //

                    PropertyChanged(this, new PropertyChangedEventArgs("PrintSchemaHelperSource"));
                    break;
            }
        }

        /// <summary>
        /// Close the window in a thread-safe way.
        /// </summary>
        private void CloseWindow()
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                this.Close();
            }));
        }

        #endregion


        #region Data binding sources

        /// <summary>
        /// The Print queue for which this window is being displayed.
        /// </summary>
        public IPrinterQueue PrinterQueue { get; private set; }

        /// <summary>
        /// The title for the ink status display.
        /// </summary>
        public string InkStatusTitle { get; private set; }

        /// <summary>
        /// Retrieve a new instance of PrintSchemaHelper, based on the current print ticket being displayed.
        /// PrintSchemaHelper encapsulates all the features and options required to populate the print preferences UI.
        /// </summary>
        public PrintSchemaHelper PrintSchemaHelperSource
        {
            get
            {
                //
                // Below is the list of features that will be displayed in the print preferences window.
                // The features are declared here for convenience/readability.
                //
                // In performant code, this array would be allocated only once per run of the application.
                //

                string[] featureNames = {
                                            "DocumentNUp",
                                            "PageMediaSize",
                                            "DocumentInputBin",
                                            "PageOrientation",
                                            "PageMediaType",
                                            "PageBorderless",
                                            "JobInputBin",
                                            "PageOutputColor",
                                            "DocumentCollate",
                                            "DocumentDuplex"
                                        };

                return new PrintSchemaHelper(displayedPrintTicket, featureNames);
            }
        }

        /// <summary>
        /// Encapsulates the information required to populate ink level.
        /// </summary>
        public BidiHelper BidiHelperSource { get; private set; }

        /// <summary>
        /// This event is raised when a data from a binding source is modified.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region Ink level display
        /// <summary>
        /// This is the method invoked when a bidi response is received.
        /// </summary>
        /// <param name="sender">IPrinterQueue object.</param>
        /// <param name="e">The results of the bidi response.</param>
        private void OnBidiResponseReceived(object sender, PrinterQueueEventArgs e)
        {
            if (e.StatusHResult != (int)HRESULT.S_OK)
            {
                MockInkStatus();
                return;
            }

            //
            // Display the ink levels from the mock data.
            //

            BidiHelperSource = new BidiHelper(e.Response);
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("BidiHelperSource"));
            }
            InkStatusTitle = "Ink status (Live data)";
        }

        /// <summary>
        /// This method is invoked when there is an error retrieving Bidi information.
        /// A mock bidi response is loaded from resource and displayed.
        /// </summary>
        private void MockInkStatus()
        {
            //
            // Load mock bidi response resource.
            //

            Assembly a = Assembly.GetExecutingAssembly();
            Stream xmlData = a.GetManifestResourceStream("PrinterExtensionSample.bidi_Ink_mock.xml");
            StreamReader sr = new StreamReader(xmlData);
            string xmlString = sr.ReadToEnd();

            //
            // Display the ink levels from the mock data.
            //

            BidiHelperSource = new BidiHelper(xmlString);
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("BidiHelperSource"));
            }
            InkStatusTitle = "Ink status (Mocked data)";
        }
        #endregion

        #region PrintSchema-related code
        /// <summary>
        /// Cancel the current printer extension event and close the current window.
        /// </summary>
        private void CancelRequestAndCloseWindow()
        {
            printerExtensionEventArgs.Request.Cancel((int)HRESULT.S_FALSE, "User canceled the operation");
            requestCompleted = true;
            CloseWindow();
        }

        /// <summary>
        /// Invoked when asynchronous print ticket validation is complete.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PrintTicketValidateCompleted(object sender, PrintSchemaAsyncOperationEventArgs e)
        {
            //
            // Print ticket validation completed successfully i.e. print ticket selections are not constrained.
            // The print ticket needs to be committed, and then window can be closed.
            //

            if (e.StatusHResult == (int)HRESULT.S_PT_NO_CONFLICT)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    CommitPrintTicketAsync(e.Ticket);
                }));

            }
            else
            {
                //
                // The ticket selections are constrained.
                //

                this.Dispatcher.Invoke(new Action(() =>
                {
                    HandleTicketConstraints(e.Ticket);
                }));
            }
        }

        /// <summary>
        /// Invoked when there are constraints in the print ticket selections.
        /// </summary>
        /// <param name="validatedTicket"></param>
        private void HandleTicketConstraints(IPrintSchemaTicket validatedTicket)
        {
            //
            // Retrieved localized display strings from a resource file/
            //
            string selectionConflictsFound = PrinterExtensionSample.Strings.SelectionConflictsFound;
            string selectionConflictsTitle = PrinterExtensionSample.Strings.SelectionConflictsTitle;

            MessageBoxResult result = MessageBox.Show(
                                        this,
                                        selectionConflictsFound,
                                        selectionConflictsTitle,
                                        MessageBoxButton.YesNoCancel);

            if (result == MessageBoxResult.Yes)
            {
                CommitPrintTicketAsync(validatedTicket);
            }
            else
            {
                PropertyChanged(this, new PropertyChangedEventArgs("PrintSchemaHelperSource"));
            }
        }

        /// <summary>
        /// Commits the input print ticket asynchronously. The completed event handler is expected to close the window.
        /// </summary>
        /// <param name="validatedTicket"></param>
        private void CommitPrintTicketAsync(IPrintSchemaTicket validatedTicket)
        {
            IPrintSchemaAsyncOperation commitAsyncOperation = printerExtensionEventArgs.Ticket.CommitAsync(validatedTicket);
            commitAsyncOperation.Completed += PrintTicketCommitCompleted;
            commitAsyncOperation.Start();
        }

        /// <summary>
        /// Invoked when the user's selections have been committed into the print ticket.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PrintTicketCommitCompleted(object sender, PrintSchemaAsyncOperationEventArgs e)
        {
            CompleteRequestAndCloseWindow();
        }

        /// <summary>
        /// Complete the current printer extension request and close the current window.
        /// </summary>
        private void CompleteRequestAndCloseWindow()
        {
            //
            // It is important to invoke the IPrinterExtensionRequest::Complete method from the thread the
            // class instance was create on (i.e. the UI thread).
            //

            this.Dispatcher.Invoke(new Action(() =>
            {
                printerExtensionEventArgs.Request.Complete();
            }));

            requestCompleted = true;
            CloseWindow();
        }

        /// <summary>
        /// Demonstrates how to modify print ticket XML. This piece of code does not perform any functionality. 
        /// It serves to demonstrate the usage of IPrintSchemaTicket::GetReadStream()/GetWriteStream()
        /// </summary>
        private void ModifyPrintTicketXml()
        {
            //
            // Load the ticket XML (as a Stream) into an XElement object.
            //

            XElement ticketRootXElement = null;
            using (Stream ticketReadStream = displayedPrintTicket.GetReadStream())
            {
                ticketRootXElement = XElement.Load(ticketReadStream);
            }

            //
            // Perform any modifications on the XElement object.
            //


            //
            // Write the changes back to the print ticket.
            //
            using (Stream ticketWriteStream = displayedPrintTicket.GetWriteStream())
            {
                ticketRootXElement.Save(ticketWriteStream);
            }
        }

        #endregion

        /// <summary>
        /// The arguments passed in for this print preferences event.
        /// </summary>
        private PrinterExtensionEventArgs printerExtensionEventArgs = null;

        /// <summary>
        /// Reflects the currently displayed print preference options.
        /// </summary>
        private IPrintSchemaTicket displayedPrintTicket = null;

        /// <summary>
        /// Determines if IPrinterExtensionRequest::Complete()/Cancel() has been invoked for this Window.
        /// instance
        /// </summary>
        private bool requestCompleted = false;
    }

    /// <summary>
    /// This class transforms the boolean 'IPrintSchemaOption.Constrained' into a visual form.
    /// </summary>
    public class OptionConstrainedToDisplayColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                return "Black";
            }

            //
            // If the option is not constrained, it will be diplayed in black.
            //

            PrintSchemaConstrainedSetting constrained = (PrintSchemaConstrainedSetting)value;
            if (constrained == PrintSchemaConstrainedSetting.None)
            {
                return "Black";
            }

            //
            // If the option is constrained, it will be displayed in red.
            //

            return "Red";
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// Provides a friendlier way to use HRESULT error codes.
    /// </summary>
    enum HRESULT : int
    {
        S_OK = 0x0000,
        S_FALSE = 0x0001,
        S_PT_NO_CONFLICT = 0x40001,
        E_INVALIDARG = unchecked((int)0x80070057),
        E_OUTOFMEMORY = unchecked((int)0x8007000E),
        ERROR_NOT_FOUND = unchecked((int)0x80070490)
    }
}