TweetFollow Us on Twitter

March 92 - A Clear View of Ten Behaviors

A Clear View of Ten Behaviors

G. Gordon Apple

In the beginning were the system and the toolboxes.

Then came object programming and the MacApp framework . Subclasses were brought forth abundantly after their kind, and views-types proliferated. Their number and complexity intimidated many, preventing them from approaching the framework.

Now there are behaviors that allow generic views to take on characteristics and capabilities as needed. This article discusses a set of drawing (actually, object manipulation) behaviors, showing how behaviors can provide an enhanced level of functional encapsulation and program modularity.

Out of the Chaos

MacApp beginners, myself included, tend to want to dump all their code into subclasses of TView. When I first read the Programming with MacApp books (Wilson, Rosenstein, and Shafer), I was surprised by the use of "helper" classes where the subview mostly consisted of "diversionary" or "deflection" methods that simply pass the calls to the helper class.

Most of these deflection methods involved event handling; menu commands or mouse downs, drawing, highlighting, and cursor control. Therefore, I was pleasantly surprised when behaviors were introduced to provide exactly that type of support in a generic TView or any subclass of TView (actually, any TEventHandler). I set out to see what behaviors might imply in code organization.

The program I chose was originally done in Pascal with MacApp 2 and was based on the ExampleDraw program in the Programming with MacApp book. A good place to start seemed to be the C++ version of the same. Unfortunately, it was also written for MacApp 2, so major code surgery lay ahead. This gave me the opportunity and the excuse to totally revamp the code organization to use behaviors, one of MacApp 3's most powerful and versatile features.

The program document consists mainly of a list of shape objects that can be drawn on the screen or the printed page. I extended the architecture to include more general items such as Views, PICTs, and now MooVs. However, they are all still manipulated as if they are draw objects.

I decided to create the behaviors and partition the code by functionality rather than by common elements or code similarity. I hoped this would result in more versatile modules. I took the approach of a creator itemizing the functionality (behaviors) imparted to the creations. This resulted in:

The Ten Behaviors

  1. Those on the list, show yourselves within the View in listed order and whenever your domain is revealed and requires updating. (TDrawItems)
  2. Those who are touched or who are within a selected area shall themselves be selected and appropriately adorned to highlight their status. (TSelectItems, TItemsSelectionAdorner)
  3. Those who are selected, move right, left, up or down when commanded, remembering your roots in case the command be undone. (TMoveItems)
  4. The selected, take on the indicated colors, patterns, and sizes which have been selected from abundant menus and palettes. (TModifyItems)
  5. The selected, your extremities shall be grabbed and your dimensions adjusted. (TResizeItems).
  6. The selected, the order of your appearance may be advanced or retarded, even to the beginning or the end. (TReorderItems)
  7. New items shall be created in your midst, cloned from the palette and sketched in accordance with current parameters. (TCreateItems)
  8. The selected, clone yourselves and give up your clones to the temporary holding area. (TCopyItems)
  9. The selected, hide until freed, or clone yourselves as before, or accept as your own the clones arriving from the temporary holding area. (TCutPasteItems)

    Well, that should about do it. But didn't I say "Ten Behaviors?" What about those items in limbo, the temporary holding area where everybody gets clipped and bored? Not much going on there. Only the first behavior from this list is needed. Also, the View in limbo is not quite so pure in that diversion methods were not provided for interfacing to the outside world. Word and pictures were provided for, but not our own private I/O. Therefore, the slightly impure view (a subclass of TView) simply deflects the necessary actions to the tenth behavior:

  10. Tell, when asked, what types of items can be supplied from the desk scrap, give of such when asked, and tell how much viewing space they require. Also, give up the data to the desk scrap before sleeping or dying. (TClipboardItems)

Using the Behaviors

The "Ten Behaviors" provide a display, drawing, and editing environment that works in a generic TView and, I hope, can also be applied to any reasonable subclass of TView.

To implement the full set of drawing features, the behaviors are attached to the TView as shown in Figure 1. TView contains a single behavior reference member that points to the first behavior object if any are present. Otherwise it is NULL. Each behavior links to the previous and next behavior to form a two-way linked chain. If the View's (EventHandler's) behavior reference in not NULL, all events, draw messages, cursor control, etc. are diverted to the first behavior. By default, the behavior simply propagates the message to the next behavior. Each behavior had a method that allows it to find the "owning" Event Handler (or View). If there is no next behavior, the message is passed directly back to the EventHandler's (e.g., the view's) equivalent method. To attain conditional or absolute control over this message propagation, simply override the appropriate method in a behavior subclass.

Normally, a PrintHandler behavior gets attached to the main view. The TDrawAdorner gets automatically attached whenever any other adorner is attached. We don't use the draw adorner here, but MacApp attaches one whether or not we make use of it. The order of behavior attachment is mostly irrelevant except that TCreateItems, TResizeItems, and TSelectItems should be in the indicated order. Note that these are not class relationships. These are actual behavior objects linked in a chain. (Adorners are in a list.)

The document has a TShapeList that contains all of the draw objects, whether rectangles, ovals, views, PICTs, or MOOVs. Each behavior derives from TItemsBehavior which has a reference to this same list. Thus each behavior has the same list reference. Multiple storage could have been eliminated by referencing back through the view to the document. This is an almost trivial change due to the use of the accessor method GetShapeList(). [By the way, I'm becoming a real convert to private field variables with accessor methods. They are more work initially, but they prove their worth when code changes and debugging are required. This way, everyone has to always come through the front door rather than slipping in through a window. At least you can find out who's trashing the place.]

The behaviors were implemented so as to be almost independent. In one case, a reference to a clicked shape is stored in TShapeList rather than requiring a reiteration of the list. If the first iterating behavior is missing, the other behavior will go ahead and do its own iteration.

The "Ten Behaviors" pretty much describe the basic functions of each behavior. Most of the basic code fragments are available in the C++ version of the Programming with MacApp book, although many require modification for MacApp 3. A list of field variables and methods, generated by Object Master, is shown in Figure 2.

Note again that the TView is just that-a generic TView, not a subclass. The TDrawItems behavior simply draws the list in the view. We debated whether to make this a behavior or an adorner. They both have draw methods. We decided that a behavior was preferred for our purposes, but the choice was not obvious. Having the Draw behavior separate from the other behaviors allowed it to easily be attached to any view, e.g., the clipview, where only displaying is required.

TMoveItems allows items to be dragged about the screen. For example, this can be used with TDrawItems and TSelectItems (no selection adorner) for a more sophisticated puzzle similar to the simple one supplied with HyperCard 2, or a game of checkers or chess.

TModifyItems allows change in appearance of items without moving them. An example would be trying different color schemes for interior decoration or fabric selection.

TReorderItems can be used for an address selection flip-pad (read only, supplied by a catalog company ) or for arranging slides.

TResizeItems would likely be used only if TMoveItems were also present.

TCreateItems would likely be used only if a selection palette is available to choose what is going to be created.

TCopyItems can be used in a read-only object source file, such as a template library.

TCutPasteItems allows items to be removed from or added to the clipboard.

Several of the above also require TSelectItems, with or without selection adornment (highlighting).

Clearly a large number of combinations of behaviors are possible. They can even be inserted and removed as needed. For example, an interactive multimedia authoring environment could allow a teacher more freedom to change the contents of a program used by students.

The Clipboard

In the quest to use pure TViews for most drawing environments, we kept getting bashed by the clipboard. No matter how long we stared at it, there were four clipboard-related methods that just wouldn't go away.
  • CalcMinFrame
  • ContainsClipType
  • GivePasteData
  • WriteToDeskScrap

We decided to use a slightly specialized clipboard view. We decided to use the behavior mechanism and a TClipboardItems behavior even though the latter is a little more than a convenient code bucket. You'll see why shortly.

Views already have a means to communicate with behaviors through the behavior chain. Someone with foresight added a method to TEventHandler so we could call down the behavior hallway chain and say, "Charlie Brown, where are you?" If Charlie Brown is there, he shouts back down the hall, "I'm here in room 314." The configuration to do this is shown in Figure 3.

The TClipboardItems behavior class was assigned a fixed identifier of 'CVIL'. The view code is as follows:

#pragma segment ShapeClip
pascal void TShapeView::CalcMinFrame(VRect& minFrame)
/* override */
{
    TBehavior* theBehavior = GetBehaviorWithIdentifier('CVIL');

    if (theBehavior)
        ((TClipboardItems*)theBehavior) -> CalcMinFrame(minFrame);
    else
        inherited::CalcMinFrame( minFrame);
}

#pragma segment ShapeClip
pascal  Boolean TShapeView::ContainsClipType(ResType aType)
                                                       /* override */
{
    TBehavior* theBehavior = GetBehaviorWithIdentifier('CVIL');
    
    if (theBehavior)
        return ((TClipboardItems*)theBehavior)
            -> ContainsClipType(aType);
    else
        return inherited::ContainsClipType( aType);
}

#pragma segment ShapeClip
pascal  long    TShapeView::GivePasteData(Handle aDataHandle,
                                    ResType dataType) /* override */
{
    TBehavior* theBehavior = GetBehaviorWithIdentifier('CVIL');
    
    if (theBehavior)
        return ((TClipboardItems*)theBehavior)
                    -> GivePasteData(aDataHandle, dataType);
    else
        return inherited::GivePasteData( aDataHandle, dataType);
}

    #pragma segment ShapeOpen
pascal  void    TShapeView::IShapeView( TDocument* itsDocument,
                                TView* itsSuperview, 
                                VPoint& itsLocation,
                                VPoint& itsSize, 
                                SizeDeterminer itsHSizeDet,
                                SizeDeterminer itsVSizeDet)
{
    this -> IView(itsDocument, itsSuperview, itsLocation,
                                itsSize, itsHSizeDet, itsVSizeDet);
}

#pragma segment ShapeClip
pascal  void    TShapeView::WriteToDeskScrap() /* override */
{
    TBehavior* theBehavior = GetBehaviorWithIdentifier('CVIL');

    if (theBehavior)
        ((TClipboardItems*)theBehavior) -> WriteToDeskScrap();
    inherited::WriteToDeskScrap();  /* Write a QuickDraw picture. */
}

In the case of CalcMinFrame, ContainsClipType, and GivePasteData, if the indicated behavior is present, the view diverts the call to the clipboard behavior. Otherwise, it calls the inherited method. WriteToDeskScrap calls the inherited method regardless, because most applications will at least output a PICT or TEXT in addition to a private scrap type and MacApp automatically provides these as defaults.

It works great! I've been using it for several months now and its simple, non-intrusive code which can be used in any view class. Just don't forget to attach the behavior. If you do, it won't crash, but it won't handle your private scrap either. The exact code used for the view and the behavior is included on the subscription code disk.

These conditioned diversions to a behavior could be added to MacApp in these four methods in TView. (The "else" part of each method should be deleted in that case.) It is non-intrusive and results in identical functionality to that at present if the indicated behavior is not present. It would allow a generic TView to be used in the clipboard. It could be hard-wired for a specific identifier, or the identifier could be set in another field variable, although I don't believe that is really necessary.

Past and Future

The code for these behaviors is largely derived from the C++ version of Programming with MacApp. The TShapeView Class was essentially eliminated except for its use as the clipboard View. The TShapeViewHelper unit was totally revamped and reorganized into separate behaviors. TShapeResizer and TItemsSelectionAdorner were added. The entire project was brought completely up-to-date from MacApp 2 through interim alpha and beta versions to the present version (3.0b3 at this writing).

The TStream classes and TStreamObject class were eliminated because they are now incorporated into MacApp. Other types of draw shapes have now been added, including the handling of views as draw objects, (including TTEViews) and PICTS.

We have plans to incorporate the graphical linking objects that were demonstrated last year at the Phoenix MADA conference (see the demo on the Phoenix conference CD ROM). We also hope to include all the drawing and text edit menus into our floating palette for ease of incorporation into other programs. We plan to handle multiple drawing layers in the same view.

Conclusion

Behaviors allow another level of abstraction and encapsulation. More importantly, they allow a level of portability and reusability that has not existed before, even in an object programming environment.

We discovered that behaviors provide a much clearer demarcation of responsibilities between what MacApp provides and what the application programmer must provide. This can't do anything but help, considering the sense of overwhelming intimidation many feel when confronted with the raw guts of the beast. Behaviors are a lot less intimidating. After all, what is a View if not simply a place for drawing and clicking? Do we really need to face a six-foot fine-print scroll list (in Object Master) of TView method names?

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.