frameworker

August 6, 2018

FORMKIT FLY-THROUGH

Filed under: Uncategorized — frameworker @ 10:09 pm

FormKit lets you easily create PDF forms through rapid and precise layout of editable fields.

Build the form described in this fly-through and you’ll understand the basics. The rest of this User’s Guide will fill in the details of FormKit’s operation, introducing additional functions and showing you alternative ways of doing some of the things covered in the fly-through.

Constructing a fillable form with FormKit is easy. You start with a “flat” PDF image of your form; it looks like a form but can’t be filled in. Using FormKit, you lay out fields over the PDF image. When you save it, the fields are “baked into” the PDF and it becomes fillable. Then any user can open it in Preview, fill it in, and save it.

You love chinchillas so much that you’ve decided to start “Chinchillas-R-Us,” a business boarding them. One thing you’ll need will be a registration form to check in new clients.

Legibility is important, so paper forms are out. You also want to make it easy for clients to download, complete, and print the form at home if they wish. That makes it easier on everyone because it lets you focus on the pet rather than the paperwork. You decide that a PDF fill-in form will fit your needs perfectly.

NOTE: In several places in this fly-through you’ll see a “PRO-TIP” heading indicating material that doesn’t strictly belong in the fly-through. It’s included because the context is perfect for introducing the additional useful information. You don’t have to be a pro to benefit from these tips, but they will make you feel like one. 🙂

GETTING STARTED

You use your favorite word processing or graphics app – such as Pages – to create the form. Then you save it as a PDF file. This gives you a “flat” form that could be printed out and filled in by hand. But it’s also the first step toward making the fill-in form you need.

Taking a peek ahead, this is what your completed form will look like when it’s filled in:

Chinchillas-R-US (completed) fitted to reduced once.png

Launch FormKit. Its menu bar and tool palette will appear. Open Chinchillas-R-Us.pdf. It will be the background image over which you lay out form fields.

It’s easier to lay out fields when the form is blown up. So you expand the page to be quite large by zooming in on the document several times using ⌘=.

Notice that FormKit’s page resizing maintains a full page view as you zoom in.

PREFERENCES

Let’s look at the Preferences before starting to lay out the form. Choose FormKit > Preferences to open them.

Prefs reduced once.png

Use the Image Opacity slider to dim the background image. This will decrease eyestrain while you’re sketching fields onto the form, making it easier to focus on the fields as you lay them out. The fields you sketch will not be dimmed by the slider. And it doesn’t affect the final form; the image there will not be dimmed at all.

Since your background image doesn’t contain borders for check boxes, click Field Shading for check boxes. That will provide a way for the user to know where to click when filling in the form. This won’t affect the form’s appearance during construction, but check boxes will be shaded in the output PDF.

Note that text fields don’t need shading because they’re more clearly demarcated and more easily discoverable; you can see the text pointer when you mouse over one.

You can play with the Stroke preferences as you’re laying out the form to find the settings that make it easiest for you to work with fields.

The Fonts preferences can wait for now, but you’ll need to set them before you save the final version of your form. They’ll be registered in the form and will be used by Preview when the form is filled in.

TOOL PALETTE

A typical drawing app, FormKit has a palette of tools. The arrow tool is used for selecting, resizing, and moving fields. The other tools correspond to the type of field that is sketched when they’re selected.

Tool Palette w Labels reduced once.png

SKETCHING FORM FIELDS

Select the text field tool on the tool palette. When you move the mouse pointer over your document window, it changes from an arrow to a plus sign (+). Sketch out a wide, thin rectangle for the “Pet’s Name” field. Notice that it has selection handles that you can use to resize it, and also that an Annotations Inspector panel has appeared. That happens whenever a single field is selected. We don’t need to do anything with the inspector right now, but it will be useful later.

POSITIONING AND RESIZING FORM FIELDS

Before you continue sketching text fields, it’s useful to understand how positioning and resizing work.

You want to adjust the text field you just sketched to be a certain size and in a particular location.

Go back to the tool palette and select the arrow tool.

You can adjust a selected field’s position by dragging the field. You can fine-tune its position a pixel at a time using the arrow keys.

You can resize a selected field by dragging one of its handles. Dragging the corner handles allows both horizontal and vertical resizing. Dragging the mid-line handles only allows you to resize perpendicularly to the line the handle is on.

You can fine-tune the height and width of a selected field a pixel at a time using the arrow keys. Option-Up raises it, Option-Down lowers it, Option-Left shrinks it, and Option-Right expands it.

Fiddle with the text field you just sketched to position and resize it the way you want.

TEXT FIELDS

There are two approaches to doing text field layout, one in which you copy and paste existing fields to create new ones. Alternatively, you could continue to sketch fields iteratively with the mouse; it’s your choice. Let’s look now at the copy and paste method.

Be sure the arrow tool is selected for this.

The recipe for building a form by copying and pasting is to iteratively copy and then paste one of the completed fields. The pasted item will appear just below the original, slightly offset to the right. Drag it to its destination and lengthen or shorten it. Repeat this, moving down the form rapidly. The fields you’ve laid out won’t be positioned perfectly, but you’ll fine-tune them in the next phase.

Do this with the “Pet’s Name” field, dragging the pasted item into the “Weight” field. Drag the middle handle on its right end and shorten it to be the width you want.

Next, copy and paste the “Weight” field, dragging it down to the “How many times a day” field and adjusting its length.

Then copy and paste the “Pet’s Name” field again, this time dragging the pasted item down to the “Own supply” field. Make it wider by dragging to the right.

Chinchillas-R-US (partial annotated) reduced once.png

Continue with this until you’ve laid out all the text fields.

PRO-TIP: ALIGN & SIZE

If you accidentally resize a field’s height when you’re stretching or shrinking it, you can deal with that by selecting it and another field – one with the correct height – using an area selector like the one the Finder uses. Then Option-click on the good field to specify it as the anchor (it turns green) and choose the Align & Size > Make Same Height command.

The anchor is the reference item. The command will make the other items in the selection conform to its attributes.

Note that the Align & Size commands are not enabled unless there’s a compound selection with a designated (green) anchor.

Align & Size reduced once.png

The exception to this is Make Square, which needs no anchor and is enabled for any selection with a non-square item. We’ll use Make Square when laying out check boxes.

CHECK BOXES

Now we want to add in the check boxes. We’ll use the same Copy and Paste recipe for this as we did with text fields.

Sketch the first one, adjust its size, and make it square with Align & Size > Make Square. Our check boxes all come in pairs, so copy and paste the check box. Move it into a position complementing the first one and align their bottom edges.

Then copy and paste these check boxes and move the new pair into place – adjusting their horizontal spread as needed – repeating until they’re all done. Then save the document again.

FINE TUNING

Make sure you’ve finished all of the initial layout — including fields that aren’t demarcated in the background by lines or boxes — copying and pasting fields and moving them to their needed positions.

Once all the fields are in place, you’ll want to fine-tune their positions and sizes using the arrow keys and the Align & Size commands.

For example, it’s a good idea to have the fields float a consistent distance above their underlines, so that the form has a smooth appearance when it’s been filled in. To do this, use the arrow keys like little tugboats to nudge the fields into their moorings.

Another example of fine tuning is to align the right edges of all the fields that extend to the form’s right margin to give it a crisp look. To do this, just select them, Option-click on the reference item, and choose Align & Size > Right Edges.

Now save the work you’ve done with the File > Save command (Command-S).

SET THE TAB ORDER

When the form is being filled in, you want the user to be able to tab in a logical order from field to field. In FormKit, it’s a breeze to set the fields’ tab order. Here’s how.

Click in the form to make its window active and to clear any selection.

Next, Command-click on the fields in the order in which you want to tab through them. When you’re done, click once on the form to clear the selection. That seals the tab order.

PRO-TIP: FAULT TOLERANCE

If making a mistake while setting the tab order meant that you had to start the process all over again, it would be a tense and unpleasant task, especially for long forms. But it can be performed incrementally, if need be.

When your setting of the tab order “goes off the road,” here’s what to do: Find the last item that’s in the correct tab order, select it, and Command-click on succeeding fields in the tab order you want. When you’ve finished, click once to clear the selection, resealing the tab order. It’s that simple.

INSPECT FIELD SETTINGS

Now that you can tab between fields in the order you want, it’s time to tab through them to inspect their settings and change them if necessary.

As noted earlier, an Annotations Inspector panel appears whenever you have a single field selected. As you tab through the fields, the inspector changes to show the settings for the currently selected item. Notice that the fields already have default names; these were set as you set the tab order.

When a text field is selected, Field Name, Max Length, and Alignment settings are shown.

textfield-inspector reduced once.png

When a check box is selected, Field Name and “On” Value settings are shown. “On” is the default “On” Value setting (a setting that’s only useful with radio buttons).

checkbox-inspector reduced once.png

If you edit a field’s settings as you tab through the form, you’ll need to return focus to the form by clicking back on the selected field in order to continue tabbing.

PRO-TIP: When you copy and paste fields, their settings are preserved. If you want a group of items to have the same settings, be sure that the first one has those settings so that the copied ones will too.

FINISH UP

When all the field settings are correct, make sure that the Fonts preferences are set to your liking; then save the document one last time, and you’re done. You now have the Chinchillas-R-Us form for your website.

Chinchillas-R-US (completed) reduced once.png

This fly-through is dedicated to John Spragens, the late cousin of my good friend Alan Spragens, who introduced me to this genre of writing. John was a creatively gifted and generous person. I’m lucky to have known him.

Advertisements

July 27, 2018

PDFKit, The Lost Samples

Filed under: Uncategorized — frameworker @ 5:06 am

PDFKit, you are a strong friend,
doing heavy lifting,
to make my task more manageable.

Introduction

Through the vestiges of time, the “Lost PDFKit Samples” have been rediscovered and brought up to date!

When I began using PDFKit, in the days of Tiger and Leopard, there were a number of sample apps that helped me learn the framework: PDFKitViewer, PDFKitLinker2, Link Snoop, PDFCalendar, PDFViewSubclasser, and PDFAnnotationEditor. These samples showed interesting aspects of PDFKit. Beyond PDFKit, they highlighted significant aspects of Cocoa. And they’re incredibly well written—readable and well factored.

But through the accumulation of deprecated APIs over nine builds and, especially, the pervasive breakage in the macOS 10.13 High Sierra rewrite, they broke and faded into obscurity.

However, with the port to iOS—“PDFKit reloaded” (sorry, Keneau)—PDFKit has come into its own. And macOS will be a direct beneficiary of that, giving me confidence that the framework, which had been allowed to stagnate will now receive true support. So, I felt it would’ve been a shame to let these samples fade away! As an exercise, I’ve made them usable once more by updating their code from Tiger and Leopard to build and run in High Sierra.

They all work now—but some polish is still needed. See the Read Me files in their project folders for details.

PDFKitViewer 2.0 illustrates the display of a PDF document.

PDFKitViewer demonstrates some simple and some less than simple uses of PDFKit:

• Basic use of PDFView with single page or side-by-side page display.
• Display of PDFOutline as data for NSOutlineView displayed using NSTableView in an NSDrawer.
• Using PDFDocument to search. The UI has a search tool in the drawer above a Page/Section results list.

Unfortunately, though, PDFKitViewer does not support annotations.

PDFKitLinker2 2.0 presents many features of (Tiger) PDFKit.

This application enables the user to annotate a PDF document by embedding links or editing existing ones. The destination of a link may be another page in the document or an external URL.

PDFAnnotationEditor is Apple’s flagship PDFKit sample program, but it was written for Leopard; PDFAnnotationLink was the one interactive annotation that was properly implemented for Tiger. That’s why this sample was written: at the time, links were the only game in town 🙂

PDFKitLinker also shows how to create and display a PDFOutline of the opened document. If the opened PDFDocument has an outline, PDFKitLinker will use the PDFOutline as data in an NSOutlineView and display it using NSTableView in an NSDrawer. This is a very useful recipe—and worth the price of admission, all by itself 🙂

Familiarity with NSTableView would be very helpful in understanding the code for this sample, but lacking that, it would still be possible to use PDFKitLinker as a “Rosetta Stone” to figure out table views.

PDF Calendar 2.0 uses PDFKit to show you how to generate your own PDF content.

The sample uses a PDFPage subclass to generate a PDFPage from an NSImage. The PDFPage subclass’s draw and bounds methods are overridden. The bounds method returns the image bounds and the draw method displays the image. This PDFPage object can be added to a PDFDocument.

The app generates a calendar from images the user supplies. The resulting PDF document can be saved, printed, etc. The sample also incorporates PDFView and PDFThumbnailView.

Link Snoop 2.0

Link Snoop is a sample application using PDFKit in Mac OS X 10.5 Tiger. When a user opens a PDF with Link Snoop, it scans it for Link annotations that have a URL associated with them and displays the PDF with these annotations highlighted.

The contents of the URL link annotations are also displayed, in a panel consisting of an NSTableView in an NSSplitView.

While lacking NSDrawer’s elegance, this architecture shows the desired workaround for replacing drawers with split views in the other Lost PDFKit Samples that still use NSDrawer.

PDFViewSubclasser 2.0

PDFViewSubclasser shows you how to subclass PDFView to overlay content—by adding subviews—relative to the PDF content.

It uses the new 10.5 PDFView method drawPagePost.

The default implementation of this method draws the text highlighting (if any) for the page. This method does not apply scaling or rotating to the current context to map to page space; instead, the context is in view-space coordinates (in which the origin is at the lower-left corner of the current PDF view).

The Go To Marker button at the bottom of the window uses PDFDestination to scroll the marker into the center of the window. But, unless you resize the window to be smaller so that scrollbars appear, there will not be any place to scroll the marker and the command will appear to do nothing.

PDFAnnotation Editor 2.1

This sample demonstrates how to use PDFKit to inspect, edit, and create annotations in a PDF document.

This is the flagship sample of PDFKit. It was updated by Apple to use the new APIs in macOS 10.13 High Sierra.

NOTE: This is not one of the Lost PDFKit Samples, but I’m including it in this collection because it’s been significantly improved. Version 2.1 can now tab between annotations in edit mode so you can see the responder chain.

The projects are available here:

https://github.com/frameworker/PDFKitViewer
https://github.com/frameworker/PDFKitLinker2
https://github.com/frameworker/PDF_Calendar
https://github.com/frameworker/Link_Snoop
https://github.com/frameworker/PDFViewSubclasser
https://github.com/frameworker/PDFAnnotationEditor

 

December 4, 2017

Zooming Breaks Focus-ring Architecture

Filed under: Uncategorized — frameworker @ 2:36 am

Programatically zooming my app’s window breaks Cocoa’s focus-ring architecture. This happens in 10.13.1 but I believe it was a problem in previous systems.

The main view of my app can be zoomed by the user. It contains NSTextView subviews. The NSTextView focus-rings are well-drawn when the main view is not zoomed. But when it is zoomed, focus rings are not drawn properly. They are drawn the same size, no matter what the zoom factor. And they drift downward as zoom is increased. (see attached screen shots). Note that the text fields themselves are zoomed properly and all mouse clicks are interpreted correctly in zoomed views. Just the focus-rings are wrong.

Is there any way to get zoomed focus rings to work using the Cocoa focus ring APIs? I would like to adopt them, but I can’t since they don’t work for me. N.B. This is bug report #35817176.

This describes my zoom-architecture:

// Here, "self" is an NSImageView subclass containing NSTextViews as subviews.
- (void) doZoom:(float)theScaleFactor
{
    float width = [[self bounds].width;
    float height = [[self bounds].height;
    NSRect zoomedRect = NSMakeRect(0, 0, width*theScaleFactor, height*theScaleFactor*pageCount);

    NSRect boundsRect = NSMakeRect(0, 0, width, height*pageCount);

    zoomedRect = [self roundedRect:zoomedRect]; // Make view corners have integral values.

    [self setFrame:zoomedRect];

    [self setBounds:boundsRect];

    [self setNeedsDisplay:YES];

    [self scrollToTop]; // Will lose relative scroll position before zoom.
}
// Here, "self" is an NSTextField nested in the NSImageView subclass.
// This is the part of the initialization method that's pertinent to focus-ring issue

- (void) initTextField;
{
    [self setFocusRingType:NSFocusRingTypeExterior];
    [self setDrawsBackground:NO];

    [[self cell] setRefusesFirstResponder:NO]; // accept first responder.
    [[self cell] setShowsFirstResponder: YES]; // show   first responder.
}

// If I use Apple's focus-ring APIs, the focus-ring is drawn as if the text-view has not been zoomed.
// And it is shifted downward from it's correct location.

// These two methods comprise the Cocoa focus-ring adoption protocol.

- (void)drawFocusRingMask
{
    // Set the focus ring mask to the zoomed bounds.
    NSRectFill([self focusRingMaskBounds]);
}

- (NSRect)focusRingMaskBounds
{
    return [self bounds];
}
// But if, instead of using the Cocoa APIs,
// I call this method from the drawRect method of the NSTextView (subclass),
// the focusRing scales to fit the zoomed text field.

- (void) drawFocusRing
{
    if ([self focus])
    {
        [NSGraphicsContext saveGraphicsState];
        [[NSColor keyboardFocusIndicatorColor] set];
        NSSetFocusRingStyle(NSFocusRingOnly);
        [[NSBezierPath bezierPathWithRect:[self bounds]] fill];
        [NSGraphicsContext restoreGraphicsState];
    }
}
UNZOOMED:

unzoomed

ZOOMED:

zoomed

April 29, 2013

Extracting & Analyzing PDF Form Data

Filed under: Uncategorized — frameworker @ 9:28 pm

PDF Form Export is an OS X app that extracts field names and values from PDF forms snd puts them into a text file.

To use the app, just drop a PDF Form on it – or “Open…” the form from it. A PDZ file is created in the directory containing the form. The PDZ file contains one line per field – the field names and values are tab-separated – like this:

  • NAME  \T  Some Guy
  • ADDRESS  \T  1234 Somewhere St.
  • etc.

You can then paste the exported data into a spreadsheet or manipulate it with a script. My Benford’s Analysis program, which I wrote as a component of a tax-return-audit-risk-identification suite, is an example of doing this.

When businesses provide forms to customers to be filled out and returned, this utility simplifies data extraction avoiding tedious and error-prone recopying.

The program is written in Objective-C with Cocoa and PDF Kit. PDF Kit makes it straightforward to iterate through a PDF’s form fields extracting their names and values.

October 14, 2011

Thank you, Steve

Filed under: Uncategorized — frameworker @ 6:30 pm

Steve changed my life completely in a good way. First, in the 1980’s, Macintosh became a vehicle that infused my – languishing – career with new purpose. And then again, when I lost my bearing in the last decade, OS X was a nurturing place to come home to. I fervently hope that Steve felt the deep gratitude of the developer community for having begotten this fertile ground for our achievement. Namasté, Steve.

April 20, 2010

Cocoa to Cappuccino – Spatially Formatting Text Fields

Filed under: Uncategorized — frameworker @ 6:18 am

OVERVIEW

I’m using pdf images as the background of electronic forms. The purpose of doing this is to make the electronic form feel just like the familiar paper one. It’s user friendly. Also the electronic forms can perform calculations automatically and accurately.

WHY A WIDE STRING?

One of the cases that inevitably has to be handled is when a string has to be entered, with its characters equally spaced in a sequence of contiguous boxes, like this:

THE COCOA WAY

Cocoa has this nifty NSString method, drawAtPoint, that lets you do this when the field is not active. (But when it is active you can enter the string – unformatted – in the text field, which exactly covers the boxes in the background, so it all feels quite natural.)

- (void)drawRect:(NSRect)rect
{
    if ((![self focus]) && ([self format] == kWideFormat))
    {
        // drawWideString calculates the bounds for each character
        // and calls a routine to draw it using drawAtPoint.
        [self drawWideString: [self stringValue]];
    }
    else
    {
        [super drawRect:rect];
    }
}

THE CAPPUCCINO WAY

Unfortunately, there is no -[CPString drawAtPoint] method in Cappuccino, so this approach can’t be used.

I must confess that this “deficiency” left me with some confusion about how to procceed to implement the WIDE string behavior in Cappuccino.

I wondered if there was a way to do it using Canvas or CSS, or if Cappuccino text support for this kind of thing might be “just around the corner.”

And the sledgehammer approach of creating a sequence of single character text fields to display the inactive text, to be swapped-out with a regular text field while editing, seemed inelegant.

But a recent conversation with @saikatc at #shdh37 convinced me that the “buffered” approach was, in fact, a reasonable way to do this. And as it is with so many things in life, once the approach was determined, it started happening.

KEY MECHANISM

The one CPTextField subclass I use throughout the forms project overrides becomeFirstResponder / resignFirstResponder to bracket the active field with controlTextDidBeginEditing / controlTextDidEndEditing calls, something that neither Cocoa nor Cappuccino does, but which is critical to knowing when to swap the static text array in and out with the regular text field. Having this mechanism obviates the need for a special CPTextField subclass for these WIDE fields!

The Begin/End Editing messages are passed to the Text Field’s delegate, a widget subclass, which sends setFocusedDisplayFormat/setUnfocusedDisplayFormat messages to the object being activated/inactivated.

It’s important to note that the approach used here takes advantage of fact that the text field covers the char-array. If this were not the case, it would be necessary to buffer the char-array’s stringValues, so they wouldn’t be displayed, while the text field was active. That would be confusing.

So to avail ourselves of this pattern, we create a WIDE Widget subclass which switches the display of the static array on and off.

Here’s the code for that class.

PDQWideWidget descends from the concrete PDQTextWidget class and adds an array for the equally spaced characters.

// PDQWideWidget.j

@import "PDQTextWidget.j"

@implementation PDQWideWidget : PDQTextWidget

{
	CPMutableArray chars @accessors; // The array of equally spaced characters
}

Init calls super, then creates the array.

- (id) init
{
	self = [super init];

	if (self)
	{
		// Do any initialization here!
		chars = [];
	}

    return self;
}

makeView is overridden to create the array of one-char text fields. The order in which the constituent fields are created is crucial. The real CPTextField is created last, so it will be on top and receive mouse events. And the widget is put into “unfocused” mode.

- (void)makeView:(CPView)itsSuperview
{
	[self buildChars:itsSuperview];

	[super makeView:itsSuperview];

	[self setUnfocusedDisplayFormat];
}

buildChars builds the array of one-char text fields using the maxLen parameter to determine how many to create that will cover the widgetRect.

- (void)buildChars:(CPView)itsSuperview
{
	var frameRect = [self widgetRect];

	var width   = frameRect.size.width;
	var height  = frameRect.size.height;
	var x	    = frameRect.origin.x;
	var y	    = frameRect.origin.y;

	var cellWidth = width/[self maxLen];

	for (var index = 0; index < [self maxLen]; index++)
	{
		var left = x + cellWidth * index;
		var charFrame = CGRectMake(left, y, cellWidth, height); // x,y,w,h

		var newCharField = [[CPTextField alloc] initWithFrame:charFrame];

		[self initCharField: newCharField];
		[newCharField setStringValue: @""];
		[newCharField setDelegate:self];
		[itsSuperview addSubview:newCharField];
		[chars addObject: newCharField];
	}
}

Each charField must be initialized to (among other things) not accept events nor become a responder.

- (void) initCharField:(CPTextField)aCharField
{
	[aCharField setBordered:NO];
	[aCharField setBezeled:NO];
	[aCharField setEditable:NO];
	[aCharField setEnabled:NO];
	[aCharField setSelectable:NO];
	[aCharField setAlignment: CPCenterTextAlignment];
	[aCharField setBackgroundColor:[CPColor clearColor]];
	[aCharField setDrawsBackground:YES];
	[aCharField setVerticalAlignment:CPCenterVerticalTextAlignment];
	[aCharField setFont:[PDQAbstractWidget getFont]];
}

When the text field is focused, compose and set its stringValue from the char-array. The TextField will be displayed over the char-array, masking it.

- (void)setFocusedDisplayFormat
{
	// Build the stringValue from the char-array

	var itsStringValue = @"";

	for (var index = 0; index < [chars count]; index++)
	{
		var aCharField = [chars objectAtIndex: index];
		var aChar = [aCharField stringValue];
		itsStringValue += aChar;
	}

	[[self attachedControl] setStringValue:itsStringValue];
}

When the text field loses focus, or is first created, unpack stringValue into the char-array, then clear stringValue. The equally spaced chars will be displayed, but the empty TextField covering it, will not.

- (void)setUnfocusedDisplayFormat
{
	// Set the chars from stringValue and then clear it.
	var itsStringValue = [[self attachedControl] stringValue];
	var count = [itsStringValue length];

	for (var index = 0; index < count; index++)
	{
		var aCharField = [chars objectAtIndex: index];
		[aCharField setStringValue: [itsStringValue characterAtIndex:index]];
	}

	[[self attachedControl] setStringValue:@""];
}

 

@end

March 20, 2010

OPTIMIZING PDQFORMS

Filed under: Uncategorized — frameworker @ 7:52 pm

I’d been testing PDQForms and hadn’t seen any performance problems, but then I saw a noticable recalculation delay when certain fields were changed in a particular form.

After a moment of doubt whether my approach was simply wrong, I sucked it up and asked myself “What would Mike Ash do?”

So I jumped into the debugger, and after tracing the flow of execution – aided by liberal logging of intermediate results – I realized that I was seeing a cascading dependency problem.

I was adding a notifier for each cell reference in a formula, so when it had more than one reference to the same cell, I was creating duplicate notifiers. And if that cell was referenced more than once in another cell’s formula, there would be duplicated recalculations. This is what I was seeing*. And the problem could become arbitrarily worse than this, since there could be an indefinite coupling of such formulae. Ouch!

* Formula A, of cell a, has n references to cell b, who’s formula B contains m references to cell c. So when cell c changes, formula B would be recalculated m times and formula A would be recalculated m * n times.

The solution to this cascading dependency problem was to allow only one notifier for any cell reference in a formula, even if the cell was referenced more than once in that formula.

THE PATTERN

When a PDQ document is opened, its form widgets are “internalized.” One step in this process is, for widgets that have a formula, to add observers to cells referenced by that formula. This stack-trace depicts the widget internalization pattern.

-[PDQDocument windowControllerDidLoadNib:]
Code added here is executed when the windowController has loaded the document’s window.

  -[PDQDocument internalizeWidgets]
  This contains the widgets’ internalization logic.

    -[PDQDocument observeReferencedCells]
    This document method calls observeReferencedCells for each widget.

      -[PDQAbstractWidget observeReferencedCells]
      Adds notifications to observe each cell referenced by this widget.

        -[NSString coalesceObservers]
        Constructs the observer list and removes duplicates, before adding notifications.

THE CODE

Here is the add/coalesceObservers code associated with the widget internalization pattern.

observeReferencedCells creates an array of the referenced cell IDs. Then it finds the object referenced by each ID and adds an observer to it.


- (void) observeReferencedCells
{
    if ([self hasExpression])
    {
        NSMutableArray * observers = [[self expression] coalesceObservers];

        int index;
		
        for (index = 0; index < [observers count]; index++) // Work OK for empty array?
        {
            NSString * theToken =  [observers objectAtIndex:index];
            
            // iterate the document's widgets (a global variable)

            PDQAbstractWidget *referencedCell = [self findWidgetWithID:theToken];
            [self addObserverToReferencedCell:(PDQAbstractWidget *)referencedCell];
        }
    }
}

coalesceObservers constructs the observer list, avoiding duplicates, by copying one instance of each cellRef token into coalescedObservers before adding notifications


- (NSMutableArray *) coalesceObservers
{
    NSMutableArray * theTokens = [self createTokensForExpression];
    NSMutableArray * coalescedObservers = [NSMutableArray array];

    int index = 0;
    while (index < [theTokens count])
    {
        NSString * theToken = [theTokens objectAtIndex:index];

        if ([theToken tokenType] == eCellRefToken)
        {
            [coalescedObservers addObject:theToken];
			
            // Remove all occurrences of theToken from theTokens.
            [theTokens removeObject:theToken];
        }
        else
        {
            index++;
        }
    }

    return coalescedObservers;
}

When theReferencedCell changes value addObserverToReferencedCell tells the dependent cell to handleVariableChanged by sending the NSNotificationCenter a changed message.

The NSNotificationCenter then sends the observer a PDQReferencedCellChanged message with an object reference to the cell that changed.


- (void) addObserverToReferencedCell:(PDQAbstractWidget *)theReferencedCell
{
    NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];

    [nc addObserver:self
           selector:@selector(handleReferencedCellChanged:)
           name    :@"PDQReferencedCellChanged"
           object  :theReferencedCell];
}




handleReferencedCellChanged is the “action procedure” being set by addObserverToReferencedCell.


// Update the cell's value since a cell it depends on has changed.
- (void) handleReferencedCellChanged:(NSNotification *)notification
{
    [self recalculate];
	
    // Now say "changed" to tell the cells that depend on me to update also. 
    NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:@"PDQReferencedCellChanged" object:self];
}

February 8, 2010

Cocoa to Cappuccino – Thinking About Strings

Filed under: Uncategorized — frameworker @ 11:52 pm

#cocoa-to-cappuccino

I found working with strings in Cappuccino to be more logical than in Cocoa, but I experienced some uncertainty about what methods and functions were available in JavaScript. So I thought this example and writeup might be useful to others, who are coming to Cappuccino from Cocoa, as many of us are.

One of the main differences between Cocoa and Cappuccino when working with strings, is that Cappuccino lacks a scanner class. So Cappuccino applications must handle scanning by themselves. I thought it would be useful and illustrative to implement a Category that performs scanning, similar to Cocoa’s NSScanner. And since JavaScript strings are toll-free bridged to Cappuccino’s CPString class that was not too difficult.

I’ve constructed my API as a Category, rather than as a Subclass, so it can be used with all CPStrings. It corresponds roughly to NSScanner, but doesn’t mirror it.

I’ve maintained a Cocoa-like style. This may change as time goes by, but for now it feels more readable, especially since I’m going back and forth between Cappuccino and Cocoa.

And I haven’t addressed performance issues in writing this. The code is adequate for my purposes. But it would be interesting to profile and optimize it somewhere down the line.

IMPLEMENTATION NOTE: I’m not currently supporting “skip characters.” That’s because the next scan position is determined by the length of the previously scanned string. If you skip characters there isn’t a simple way (that I could think of) to communicate this to the next use of the the scanner. Also all scans are case sensitive. An extended scanning category could add methods to support these. But for now, I’m avoiding that to keep things simple.

If you’re not familiar with NSScanner, it’s useful to note that the term “scan” means scanning from a particular starting point. That is, if you’re scanning for a particular string and it isn’t at the starting location of the string being scanned, then an empty string will be returned.

I’ll summarize the API here, but it will be much more instructive to view the source, which I’ve wrapped in a test program called cappscanner.

SCANNING METHODS

scanString – scans SELF, returning theString if a match is found.

    -(CPString)scanString:(CPString)theString startingAt:(int)startIndex

scanUpToString – scans SELF until a given string is encountered, accumulating characters into a string that’s returned. Scans to the end of SELF if stopString is not found.

- (CPString) scanUpToString:(CPString)stopString startingAt:(int)startIndex

scanUpToCharactersFromSet – scans SELF until a stopChar is encountered, accumulating characters into a string that’s returned. Scans to the end of SELF if no stopChars are found.

-(CPString)scanUpToCharactersFromSet:(CPString)stopChars startIndex:(int)index

scanCharactersFromSet – scans SELF as long as charsToScan are encountered, accumulating characters into a string that’s returned. Returns an empty string if no charsToScan are found.

-(CPString)scanCharactersFromSet:(CPString)charsToScan startIndex:(int)index

UTILITY METHODS

stringByReplacingString – replaces “target” with “replacement”, where “target” is a substring of SELF.

- (CPString)stringByReplacingString:(CPString)target withString:(CPString)replacement

setCharacterAtIndex – replaces the character at “index” in SELF.

-(CPString)setCharacterAtIndex:(unsigned)index theChar:(unichar)character

filterString – returns a copy of SELF filtering out the specified characters.

-(CPString)filterString:(CPString)charactersToRemove

stripPrefix – returns a copy of SELF without thePrefix. Does nothing if SELF doesn’t have thePrefix

-(CPString)stripPrefix:(CPString)thePrefix

stripSuffix – returns a copy of SELF without theSuffix. Does nothing if SELF doesn’t have theSuffix.

-(CPString)stripSuffix:(CPString)theSuffix

dropCharacters – drops numCharsToDrop from the end of SELF. Does nothing if charsToDrop > [string length]. Returns an empty string if numCharsToDrop == [string length]

-(CPString)dropCharacters:(int)numCharsToDrop

TEST RELATED METHODS

decimalTail – returns the tail of a decimal string.

-(CPString)decimalTail

formatNodecString – replaces the period in a formatted decimal string with a single space character.

-(CPString)formatNodecString

formatNosepString – removes commas and the period from a formatted decimal string.

-(CPString)formatNosepString

removeSurroundingParentheses – strips any leading or trailing spaces too. N.B. Won’t remove an odd parenthesis on one end!

-(CPString)removeSurroundingParentheses

parseScript – parses the if, then and else components of a script string. Notice how the scanner walks down the script using the cumulative offset of previously scanned components. This is illustrative of a repetitive scanning pattern.

-(void)parseScript

rectFromAnnot – converts the RECT string from a pdf annotation (e.g. RECT [432.97 580.92 441.86 589.95]) into a CGRect.

-(CGRect)rectFromAnnot

scanRect – scans the RECT string found in pdf annotations. Returns an array of strings for the left, bottom, right and top coordinates. Note that scanRect also employs a repetitive scanning pattern.

-(CPArray)scanRect

tokensSeparatedByCharactersFromSet – breaks the input string into an array of substrings.

-(CPArray)tokensSeparatedByCharactersFromSet:(CPString)separatorSet

SCANNING TESTS

When you double-click the index.html file and then click the “Perform Scan Tests” button in the Scan Tests window, a Cappuccino Run Log Window will appear that contains these statements:

  Performing scan tests.

  Testing Scanning Methods.

  Scan if-then-else script.

  script is =IF(L222<12000;3500*L106e;0)
  scriptIf = L222<12000
  scriptThen = 3500*L106e
  scriptElse = 0

  Scan pdf style Rect.

  Build CGRect.

  left = 432.97
  bottom = 580.92
  right = 441.86
  top = 589.95

  Testing Utility Methods.

  Test stringByReplacingString

  string A plus string B
  string A + string B

  Test setCharacterAtIndex

  1234567
  A2C4E6G

  Test stripPrefix

  Mr. Coffee
  Coffee

  Test stripSuffix

  String Jr.
  String

  Test dropCharacters

  123.45
  123

  Testing Test Related Methods.

  Test decimalTail

  1,099.87
  87

  Test formatNodecString

  1,099.87
  1,099 87

  Test formatNosepString

  1,099.87
  109987

  Scan tests complete.

“It works” 🙂

My thanks to the Cappuccino Community, and especially to the Core Team.

September 11, 2009

How to constrain window size in Cappuccino?

Filed under: Uncategorized — frameworker @ 8:13 pm

I’m displaying an image in a CPWindow and wanted to keep the window from getting bigger than the image it’s displaying. I tried setting the window’s maximum size in applicationDidFinishLaunching. But that didn’t accomplish what I wanted; I’m still able to make the window arbitrarily large.

However, there is a change in behavior when setMaxSize is called.  The scroll bars persist at the maxSize position until both x and y are greater than maxSize.

With maxSize set, as you grow the window vertically, the horizontal scroll bar is fixed at the maxSize position and there is white space between the scroll bar and the bottom of the window.  Also, the vertical scroll bar is depicted as an empty, shaded, rect.

CPWindow

Once you make the window bigger than both maxWidth and maxHeight both scroll bars disappear and the window looks just like it would in the case where maxSize isn’t set.

In the case when maxSize isn’t set, as you grow the window vertically, the horizontal scroll bar is displayed at the window’s bottom edge with white space separating the bottom of the image and the scroll bar.  And if you make the window wider than the image’s width, the horizontal scroll bar disappears.

However, there is a change in behavior when setMaxSize is called.  The scroll bars persist at the maxSize position until both x and y are greater than maxSize.
With maxSize set, as you grow the window vertically, the horizontal scroll bar is fixed at the maxSize position and there is white space between the scroll bar and the bottom of the window.  Also, the vertical scroll bar is depicted as an empty, shaded, rect.  Once you make the window bigger than both maxWidth and maxHeight both scroll bars disappear and the window looks just like it would in the case where maxSize isn’t set.
In the case when maxSize isn’t set, as you grow the window vertically, the horizontal scroll bar is displayed at the window’s bottom edge with white space separating the bottom of the image and the scroll bar.  And if you make the window wider than the image’s width, the horizontal scroll bar disappears

How do you constrain the window’s size? Do I need to do something in addition to setMaxSize? Is a different approach required to do this?

Here’s my AppController.j source code.

@import <Foundation/CPObject.j>
@import <Foundation/CPString.j>

@implementation AppController : CPObject
{

}

- (void)applicationDidFinishLaunching:(CPNotification)aNotification
{
    var kImageWidth  = 612.0,
        kImageHeight = 792.0,
            kMargin  = 16.0;

    // Create a window to take up the full screen

    var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask],

        contentView = [theWindow contentView],

        bounds = [contentView bounds];

    // Create a scrollView to contain the pdf image

    var scrollView = [[CPScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(bounds), CGRectGetHeight(bounds))];

    [scrollView setAutoresizingMask: CPViewHeightSizable | CPViewWidthSizable];

    [scrollView setAutohidesScrollers:YES];

    // Create the image and imageView.

    var theImage = [[CPImage alloc] initWithContentsOfFile:[[CPBundle mainBundle] pathForResource:@"testImage.pdf"]];

    // Create the image view.

    var imageView = [[CPImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, kImageWidth, kImageHeight)];

    // Put the image in the imageView.

    [imageView setImage: theImage];

    // We don't want the image to resize.

    // (Could have [imageView setAutoresizingMask:CPViewNotSizable | CPViewNotSizable] instead.)

    [imageView setImageScaling: CPScaleNone];

    // Put the imageView in the scroller.

    [scrollView setDocumentView:imageView];

    // Put the scroller in the window's view hierarchy.
    [contentView addSubview:scrollView];

    var maxWidth   = kImageWidth  + kMargin,

        maxHeight  = kImageHeight + kMargin,

        theMaxSize = CPMakeSize(maxWidth, maxHeight);

    [theWindow setMaxSize: theMaxSize];

    // Bring the window forward to display it.

    [theWindow orderFront:self];
}

@end

June 29, 2009

Inside PDQForms

Filed under: Uncategorized — frameworker @ 9:31 pm

Overview

PDQForms is tax preparation software for State and Federal forms. It integrates spreadsheet logic into pdf forms using PDFKit to combine form field information with labels and expressions. The result is a spreadsheet-like application layer over the form.

Creating a PDQ Form

The idea was to automate
everything that could be.

The first step is to extract information for all the form’s fields, or “Annotations” in PDF lingo.

We need the type of Annotation: TEXT or CHECKBOX, and its PAGE, RECT and MAXLEN values.

This is accomplished with a PDFKit based program called PDQ Annotation Editor, which outputs a text file.

Next we must define expressions that contain the logic for each of the form’s fields. This is just like programming a spreadsheet.

Adding this information to the Annotation meta-data completes our task.

We now have a text file containing the information PDQForms will need to automate the form.

We then “bake” this back into the original PDF file.

And the form can now be opened with PDQForms!

Older Posts »

Blog at WordPress.com.