TweetFollow Us on Twitter

Ports
Volume Number:1
Issue Number:4
Column Tag:C Workshop

Ports

By Chris Derossi

When one thinks of the Macintosh, one of the first things to come to mind is the Mac’s frequent use of windows for multiple, independent areas or objects. Usually, one window is related to one task or concept, and tasks that have very different orientations are in separate windows.

There are several benefits for grouping items or tasks into separate windows. The most important is user interfacing. By using windows, the user can conceptually group similar or common things. This makes the use of sotware more intuitive because the user is shielded from modes in the software. In other words, instead of explicitly needing to have the computer switch to a different mode, all that is needed is to begin operations in a different window.

Obviously, the more intuitive for the user that your software is, the better. Indeed, one of the primary concepts of the Macintosh is that of using tools like icons, the mouse, and windows to decrease the need for special knowledge or special education. In this article, we will take a look at the concept behind windows, that of ports. (In a later article, we will examine windows more closely.)

In order to facilitate the creation of independent windows, the implementation of ports or graph ports provides for completely separate drawing envir- onments. That is, each port is an entire drawing environment, and operations with one port are not related to another.

At any given time, after QuickDraw is initialized, a single port is always active, and is considered the current graph port. QuickDraw operations always occur within the current graph port.

With each graph port are associated several characteristics and parameters. These include location of the port’s bit map, size, clipping region, visible region, background color, and several text mode values. The port’s bit map refers to an area of memory where the bit image of any drawing is put. Usually, this coincides with an area of the screen ram, so that drawing is displayed on the screen. However, this is not a requirement. The port’s bit map can be any area of memory on or off the screen. For example, a port may use an off-screen bit map to prepare an image, then move that image into the screen bit map.

The size of the port is determined by an enclosing rectangle. The rectangle encloses part of the bit map and indicates size and position within the bit map. For ports that are visible, the rectangle encloses an area of the screen.

Clipping region and visible region both restrict the available drawing area within a graph port. While the port itself is rectangular, the clipping and visible areas are regions, providing total flexibility with shape and configuration. The visible region acts like a clipping region, but is separate from it mainly for use by the window manager. (When one window overlaps another, the visible region of the bottom window is set to equal the part of the port that still shows.) There are two regions so that the user may have a region for clipping that is unrelated to the the region needed by the window manager for handling overlap.

Each port is its own drawing environment, and as such has its own drawing characteristics such as pen size, pattern, position, etc. Also, each port has its own text drawing characteristics that are used by the font manager. This way, you need only choose which port in which to draw, and the font, style, and text size associated with that port are automatically used.

In addition to having its own locations, size, and modes, each graph port may also have its own coordinate system. That is, regardless of where on the screen the port is displayed, the upper left corner of the port may be any coordinate. Usually, of course, the upper left coordinate is assigned the value 0,0. This is useful because neither the user nor the programmer need be concerned with the actual position of any port; drawing may be made as if the port were the entire universe. (You might begin to see why moving windows around is so easy; the coordinates inside the window remain constant.)

Since the available coordinate plane is much larger than any visible graph port, this feature allows ports to ‘look at’ different areas of the coordinate plane. For example, a program may draw on the entire plane, and different graph ports may be created as neccessary to view separate parts of the entire area. This can be done without the need for conversions either in the drawing or the displaying; QuickDraw handles all conversions.

There are two important programming practices to develop with regards to ports. The first has already been mentioned; it is a good idea to group similar things, and separate dissimilar things. The second idea is that of port independence. Programs should be written to not rely on any port size or location. (When changing the size of a window, for instance, the program should NOT need a certain size window to perform.)

The sample program this month illustrates the second concept, as the first one is much easier to practice. In this program, the user ‘creates’ television sets on which drawing is displayed. While drawing is occurring, the user may create more TVs, or change which one is active. All this is done by clicking the mouse. If the mouse is clicked in a TV, it becomes the active one, if not, a new TV is created.

Each TV, of course, is a graph port. A port is created, and then in that port a television is drawn. Then, the clipping region of that port is restricted to the ‘picture tube’ part of the picture.

Drawing continues, regardless of which port is active, or where it is. The placement of the port, and the selection of the current port is entirely up to the user. Notice, that the main drawing procedure has absolutely no idea which port is active.

In order to avoid running out of memory, the number of possible ports is restricted. You may vary the constant ‘MaxPorts’ as you like. An array is set up called ‘Screens’ which contains pointers to the graph ports. QuickDraw procedures and functions that act upon ports take a pointer to the port as the parameter, not the port itself. The port is left to be dynamically allocated for flexibility. The type ‘GrafPtr’ is the predefined pointer to a graph port.

The variable ScrnCnt keeps track of how many ports we have created. Since we want to draw only on our TV screens, drawing does not occur if the user has not created any ports yet. When the user clicks the mouse, the program checks to see if the position of the mouse is inside any graph port. The point must first be brought to global coordinates, which makes it independent of any port. Then, one by one, the point is referenced to each graph port and checked against that port’s rectangle. If the point is inside the rectangle, that port is selected as the current one.

When the point lies outside all ports, a new port is created. (Unless all possible ports have been created already; then the program terminates.) The port is initialized and its characteristics are set. Then, the TV is drawn in the port, and the clipping region set. The new port is also set as the current port. Notice that the program explicitly sets the port’s origin. Try playing with the origin values.

When the program ends, it closes each port one by one and frees the memory used by the ports. Then, it creates another temporary port that covers the entire screen. (The default values for the size and location of the port coincide with the screen.) This port is then filled with gray to eliminate the other graphics. Finally, this temporary port is also closed and its memory freed.

Although this is a simple example, it demonstrates a very powerful principle; that of independence. The more independent you programs are, the more flexible they are, and the more control the user may have. This avoids placing pointless limitations on your programs and their users. In addition, programming of this nature helps keep programs functional when the environment changes. (Like moving from a Mac to the Lisa with MacWorks, or future, improved machines.)

This concludes our introduction to the basics of QuickDraw. With this foundation, we can move on into the rest of the Macintosh with a strong background. You might want to try and improve on this sample program as an excersize to increase your skill. For example, try to allow the user to select the size as well as the location of the port. Or, try to prevent the ports from overlapping. If you’re really enthusiastic, have all the TV sets going at once, and let the user change ‘channels’ on each of them, causing different graphics to appear on each channel.

In the next issue, we’ll extend the discussion of ports to windows. We’ll find out what the concept of windows adds to the already powerful idea of ports, and find out what features are provided to the user through the use of windows. Ciao.

program Ports_Demo;

{ Ports_Demo - for MacTutor}
{ -- by Chris Derossi}

 uses
  QuickDraw2;  {QuickDraw2 contains the stuff for regions.}

 const
  MaxScreens = 8;

 type
  TVList = array[1..MaxScreens] of GrafPtr;

 var
  Screens : TVList;
  ScrnCnt : INTEGER;
  done : BOOLEAN;

 procedure SetUp;

 begin
  HideAll;
  ScrnCnt := 0;
  done := FALSE;
 end;

 procedure ShutDown;

  var
   TempPort : GrafPtr;

 begin
  while ScrnCnt > 0 do
   begin
    ClosePort(Screens[ScrnCnt]);
    Dispose(Screens[ScrnCnt]);
    ScrnCnt := ScrnCnt - 1;
   end;

{ Create a new port and fill the screen with gray. }
  NEW(TempPort);
  OpenPort(TempPort);
  BackPat(Gray);
  EraseRect(TempPort^.PortRect);
  ClosePort(TempPort);
  Dispose(TempPort);
 end;

 function MakeTV (Left, Top : INTEGER) : GrafPtr;

  var
   TempPtr : GrafPtr;
   WorkRect : Rect;

 begin
{ Create a new port and set its characteristics. }
  NEW(TempPtr);
  OpenPort(TempPtr);
  PortSize(100, 80);
  MovePortTo(Left, Top);
  SetOrigin(0, 0);

{ Clear the port to white and draw our ‘television’ }
  BackPat(White);
  EraseRect(TempPtr^.PortRect);
  FrameRect(TempPtr^.PortRect);
  MoveTo(80, 0);
  LineTo(80, 80);
  SetRect(WorkRect, 85, 10, 95, 20);
  FrameOval(WorkRect);
  SetRect(WorkRect, 85, 30, 95, 40);
  FrameOval(WorkRect);

{ Restrict the clipping region to the TV ‘screen’ }
  WorkRect := TempPtr^.PortRect;
  WorkRect.right := WorkRect.Right - 20;
  InsetRect(WorkRect, 1, 1);
  ClipRect(WorkRect);
  MakeTV := TempPtr;
 end;

 procedure SetTV;

{ If the mouse is in one of our ports, select that port. If all}
{possible ports are created and the mouse is not in any port,}
{then we’re done. Otherwise, create a new port.}

  var
   MousePt, Pnt1 : Point;
   I, X, Y : INTEGER;
   TempPtr : GrafPtr;

 begin
  TempPtr := nil;
  GetMouse(X, Y); { Current port’s local coordinates }
  repeat { nothing }
  until not Button;

{ Convert to a point, the to global coordinates }
  MousePt.h := X;
  MousePt.v := Y;
  LocalToGlobal(MousePt);
  Pnt1 := MousePt;

{ Scan the existing ports. }
  if ScrnCnt > 0 then { we have some ports to scan }
   for I := 1 to ScrnCnt do
    begin
    SetPort(Screens[I]);
    MousePt := Pnt1;
    GlobalToLocal(MousePt);
    if PtInRect(MousePt, Screens[I]^.PortRect) then
    TempPtr := Screens[I];
    end; { for loop }

  if TempPtr <> nil then { the mouse is in a port; set it }
   SetPort(TempPtr)
  else if ScrnCnt = MaxScreens then { all ports used }
   done := TRUE
  else
   begin
    ScrnCnt := ScrnCnt + 1;
    Screens[ScrnCnt] := MakeTV(Pnt1.h, Pnt1.v);
   end;
 end;

 procedure MainLoop;

  var
   Figure : INTEGER;
   WorkRect : Rect;

 begin
  if Button then
   SetTV;

  if ScrnCnt > 0 then { do some drawing }
   begin
    if random mod 100 < 5 then { Clear the ‘screen’ }
    begin
    SetRect(WorkRect, 0, 0, 90, 90);
    EraseRect(WorkRect);
    end;

{ Create a random rectangle for drawing }
    WorkRect.top := random mod 80;
    WorkRect.left := random mod 80;
    WorkRect.right := WorkRect.left + (random mod 60);
    WorkRect.bottom := WorkRect.top + (random mod 60);
    Figure := random mod 6;
    case Figure of
    0 : 
    FrameRect(WorkRect);
    1 : 
    FrameRoundRect(WorkRect, 18, 18);
    2 : 
    FrameOval(WorkRect);
    3 : 
    PaintRect(WorkRect);
    4 : 
    PaintRoundRect(WorkRect, 18, 18);
    5 : 
    PaintOval(WorkRect);
    end;
   end;
 end;

begin   { Ports_Demo }
 SetUp;
 while not done do
  MainLoop;
 ShutDown;
end.

 
AAPL
$97.67
Apple Inc.
+1.41
MSFT
$43.63
Microsoft Corpora
+0.89
GOOG
$511.17
Google Inc.
-13.34

MacTech Search:
Community Search:

Software Updates via MacUpdate

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
OnyX 2.8.8 - Maintenance and optimizatio...
OnyX is a multifunctional utility for OS X. It allows you to verify the startup disk and the structure of its System files, to run miscellaneous tasks of system maintenance, to configure the hidden... Read more
Parallels Desktop 10.1 - Run Windows app...
Parallels Desktop is simply the world's bestselling, top-rated, and most trusted solution for running Windows applications on your Mac. With Parallels Desktop for Mac, you can seamlessly run both... Read more
Apple Keynote 6.5 - Apple's present...
Apple Keynote makes it simple to create and deliver beautiful presentations. Powerful tools and dazzling effects bring your ideas to life. You can work seamlessly between Mac and iOS devices. And... Read more
OmniPlan 2.3.7 - Robust project manageme...
With OmniPlan, you can create logical, manageable project plans with Gantt charts, schedules, summaries, milestones, and critical paths. Break down the tasks needed to make your project a success,... Read more
Flavours 1.1.16 - Create and apply theme...
Flavours is a Mac application that allow users to create, apply and share beautifully designed themes. Classy Give your Mac a gorgeous new look by applying delicious themes! Easy Unleash your... Read more
Duplicate Annihilator 5.1.0 - Find and d...
Duplicate Annihilator takes on the time-consuming task of comparing the images in your iPhoto library using effective algorithms to make sure that no duplicate escapes. Duplicate Annihilator detects... Read more

Latest Forum Discussions

See All

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 »
Loot Raiders Review
Loot Raiders Review By Campbell Bird on October 17th, 2014 Our Rating: :: PRESS BUTTON, GET LOOTUniversal App - Designed for iPhone and iPad This menu-based loot game is suitable to compel those with pretty extreme loot lust.   | Read more »
Angry Birds are Crashing Puzzle & Dr...
Angry Birds are Crashing Puzzle & Dragons Next Week Posted by Rob Rich on October 17th, 2014 [ permalink ] Next week, Puzzle & Dragons is getting a little angry. Because, you know, Angry Birds. It’s a… a pun. I thought… never mind. | Read more »
Incandescence Review
Incandescence Review By Andrew Fisher on October 17th, 2014 Our Rating: :: ALL TAPPED OUTUniversal App - Designed for iPhone and iPad Incandescence promises intense tapping action, but isn’t particularly fun.   | Read more »
Lion Pig (Games)
Lion Pig 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: "Leaving aside the biology of how a pig and a lion might meet, fall in love, and create this curious cross-breed, Lion Pig is a... | Read more »
Zero Lives (Games)
Zero Lives 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Zero Lives is a puzzle game. Simple and elegant at its core but deep and captivating the more you play. Each puzzle will challenge... | Read more »
#SUPERHYPER (Games)
#SUPERHYPER 001 Device: iOS Universal Category: Games Price: $.99, Version: 001 (iTunes) Description: "This is a game that fans of challenging minimalist arcade games, not to mention pixel art, should keep an eye on" - Touch Arcade "... | Read more »

Price Scanner via MacPrices.net

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
WaterField Designs Unveils Outback iPad Slip...
Fresh on the heels of Apple’s announcement Thursday, WaterField Designs unveils its new Outback Slip Case for the iPad Air 2 and iPad mini 3 — a custom-fitted case for the just-announced Apple iPads... Read more
Apple Introduces iPad Air 2 & iPad mini 3...
Apple on Thursday introduced iPad Air 2, slimmed down again to just 6.1 mm, and weighing less than a pound. iPad Air 2 also features an improved Retina display claimed to deliver enhanced contrast... Read more

Jobs Board

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
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.