Rubber banding

The program Rubber.m3 shows how to do rubber banding. Rubber banding is frequently used to select a rectangular region of a VBT. The mouse and position methods play an important role in rubber banding. So we need to understand these methods first.

A mouse method is called by Trestle whenever there is a mouse event; i.e., when a mouse button is pressed or released. The second parameter to the mouse method contains information about the mouse event such as which button was involved and whether it was pressed or released. Using this information, we can do some action in response to a particular mouse event.

A position method is called by Trestle whenever the mouse leaves the cage of the VBT. A cage is a set of cursor positions. The cage of a VBT can be set to contain a single position, a rectangle of positions inside a VBT, all of the positions in a VBT, or all of the positions outside a VBT.

The application program Rubber.m3 a simple leaf VBT. A rectangular portion of the VBT can be selected by pressing a mouse button down and dragging the cursor to the opposite corner of the area. When the button is pressed the current position, the first corner of the area, is saved. Each time the cursor is moved a new rectangle is drawn showing the area between the saved corner and the current position. When the button is released the second corner is saved. Nothing is done with the region. The last rectangle is not even erased, although normally it is no longer important. The rectangle is not redrawn, even if the application is revealed after being covered by another application. The repaint procedure would be responsible for maintaining the appearance of the selected region if, for example, it were to be redrawn or displayed in a different color. The following images

depict two different views of the application, although there is not much to see. Two views are shown each with a different rectangle. The cursor is not shown in these figures.

The PaintOp.Swap operation is used to draw and erase the rectangle. The swap operation ensures that original pixels on the path are restored when the path is erased. To implement rubber banding four things are done in the mouse method.

  1. Set a flag to indicate that the rubber banding has begun.
  2. Start a new rubber banding path.
  3. Save the cursor position.
  4. Set the VBT's cage to the current cursor position so that Trestle calls the position method when the mouse leaves the current position.

The following actions are done in the position method if rubber banding is currently taking place.

  1. Erase the previous rubber banding path if it exists.
  2. Build a new rectangular path using the current position as one corner.
  3. Draw the path.
  4. Set the VBT's cage to contain only the current cursor position. This makes Trestle call position method again as soon as the cursor leaves the current position.