TweetFollow Us on Twitter

March 95 - Print Hints

PRINT HINTS

Writing QuickDraw GX Drivers With Custom I/O and Buffering

DAVE HERSEY

[IMAGE 073-077_Print_Hints_html1.GIF]


One of the great features of QuickDraw GX is that it provides the printer driver developer with default implementations of commonly used routines. For example, just by specifying a few parameters in your driver's 'comm' (gxDeviceCommunicationsType) resource, your printer driver can connect to a printer either serially or through the Printer Access Protocol (PAP). You don't need to write a single line of communications code!

Another powerful feature of QuickDraw GX is that you can ignore the default implementations of printer driver routines and write your own routines instead. This feature enables you to tailor your printer driver so that it can accommodate unique situations. The ability to modify bits and pieces of the printing system is especially useful when it comes to writing printer drivers with custom communications code or buffering routines.

In general, to create custom communications code, youconfigure your driver's 'iobm' (gxUniversalIOPrefsType)resource, create a "not connected" 'comm' resource, and then override certain QuickDraw GX messages. For SCSI printers, however, you don't need to create the "not connected" resource, because a SCSI format of the 'comm' resource is already defined. We'll talk more about when you would want to use custom communications code, and how to write it, later in this column.

Also covered is how to write custom buffering routines. You may want to use custom buffering if, for example, you already have code that you want to use or you want to increase printer performance by taking advantage of a hardware buffer that you have available.

On this issue's CD, you'll find a sample printer driver called CustomWriter that illustrates how to implement "not connected" custom I/O and buffering. In addition, there's a sample LaserWriter IISC printer driver that shows how to create custom I/O code for a SCSI printer.

CUSTOM I/O -- WHO NEEDS IT?
The default communications code in QuickDraw GX handles asynchronous communications for serial and PAP printers and QuickDraw GX shared printers. Even so, you may want to override this code in some cases, such as if your printer communicates using a protocol that QuickDraw GX doesn't support (like 200 Kbits/second serial), or if you have your own PAP code that you'd like to continue using.

QuickDraw GX also supports the special cases of "not connected" printers and SCSI printers. If you're writing a driver using either of these two types of connections, you'll need to write some custom I/O code. In fact, the "not connected" communications method is provided specifically for the developer writing a driver containing custom communications code. What does this type of communications method do? In the default implementation, nothing at all. In a minute, you'll see how to use this to your advantage.

The only SCSI support currently built into QuickDraw GX handles filling out the Chooser list with your devices' SCSI addresses and saving updated 'comm' resources for any desktop printers that are created. Otherwise, QuickDraw GX doesn't actually open connections or try to send commands, such as SCSIRead or SCSIWrite, to the printer. SCSI printers usually have unique command sets, and trying to provide a generic mechanism to support all of these devices is unrealistic. As a result, you must provide your own communications code if you're writing a SCSI driver.

Finally, if your device is connected through a hardware interface that QuickDraw GX doesn't provide default support for (such as a NuBusTM card), you'll need to provide all of the communications code for your driver.

HOW TO GET STARTED
The first step in writing a driver with custom communications code is to configure your driver's 'iobm' resource. This is a very easy (and very critical) exercise.

'iobm' stands for "Input/Output and Buffering preferences." So what does the "m" stand for? Great question. As it turns out, if you set up this resource incorrectly, it becomes an "I/O BooM" resource. (The system crashes.) The "m" is silent as long as the resource is set up correctly. *

The 'iobm' resource tells QuickDraw GX how your driver wants its communications and buffering environment set up. This resource has the following format:

type gxUniversalIOPrefsType {
    longint standardIO = 0x00000000,
            customIO = 0x00000001;
    longint;        // number of buffers to allocate,
                    // 0 = none
    longint;        // size of each buffer
    longint;        // number of IO requests that can
                    // be pending at any one time
    longint;        // open/close time-out in ticks
    longint;        // read/write time-out in ticks
};

The 'iobm' resource was described in thedevelop Issue 20 Print Hints column about QuickDraw GX buffering. Rather than reiterate that information here, we're going to briefly focus on the first three fields of the resource.

The first item in the 'iobm' resource (standardIO or customIO) tells QuickDraw GX whether you want to use its built-in communications code. You must specify customIO if you want to use your own custom I/O code. When customIO is specified, QuickDraw GX won't go through the overhead of initialization and data allocation for the internal communications routines; as a result, youmust override certain messages, as described in a following section. When you specify customIO, the last three longint fields of this resource are ignored.

The two fields in the 'iobm' resource that follow the I/O type field indicate the number and size of the buffers your driver would like QuickDraw GX to create. Note that you can use QuickDraw GX's built-in buffering even if you're writing your own communications code. If, however, you're creating and disposing of your own buffers, you should set the "number of buffers" field to 0, so that QuickDraw GX won't waste time and memory allocating buffers that are never used. For code that communicates synchronously, multiple buffers don't improve performance, so you should set this field to 1.

Later in this column we'll take a closer look at what's required to create and manage your own I/O buffers.

WHEN "NOT CONNECTED" MEANS "CONNECTED"
Unless you're writing custom I/O routines to support a SCSI printer, you'll want to create a "not connected" 'comm' resource for your driver. Below is the declaration of a 'comm' resource for the "not connected" case.

For the full description of a 'comm' resource, see Inside Macintosh: QuickDraw GX Printing Extensions and Drivers .*

type gxDeviceCommunicationsType {
    unsigned longint = 'nops';
};

There's not a whole lot to it, is there? When you specify customIO in your 'iobm' resource, QuickDraw GX never does anything with your desktop printer's 'comm' resources other than examine the first longint. So, all sorts of possibilities become apparent. As long as that first longint is 'nops', you can extend the definition of this resource to suit your needs. Whether to change the definition of the resource in the PrintingResTypes.r interface file or not is up to you. Instead, you could just resize the resource when you update it at desktop printer creation time, as we'll discuss momentarily.

CUSTOM I/O -- THE MESSAGES
When you supply your own I/O routines, there are several messages that you need to override. Some of these messages will always need to betotally overridden, meaning that your overrides for these messages should never forward the messages. Other messages should bepartially overridden, in which case the message is forwarded at some point in your override code.

Now we'll look at the messages you need to override. (Table 1 summarizes these messages and the ones to override for custom buffering.) If you want more information on writingmessage overrides, see Sam Weiss's article, "DevelopingQuickDraw GX Printing Extensions," in develop Issue 15, andInside Macintosh: QuickDraw GX Printing Extensions and Drivers .


Table 1. Overriding QuickDraw GX messages

When to OverrideCustom I/OCustom Buffering
Always override (partially)GXOpenConnectionGXOpenConnection
GXCloseConnectionGXCloseConnection
GXCleanupOpenConnectionGXCleanupOpenConnection
GXWriteData
Always override (totally)GXDumpBufferGXBufferData
GXWriteData
Usually override (partially)GXDefaultDesktopPrinter
GXChooserMessage
Sometimes override (totally)GXFreeBuffer

Always override (partially)

  • GXOpenConnection
  • GXCloseConnection
  • GXCleanupOpenConnection
  • GXWriteData

When you override these messages, you should first forward the message, then execute your added code. Your overrides for the first three messages should contain code to open and close a connection to your device.

GXCloseConnection is sent to close a connection if no errors occur during the device communications phase of printing; GXCleanupOpenConnection is sent if an error does occur during this time. The goal for both of these overrides is to "undo" any data allocation or initialization that occurred in the GXOpenConnection override. Often, your GXCleanupOpenConnection message override can simply execute the same code as your GXCloseConnection override.

The GXWriteData override should forward the message(with a nil pointer and a length of 0) to flush any data that's buffered, and then send the data to the printer.

Always override (totally)

  • GXDumpBuffer

Your override for this message should execute code that sends the indicated data to your printer. When this message is sent, a connection to your device will already have been established through the successful execution of your GXOpenConnection override. The GXDumpBuffer message is used to send data to the printer whenever an I/O buffer becomes full.

Usually override (partially)

  • GXDefaultDesktopPrinter
  • GXChooserMessage

When QuickDraw GX creates a desktop printer, it stores in it a 'comm' resource that specifies how to communicate with the printer. By default, this 'comm' resource is just a filled-in copy of one of your driver's 'comm' resources. Depending on the setting in the Chooser's "Connect via:" menu, the 'comm' resource is updated with information about the printer, such as the selected serial port, SCSI address, and network address for an AppleTalk printer. If your driver uses a "not connected" 'comm' resource (as described earlier), it will be copied verbatim, without updated information about the selected printer. As a result, you might need to step in and fill out the resource yourself.

To update the 'comm' resource, you need to override the GXDefaultDesktopPrinter message as shown in Listing 1. Here we forward the message so that QuickDraw GX completes creation of the desktop printer; then we retrieve the 'comm' resource from the desktop printer, update it, and replace the old version with the updated version.

When you update the 'comm' resource, you need to know which printer the user selected, as well as its addressing information and so forth. You can find this information by overriding GXChooserMessage, which is sent by the GXHandleChooserMessage API call. In this override, possibly with some help from your Chooser PACK's LDEF, you can determine the relevant information about the selected printer.

For example, you can store this information in a column of cells that's appended to the printer list. Or you can store it in the list record's userHandle or, by using PC-relative addressing, in a data storage area following your jump table. When you retrieve this data in your GXChooserMessage override, simply store it using one of QuickDraw GX's global data functions for printing. Finally, retrieve the information from your GXDefaultDesktopPrinter override and store it in the desktop printer's 'comm' resource.

It's important to note that you can't use any of the functions GetMessageHandlerInstanceContext, SetMessageHandlerInstanceContext, GXGetJobRefCon,GXSetJobRefCon, and NewMessageGlobals for the example in Listing 1, because the GXChooserMessage and GXDefaultDesktopPrinter messages are sent to two different message handler instances. Therefore, you should use GetMessageHandlerClassContext, SetMessageHandlerClassContext, or some other method that works across message handler instances.

Sometimes override (totally)

  • GXFreeBuffer

If your communications code runs asynchronously, you must override GXFreeBuffer so that QuickDraw GX can tell when operations on a buffer have completed. The GXFreeBuffer message is sent to make sure that all the data in the buffer has been processed before the buffer is used again. When GXFreeBuffer returns, the indicated buffer is ready to accept more data. An override for this message should loop (calling GXJobIdle) until I/O on the specified buffer is complete, and then return.


Listing 1. Updating a 'comm' resource when a desktop printer is created

OSErr MyDefaultDesktopPrinter (Str31 dtpName) {
    OSErr   anyErrors;
    Handle  theCommResource;
    
    // Forward the message so that the desktop printer is created.
    anyErrors = Forward_GXDefaultDesktopPrinter(dtpName);
    nrequire(anyErrors, Abort);
    
    // Load the data for the 'comm' resource that was stored in the
    // desktop printer.
    anyErrors = GXFetchDTPData(dtpName, gxDeviceCommunicationsType,
       gxDeviceCommunicationsID, &theCommResource);
    require_action(theCommResource != nil, Abort,
       anyErrors = resNotFound;);
    
    // Update the 'comm' data with info about the selected printer,
    // and store the updated copy 
    // back in the desktop printer.
    MyUpdateCommResource(theCommResource);
    anyErrors = GXWriteDTPData(dtpName, gxDeviceCommunicationsType,
       gxDeviceCommunicationsID, theCommResource);
    
    // Finally, dispose of the handle we received from
    // GXFetchDTPData. It's a detached resource
    // handle, so DON'T USE RELEASERESOURCE!!
    DisposeHandle(theCommResource);

Abort:
    return anyErrors;
}

USING YOUR OWN BUFFERING SCHEME
At this point, we've discussed everything that's needed to handle your own custom I/O code. Now we'll take a quick look at what's required if you want to create and maintain your own buffers, instead of using those that the default implementation provides.

First things first. Go back to your 'iobm' resource, and set the number of buffers to 0. This tells QuickDraw GX not to waste time and memory allocating buffers that you aren't going to use.

When you implement your own buffering scheme, you can use any sort of internal representation for your buffers that you want to. However, since some of the buffering messages take a pointer to a gxPrintingBuffer, you'll need to use that format for passing your buffers between certain messages. But as far as the actual buffer structures go, you can use a handle, a linked list, or any other configuration that's convenient or necessary to use.

To support custom buffering code, you'll need to override the following messages.

Always override (partially)

  • GXOpenConnection
  • GXCloseConnection
  • GXCleanupOpenConnection
The partial overrides for these messages should forward the messages and then allocate or dispose of your internal buffer structures. If you're using custom I/O, you already provide overrides of these messages. In that case, simply add this new code to the existing overrides.

Always override (totally)

  • GXBufferData
  • GXWriteData

Provide an override of GXBufferData that stores the passed data in your next available buffer. If a buffer becomes full, call Send_GXDumpBuffer. Before you attempt to add data to this buffer again, call Send_GXFreeBuffer to make sure that all of the buffer's data has been sent to the printer.

Your override for the GXWriteData message should flush all data from your buffers and then immediately send the passed data to the printer. To do this, call Send_GXDumpBuffer on all buffers, followed bySend_GXFreeBuffer on all buffers. If you're performingcustom I/O, just add this code to your existing override.

You may wonder why you don't need to override the GXDumpBuffer message when you perform custom buffering. Unlike the messages listed above, GXDumpBuffer takes a pointer to a gxPrintingBuffer. Whenever your code calls Send_GXDumpBuffer, you must pass data in a gxPrintingBuffer structure, regardless of the internal buffer representation that you're using. Since the buffered data is passed in the format that GXDumpBuffer already expects, there's no need to override the message.

DRIVE SAFELY
That's all there is to it. So, the next time someone asks, "Can you write QuickDraw GX printer drivers for my 200 Kbits/second serial typesetter, my SCSI copier/printer, and my NuBus-interfaced cutter plotter?" tell them, "Yoooooooou betcha!"

DAVE HERSEY (AppleLink HERSEY) left Apple's Developer Technical Support (DTS) group about six months ago to join the Print Shop software development group. He now fixes the QuickDraw GX bugs that he reported while in DTS, and works on QuickDraw GX 2.0 -- the "knock your socks off" release. *

Thanks to Tom Dowdy, David Hayward, and Nick Thompson for reviewing this column. *

 
AAPL
$99.28
Apple Inc.
+1.61
MSFT
$43.87
Microsoft Corpora
+0.24
GOOG
$516.51
Google Inc.
+5.34

MacTech Search:
Community Search:

Software Updates via MacUpdate

TechTool Pro 7.0.5 - Hard drive and syst...
TechTool Pro is now 7, and this is the most advanced version of the acclaimed Macintosh troubleshooting utility created in its 20-year history. Micromat has redeveloped TechTool Pro 7 to be fully 64... Read more
Yasu 2.9.1 - System maintenance app; per...
Yasu was originally created with System Administrators who service large groups of workstations in mind, Yasu (Yet Another System Utility) was made to do a specific group of maintenance tasks... Read more
Hazel 3.3 - Create rules for organizing...
Hazel is your personal housekeeper, organizing and cleaning folders based on rules you define. Hazel can also manage your trash and uninstall your applications. Organize your files using a... Read more
Autopano Giga 3.7 - Stitch multiple imag...
Autopano Giga allows you to stitch 2, 20, or 2,000 images. Version 3.0 integrates impressive new features that will definitely make you adopt Autopano Pro or Autopano Giga: Choose between 9... Read more
MenuMeters 1.8 - CPU, memory, disk, and...
MenuMeters is a set of CPU, memory, disk, and network monitoring tools for Mac OS X. Although there are numerous other programs which do the same thing, none had quite the feature set I was looking... Read more
Coda 2.5 - One-window Web development su...
Coda is a powerful Web editor that puts everything in one place. An editor. Terminal. CSS. Files. With Coda 2, we went beyond expectations. With loads of new, much-requested features, a few... Read more
Arq 4.6.1 - Online backup to Google Driv...
Arq is super-easy online backup for the Mac. Back up to your own Google Drive storage (15GB free storage), your own Amazon Glacier ($.01/GB per month storage) or S3, or any SFTP server. Arq backs up... Read more
Airfoil 4.8.10 - Send audio from any app...
Airfoil allows you to send any audio to AirPort Express units, Apple TVs, and even other Macs and PCs, all in sync! It's your audio - everywhere. With Airfoil you can take audio from any... Read more
Apple iMovie 10.0.6 - Edit personal vide...
With an all-new design, Apple iMovie lets you enjoy your videos like never before. Browse your clips more easily, instantly share your favorite moments, and create beautiful HD movies and Hollywood-... Read more
Tunnelblick 3.4.1 - GUI for OpenVPN. (Fr...
Tunnelblick is a free, open source graphic user interface for OpenVPN on OS X. It provides easy control of OpenVPN client and/or server connections. It comes as a ready-to-use application with all... Read more

Latest Forum Discussions

See All

GAMEVIL Announces the Upcoming Launch of...
GAMEVIL Announces the Upcoming Launch of Mark of the Dragon Posted by Jessica Fisher on October 20th, 2014 [ permalink ] Mark of the Dragon, by GAMEVIL, put | Read more »
Find Free Food on Campus with Ypay
Find Free Food on Campus with Ypay Posted by Jessica Fisher on October 20th, 2014 [ permalink ] iPhone App - Designed for the iPhone, compatible with the iPad | Read more »
Strung Along Review
Strung Along Review By Jordan Minor on October 20th, 2014 Our Rating: :: GOT NO STRINGSUniversal App - Designed for iPhone and iPad A cool gimmick and a great art style keep Strung Along from completely falling apart.   | Read more »
P2P file transferring app Send Anywhere...
File sharing services like Dropbox have security issues. Email attachments can be problematic when it comes to sharing large files. USB dongles don’t fit into your phone. Send Anywhere, a peer-to-peer file transferring application, solves all of... | Read more »
Zero Age Review
Zero Age Review By Jordan Minor on October 20th, 2014 Our Rating: :: MORE THAN ZEROiPad Only App - Designed for the iPad With its mind-bending puzzles and spellbinding visuals, Zero Age has it all.   | Read more »
Hay Ewe Review
Hay Ewe Review By Campbell Bird on October 20th, 2014 Our Rating: :: SAVE YOUR SHEEPLEUniversal App - Designed for iPhone and iPad Pave the way for your flock in this line drawing puzzle game from the creators of Worms.   | Read more »
My Very Hungry Caterpillar (Education)
My Very Hungry Caterpillar 1.0.0 Device: iOS Universal Category: Education Price: $3.99, Version: 1.0.0 (iTunes) Description: Care for your very own Very Hungry Caterpillar! My Very Hungry Caterpillar will captivate you as he crawls... | Read more »
Dungeon Dick (Games)
Dungeon Dick 1.1 Device: iOS Universal Category: Games Price: $.99, Version: 1.1 (iTunes) Description: Dungeon Dick is a fantasy adventure where you must discover the wicked plot to destroy the lands . 'Fling' at your foes and land... | Read more »
Here’s How the Apple Watch Could Transfo...
With the Apple Watch’s generic release date of, “early 2015” hovering on the horizon, it’s only a matter of time before gamers begin to ask “What’s in it for us?” The obvious choice would be to place entire games directly on the face of the watch,... | Read more »
Republique Episode 3: Ones & Zeroes...
Republique Episode 3: Ones & Zeroes is Available Now Posted by Rob Rich on October 17th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »

Price Scanner via MacPrices.net

2013 15-inch 2.0GHz Retina MacBook Pro availa...
B&H Photo has leftover previous-generation 15″ 2.0GHz Retina MacBook Pros now available for $1599 including free shipping plus NY sales tax only. Their price is $400 off original MSRP. B&H... Read more
Updated iPad Prices
We’ve updated our iPad Air Price Tracker and our iPad mini Price Tracker with the latest information on prices and availability from Apple and other resellers, including the new iPad Air 2 and the... Read more
Apple Pay Available to Millions of Visa Cardh...
Visa Inc. brings secure, convenient payments to iPad Air 2 and iPad mini 3as well as iPhone 6 and 6 Plus. Starting October 20th, eligible Visa cardholders in the U.S. will be able to use Apple Pay,... Read more
Textkraft Pocket – the missing TextEdit for i...
infovole GmbH has announced the release and immediate availability of Textkraft Pocket 1.0, a professional text editor and note taking app for Apple’s iPhone. In March 2014 rumors were all about... Read more
C Spire to offer iPad Air 2 and iPad mini 3,...
C Spire on Friday announced that it will offer iPad Air 2 and iPad mini 3, both with Wi-Fi + Cellular, on its 4G+ LTE network in the coming weeks. C Spire will offer the new iPads with a range of... Read more
Belkin Announces Full Line of Keyboards and C...
Belkin International has unveiled a new lineup of keyboard cases and accessories for Apple’s newest iPads, featuring three QODE keyboards and a collection of thin, lightweight folios for both the... Read more
Verizon offers new iPad Air 2 preorders for $...
Verizon Wireless is accepting preorders for the new iPad Air 2, cellular models, for $100 off MSRP with a 2-year service agreement: - 16GB iPad Air 2 WiFi + Cellular: $529.99 - 64GB iPad Air 2 WiFi... Read more
Price drops on refurbished Mac minis, now ava...
The Apple Store has dropped prices on Apple Certified Refurbished previous-generation Mac minis, with models now available starting at $419. Apple’s one-year warranty is included with each mini, and... Read more
Apple refurbished 2014 MacBook Airs available...
The Apple Store has Apple Certified Refurbished 2014 MacBook Airs available for up to $180 off the cost of new models. An Apple one-year warranty is included with each MacBook, and shipping is free.... Read more
Refurbished 2013 MacBook Pros available for u...
The Apple Store has Apple Certified Refurbished 13″ and 15″ MacBook Pros available starting at $929. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.5GHz MacBook Pros (4GB RAM/... Read more

Jobs Board

Position Opening at *Apple* - Apple (United...
…customers purchase our products, you're the one who helps them get more out of their new Apple technology. Your day in the Apple Store is filled with a range of Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** At the Apple Store, you connect business professionals and entrepreneurs with the tools they need in order to put Apple solutions to work in their Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** The Apple Store is a retail environment like no other - uniquely focused on delivering amazing customer experiences. As an Expert, you introduce people Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** As businesses discover the power of Apple computers and mobile devices, it's your job - as a Solutions Engineer - to show them how to introduce these Read more
Position Opening at *Apple* - Apple (United...
…Summary** As a Specialist, you help create the energy and excitement around Apple products, providing the right solutions and getting products into customers' hands. You Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.