TweetFollow Us on Twitter

OS Shell In Java

Volume Number: 15 (1999)
Issue Number: 1
Column Tag: JavaTech

Writing an OS Shell in Java

by Andrew Downs

Building a Facade

Introduction

This article describes the design and implementation of a Finder-like shell written in Java. Several custom classes (and their methods) areexamined: these classes provide a subset of the Macintosh Finder's functionality. The example code presents some low-level Java programming techniques, including tracking mouse events, displaying images, and menu and folder display and handling. It also discusses several high-level issues, such as serialization and JAR files.

Java provides platform-dependent GUI functionality in the Abstract Windowing Tookit (AWT) package, and platform-independent look and feel in the new Java Foundation Classes (Swing) API. In order to faithfully model the appearance and behavior of one specific platform on another, it is necessary to use a combination of existing and custom Java classes. Certain classes can inherit from the Java API classes, while overriding their appearance and functionality. This article presents techniques used to create a Java application (Facade) that provides some of the Macintosh Finder's capabilities and appearance. As a Java application, it can theoretically run on any platform supporting the Java 1.1 and JFC APIs. Figure 1 provides an overview of the Facade desktop and its functionality. Figure 2 shows a portion of the underlying object model. It contains a mixture of existing Java classes (such as Component and Window) and numerous custom classes. In the diagram, the user interface classes are separated from the support classes for clarity.


Figure 1. Facade on Windows 95.


Figure 2. Facade object model (partial). Only the inheritance structure is shown; relational attributes are not shown.

The Object Model

Facade's object model utilizes the core Java packages and classes where possible. However, in order to provide the appropriate appearance and speed, custom versions of several standard Java classes were added. For instance, the DesktopFrame class is used to display folder contents. Its functionality is similar to the java.awt.Frame class. However, additional behavior (i.e. window-shade) and appearance requirements dictated the creation of a "knockoff" class.

One advantage of using custom classes can be improved speed. This holds true for classes inheriting from java.awt.Component: such classes do not require the creation of platform-specific "peer" objects at runtime. Less baggage results in a faster response. For example, the Facade menu display and handling classes respond very quickly.

In the custom classes, most drawing uses primitive functions to draw text, fill rectangles, etc. Layout and display customization is assisted through the use of global constant values which typically signify offsets from a particular location (as opposed to hardcoded coordinates).

Several of the classes depicted in the object model will be discussed in this article.

Appearance and Functionality

Facade relies on several graphical user interface classes in order to provide a Finder-like interface. These classes fall into the following categories:

  • GUI
    • Desktop
    • Menus
    • Icons
    • Folders
  • Support
    • Startup
    • Timing
    • Constants

Facade provides a subset of the following operations:

  • Menu and menu item selection
  • Displaying volume/folder contents
  • Dragging icons
  • Opening and closing windows
  • Managing the trash
  • Saving the desktop state at shutdown (exit)
  • Restoring the desktop state at startup
  • Launching applications
  • Dialog display
  • Cut/Copy/Paste
  • Changing the cursor
  • Emulating the desktop database

Several of these operations (and the classes which implement them) will be discussed in the following sections.

The Desktop

The Desktop class is a direct descendant of the java.awt.Window class, which provides a container with no predefined border (unlike the java.awt.Frame class). This approach allows the drawing and positioning of elements within the Desktop area, without needing to hide the platform-specific scrollbars, title bar, etc.

However, this approach means that special care and feeding is required to make the menubar work properly. In the current implementation, menubar (and menu) drawing is done directly in the Desktop class, using values obtained from those respective classes. In other words, menus don't draw themselves, Desktop does it for them.

Menu Creation

The following code snippet (Listing 1), taken from the Desktop constructor, creates the Apple menu, and populates it with one item. The menu is an instance of the DesktopImage class. The Apple icon (imgApple) was loaded further up in this method. A similar sequence creates and populates the File menu.

Listing 1: Desktop constructor

Desktop constructor
Creating menus in the Desktop constructor.

// ----------------------------------
//		* Desktop constructor
// ----------------------------------

Desktop() {

  // <snip>

  // Create the menus and their menu items.
  DesktopImageMenu dim;
  Vector vectorMenuItems;
  DesktopMenuItem dmi;
  // Calculate the y-coordinate of the menus (constant).
  int newY = this.getY() + this.getMenuBarHeight() -
   ( this.getMenuBarHeight() / 3 );
		
  // Calculate the x-coordinate of the menus (variable).
  int newX = this.getX();
  // Create the Apple menu.
  dim = new DesktopImageMenu();
  dim.setImage( imgApple.getImage() );
  dim.setX( imgApple.getX() );
  dim.setY( imgApple.getY() );
  // Create menu item "About..."
  dmi = new DesktopMenuItem( Global.menuItemAboutMac );
  dmi.setEnabled( true );
  // Add the menu item to the Vector for this particular menu...
  dim.getVector().addElement( dmi );
  // ...then tell the menu to calculate the item position(s).
  // Note that the Desktop's FontMetrics object gets used here.
  dim.setItemLocations( this.getGraphics().getFontMetrics() );
  // Add the Apple menu to the menubar's Vector.
  // The menubar was instantiated further up in this method.
  dmb.getVector().addElement( dim );
  // For the next menu, calculate its x-coordinate.
  newX = imgApple.getX();
  newX += ( 2 * Global.defaultMenuHSep );
  newX += ( ( DesktopImageMenu )dmb.getVector().elementAt( 0 )
   ).getImage().getWidth( this ); // Line wrap.
  DesktopMenu dm;
  // Create the File menu...
  dm = new DesktopMenu();
  dm.setLabel( Global.menuFile );
  dm.setX( newX );
  dm.setY( newY );
  // ...and all its menu items.
  dmi = new DesktopMenuItem( Global.menuItemNew );
  dmi.setEnabled( true );
  dm.getVector().addElement( dmi );
  dmi = new DesktopMenuItem( Global.menuItemOpen );
  dmi.setEnabled( false );
  dm.getVector().addElement( dmi );
  dmi = new DesktopMenuItem( Global.menuItemClose );
  dmi.setEnabled( false );
  dm.getVector().addElement( dmi );
  // Tell the menu to calculate the item position(s).
  dm.setItemLocations( this.getGraphics().getFontMetrics() );
  // Add the File menu to the menubar's Vector.
  dmb.getVector().addElement( dm );
  newX += ( 2 * Global.defaultMenuHSep );
  newX += theFontMetrics.stringWidth( dm.getLabel() );
  // <etc.>
}

Here, the variable dim is an instance of the class DesktopImageMenu. This specialized menu class simply adds an instance variable that contains an Image (in this case, the Apple) to the DesktopMenu class. Its behavior is the same as other menus, except that instead of a String it displays its Image. The x and y coordinates of this menu are determined by the same values assigned to the image when it was loaded.

This object contains one menu item, the "About" item. That item is enabled, and added to the Vector for the menu. This Vector contains all the menu items for that menu. This approach provides an easy way to manage and iterate over the menu items.

Once the Vector has been setup, its contents are given their x-y coordinates for drawing and selection purposes through the setItemLocations() method. Although this calculation can be done when the menu is selected, the code runs faster if those numbers are calculated and assigned at startup time.

Finally, the menu is added to the Vector for the menubar. The menubar uses a Vector to iterate over its menus, in the same way the menus iterate over their menu items. This will become apparent when examining the mouse-event handling code for the Desktop class.

The same approach is shown for the File menu, except that File contains a String instead of an Image, as well as several menu items.

Menu and Menu Item Selection

This class defines some global values that are shared between the Display and ModeSelector classes. These values are collected in one place to simplify housekeeping and maintenance. We will refer to them from the other classes as Global.NORMAL, Global.sleep, etc. This is the Java syntax for referencing static (class) attributes. Note that final means the values cannot be changed after they are initially assigned, so these are constants.


Figure 3. Menu item selection.

The code in Listing 2 handles mouseDown events in the menubar. The first two lines reset the instance variables used to track the currently active menu and menu item. Since the user has pressed the mouse, the old values do not apply. Next, the Graphics and corresponding FontMetrics objects for the Desktop instance are retrieved. They will be used in drawing and determining what selection the user has made.

Next, test to see whether the event occured within the bounding rectangle of the menubar. This line uses the java.awt.Component.contains() method. If the x-y coordinates of the mouse event are inside the menubar, then determine which menu (if any) the user selected.

Determining the menu selection uses the menubar's Vector of menus. Iterate over the Vector elements, casting each retrieved element to a DesktopMenu object. (Vector.elementAt() returns Object instances by default, which won't work here.) The menu has its own bounding rectangle, which is compared to the event x-y coordinates. In addition, in order to duplicate the Finder, a fixed pixel amount is subtracted from the left-side of the bounding rectangle, and added to the right-side. This allows the user to select near, but not necessarily directly on, the menu name (or image). Notice also in the (big and nasty) if conditional that the DesktopMenu retrieved from the Vector is checked for an Image (this handles the Apple menu). If it has one, the image width is used instead of the String width.

Once the user's menu selection has been found, it is redrawn with a blue background. Then, the menu items belonging to that menu are drawn inside a bounding rectangle (black text on white background). The menu item coordinates, and the corresponding bounding rectangle coordinates, were calculated when the menu was created, saving some CPU cycles here.

Listing 2: mousePressed

mousePressed
The mousePressed method handles menu selections.

// ----------------------------------
//		* mousePressed
// ----------------------------------

public void mousePressed( MouseEvent e ) {

  // New click means no previous selection.
  this.activeMenu = -1;
  this.activeMenuItem = -1;
  Graphics g = this.getGraphics();
  FontMetrics theFontMetrics = g.getFontMetrics();
  if ( dmb.contains( e.getX(), e.getY() ) ) {
   // Handle menu selection.
   for ( int i = 0; i < dmb.getVector().size(); i++ ) {
     // Get menu object.
  DesktopMenu d = ( DesktopMenu )dmb.getVector().elementAt( i );
     // Determine if we're inside this menu.
     // This could be done with one or more Rectangles.
     // Note the (buried) conditional operator: it accounts
     // for both text and image (e.g. the Apple) menus.
     if ( ( e.getX() >= d.getX() - Global.defaultMenuHSep ) 
     && ( e.getX() <= ( d.getX() + ( d.getLabel() == null ? 
      ( ( DesktopImageMenu )d ).getImage().getWidth( this ) :
      theFontMetrics.stringWidth( d.getLabel() ) ) +
      Global.defaultMenuHSep ) ) 
     && ( e.getY() >= this.getY() ) && ( e.getY() <=
      this.getMenuBarHeight() ) ) {
      // Draw menubar highlighting...
      g.setColor( Color.blue );
      // Save the current Rectangle surrounding the menu.
      // This will speed up painting on the following line,
      // and when the user leaves this menu.
      activeMenuRect = new Rectangle( d.getX() -
        Global.defaultMenuHSep, this.getY(), ( d.getLabel() ==
        null ? ( ( DesktopImageMenu )d ).getImage().getWidth(
        this ) : theFontMetrics.stringWidth( d.getLabel() ) ) + 
        ( 2 * Global.defaultMenuHSep ), getMenuBarHeight() );
      g.fillRect( activeMenuRect.x, activeMenuRect.y,
        activeMenuRect.width, activeMenuRect.height );
      // Draw menu String or Image.
      g.setColor( Color.black );
      if ( d.getLabel() != null )
        g.drawString( d.getLabel(), d.getX(), d.getY() );
      else
        g.drawImage( ( ( DesktopImageMenu )d ).getImage(),
         d.getX(), d.getY(), this );
				
      // Get menu item vector.
      Vector v = d.getVector();
      // If the Trash is full, enable the menu item.
      // This code can easily be moved; it is included
      // here for illustration.
      DesktopMenuItem dmi = 
        ( DesktopMenuItem )v.elementAt( 0 );
    if ( dmi.getLabel().equals( Global.menuItemEmptyTrash ) ) {
        DesktopImage di = ( ( DesktopImage
         )this.vectorImages.elementAt( 1 ) );
        String path = di.getPath();
        File f = new File( path, Global.trashDisplayString );
        if ( f.exists() ) {
         String array[] = f.list();
							
         if ( array == null || array.length == 0 )
           dmi.setEnabled( false );
         else
           dmi.setEnabled( true );
        }
      }

      // Draw menu background.
      g.setColor( dmb.getBackground() );
      g.fillRect( d.getItemBounds().getBounds().x,
        d.getItemBounds().getBounds().y,
        d.getItemBounds().getBounds().width,
        d.getItemBounds().getBounds().height );
      // Draw menu items.
      for ( int j = 0; j < v.size(); j++ ) {
        g.setColor( Color.black );
        if ( !( ( DesktopMenuItem )v.elementAt( j )
         ).getEnabled() )
         g.setColor( Color.lightGray );
        g.drawString( ( ( DesktopMenuItem )v.elementAt( j )
         ).getLabel(), ( ( DesktopMenuItem )v.elementAt( j )
         ).getDrawPoint().x,
         ( ( DesktopMenuItem )v.elementAt( j )
         ).getDrawPoint().y );
      }
      g.setColor( Color.black );
      // Outline the menu item list bounding rectangle.
      g.drawRect( d.getItemBounds().getBounds().x,
        d.getItemBounds().getBounds().y,
        d.getItemBounds().getBounds().width,
        d.getItemBounds().getBounds().height );
      // Add horizontal drop shadow.
      g.fillRect( d.getItemBounds().getBounds().x + 2,
        d.getItemBounds().getBounds().y +
        d.getItemBounds().getBounds().height,
        d.getItemBounds().getBounds().width, 2 );
      // Add vertical drop shadow.
      g.fillRect( d.getItemBounds().getBounds().x +
        d.getItemBounds().getBounds().width,
        d.getItemBounds().getBounds().y + 2, 2,
        d.getItemBounds().getBounds().height );
      // Set current menu.
      this.activeMenu = i;
      // Once found, we're done.
      break;
     }
   }
  }
}

The mouseDragged() method (not shown) is responsible for the highlighting and unhilighting of menus and menu items: that is where menu items get redrawn with white text on a blue background, as depicted in Figure 3.

Displaying Folder Contents

Folders in Facade use a combination of core Java classes and Swing classes. The container itself descends from java.awt.Window, and the paint() method performs the low-level drawing calls (drawing the title bar, close box, etc.). The content is displayed inside a JScrollPane.

Once the Macintosh look-and-feel is activated, the scrollbars take the appearance shown in Figure 4. The icons within the scrollpane are added to a grid layout. This approach works well, except that the tendency of the scrollpane is to take up the entire display area (ignoring the title bar, etc.). So, on resize of the container, the scrollpane is also resized. A java.awt.Insets object is used to make this as painless as possible: the Insets values are used as the buffer area around the scrollpane.

Like most of the Facade classes, DesktopFolder implements the MouseListener and MouseMotionListener interfaces so it can receive mouse events. Within the methods required for those interfaces, the x-y coordinates are checked to determine if a close, zoom, shade, grow, or drag operation is taking place, and the container gets reshaped appropriately.


Figure 4. Displaying folder contents.

Listing 3: addFileTree

addFileTree
Building a folder's display area.

// ----------------------------------
//		* addFileTree
// ----------------------------------

public void addFileTree( String s ) {
  // Instantiate the instance variables for this object's content.
  // The Mac L&F requires both scrollbars.
  pane = new JScrollPane();
  pane.setHorizontalScrollBarPolicy( 
   JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
  pane.setVerticalScrollBarPolicy( 
   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
  // Make sure the argument passed in is a valid directory.
  String defaultVolume = s;
  if ( defaultVolume == null )
   return;
		
  File theDir = new File( defaultVolume );
  if ( !theDir.isDirectory() )
   return;
  // Retrieve the contents of this folder/directory.
  contents = theDir.list();
  int tempLength = 0;
  if ( contents != null ) {
   tempLength = contents.length;
  // Use a Swing panel inside the Swing scrollpane.
  // Default to a grid layout simply because it looks the best.
  JPanel p = new JPanel();
  p.setLayout( new GridLayout( 5, 3, 5, 5 ) );
  // If the contents contain full path specifications, there will
  // be some extraneous characters that we don't want to display.
  char pathSeparatorChar = theDir.pathSeparatorChar;
  char separatorChar = theDir.separatorChar;
  Vector v = new Vector();
  v.addElement( Global.spaceSep );
  int loc = 0;
  int k = 0;
		
  for ( int j = 0; j < tempLength; j++ ) {
   // For each item, separator chars should become spaces for 
   // display purposes.
   File tempFile = new File( theDir, contents[ j ] );
   contents[ j ] = 
 new String( contents[ j ].replace( pathSeparatorChar, ' ' ) );
   contents[ j ] = 
     new String( contents[ j ].replace( separatorChar, ' ' ) );
   for ( int l = 0; l < v.size(); l++ ) {
     // Parse root volume name.
     // Remove leading '%20' character.
     loc = contents[ j ].indexOf( ( String )v.elementAt( l ) );
     if ( loc == 0 )
      contents[ j ] = new String( contents[ j ].substring( ( 
        ( String )v.elementAt( l ) ).length() ) );
     // Volume name includes first '%20'.
     // Rework this for MacOS.
     loc = contents[ j ].indexOf( ( String )v.elementAt( l ) );
     // Build the final display String from substrings.
while ( ( loc > 0 ) && ( loc < contents[ j ].length() + 1 ) ) {
   String s1 = new String( contents[ j ].substring( 0, loc ) );
      String s2 = new String( contents[ j ].substring( loc + ( 
        ( String )v.elementAt( l ) ).length() ) );
      contents[ j ] = new String( s1 + " " + s2 );
    loc = contents[ j ].indexOf( ( String )v.elementAt( l ) );
     }
   }

   // Now build the appropriate icon.
   Image theImage;
   int tempWidth = 0;
   DesktopFrameItem d;
   ImageIcon ii = new ImageIcon();
   // Files obviously look different than folders.
   // Set the appropriate Image.
   // This version does not handle mouse clicks on documents.
   if ( tempFile.isFile() ) {
     d = new DesktopDoc();
     ii = new ImageIcon( ( ( DesktopDoc )d ).getImage() );
   }
   else {
     d = new DesktopFolder();
     ii = new ImageIcon( ( ( DesktopFolder )d ).getImage() );
     d.addMouseListener( ( DesktopFolder )d );
   }

   // Set the display Strings.
   d.setLabel( contents[ j ] );
   d.setText( contents[ j ] );
   // Set the path for the item. It is built from the parent folder
   // path and filename.
   d.setPath( this.getPath() + 
     System.getProperty( "file.separator" ) + contents[ j ] );
   // And set the icon.
   d.setIcon( ii );
   // Swing methods for positioning the icon and label.
   d.setHorizontalAlignment( JLabel.CENTER );
   d.setHorizontalTextPosition( JLabel.CENTER );
   d.setVerticalTextPosition( JLabel.BOTTOM );
   ii.setImageObserver( d );
   // Add the completed item to the panel.
   p.add( d );
  }

  // Set the panel characteristics, then add it to the scrollpane.
  p.setVisible( true );
  pane.getViewport().add( p, "Center" );
  pane.setVisible( true );
  // A container within a container within a container...it works.
  panel = new JPanel();
  panel.setLayout( new BorderLayout() );
  panel.add( pane, "Center" );
  this.add( panel );
  // Use the Insets object for this window to set the viewing
  // size of the panels and scrollpane.
  panel.reshape( this.getInsets().left, this.getInsets().top, 
   this.getBounds().width - this.getInsets().right - 
   this.getInsets().left, this.getBounds().height - 
   this.getInsets().top - this.getInsets().bottom 
  // Ready for display.
  panel.setVisible( true );
  this.pack();
  this.validate();
}

The Trash

The trash is simply a directory located at the root of the volume (for example, c:\Trash). Items can be dragged onto the trash can icon, the mouse button released, and the item (and its contents, if it is a folder) are moved to the trash directory. If the item has an open window, that window is destroyed. Emptying is accomplished through the "Empty Trash..." menu item in the Special menu. Figure 5 shows a folder being dragged to the trash. The cursor did not get captured in the image, but it is positioned over the trash icon, ready to release the folder.


Figure 5. Dragging a folder to the Trash.

The code in Listing 4 handles the "Empty Trash..." menu item. If a match is found between the selected item and the constant assigned as the Trash label, the path to the Trash is retrieved. Once the code determines the "Trash" is indeed an existing directory, the emptyDir() method is called. Once emptyDir() returns, the icon is changed from full to empty. Note that the trash icon is always present in the vectorImages object. This Vector contains the known images (icons) for items on the desktop. The trash is always at position 0, the first position. The root volume is at position 1. This allows quick, though hardcoded, access to the images when repainting occurs, or an image needs swapping.

Listing 4: handleMenuItem

handleMenuItem
Handling the "Empty Trash..." menu item.

// ----------------------------------
//		* handleMenuItem
// ----------------------------------

public boolean handleMenuItem() {
  boolean returnValue = false;
  // Handle active menu item.
 if ( ( this.activeMenu != -1 ) && ( this.activeMenuItem != -1 ) ) {
   // Get menu object.
   DesktopMenu dm = 
   ( DesktopMenu )dmb.getVector().elementAt( this.activeMenu );
   // Get menu item.
   String s = ( ( DesktopMenuItem )dm.getVector().elementAt(
     this.activeMenuItem ) ).getLabel();
   // <snip>
   if ( s.equals( Global.menuItemEmptyTrash ) ) {
     // The path to the trash is assumed to be of the form:
     //  <root vol>/Trash
     DesktopImage di = 
      ( ( DesktopImage )this.vectorImages.elementAt( 1 ) );
     String path = di.getPath();
     File f = new File( path, Global.trashDisplayString );
     // Once we have the object that references the Trash dir...
     if ( f.exists() && f.isDirectory() ) {
      // Call the method which empties it.
      boolean b = this.emptyDir( f );
      // If successful, change the icon back to empty.
      if ( b ) {
        // Save the current bounds. We really want the x-y.
        Rectangle r =
         ( ( DesktopImage )this.vectorImages.elementAt( 0 )
          ).getBounds();
        // Change the icon. imgTrash and imgTrashFull are two
        // instance variables, each referencing the appropriate
        // icon.
        this.vectorImages.setElementAt( this.imgTrash, 0 );
        ( ( DesktopImage )this.vectorImages.elementAt( 0 )
         ).setBounds( r );
        // Show the change.
        this.repaint();
      }
     }
   }
  }
}

Emptying the Trash

emptyDir() is displayed in Listing 5. This method will empty the specified directory recursively. As it finds each item in the directory, appropriate action is taken. If the item is a file it is immediately deleted. If it is a directory, emptyDir() is called again, with the subdirectory name as its argument. Eventually, all of the files in the subdirectory are deleted, and then the subdirectory itself is removed.

Listing 5: emptyDir

emptyDir
Emptying a directory.

// ----------------------------------
//		* emptyDir
// ----------------------------------

public boolean emptyDir( File dir ) {
  // Recursive method to remove a directory's contents,
  // then delete the directory.
  boolean b = false;
  // Get the directory contents.
  String array[] = dir.list();
  // If the path is screwed up, this will catch it.
  if ( array != null ) {
   // Iterate over the directory contents...
   for ( int count = 0; count < array.length; count ++ ) {
     String temp = array[ count ];
     // Create a new File object using path + filename.
     File f1 = new File( dir, temp );
     // Delete files immediately.
     // Call this method again for subdirectories.
     if ( f1.isFile() ) {
      b = f1.delete();
     }
     else if ( f1.isDirectory() ) {
      b = this.emptyDir( f1 );
      b = f1.delete();
     }
   }
  }
  return b;
}

Saving and Restoring State

Facade uses a variant on the standard Java serialization mechanism for saving the Desktop state. The code in Listing 6 illustrates the saving and restoring of open folder windows. Both of these methods are in the Desktop class. Note that rather than flatten entire DesktopFrame objects, this code saves only specific attributes from each object. The primary reason for this approach is that it avoids any exceptions thrown when attempting to serialize the Swing components and Images (which are not serializable by default) within each DesktopFrame. Another reason is the relative ease with which this approach may be implemented. Plus, it reduces the amount of data written to disk. One disadvantage is that the current scroll position of any open window is lost.

Listing 6: saveState and restoreState

saveState
Saving and restoring open DesktopFrames.

// ----------------------------------
//		* saveState
// ----------------------------------

private void saveState() {
  // The Desktop data will be stored in a file at the root level.
  DesktopImage di =
   ( ( DesktopImage )this.vectorImages.elementAt( 1 ) );
  String s = new String( di.getPath() + "Desktop.ser" );
  try {
   FileOutputStream fos = new FileOutputStream( s );
   ObjectOutputStream outStream = new ObjectOutputStream( fos );
   // Use a temporary Vector to hold the open DesktopFrames.
   // This should not be necessary when shutting down, but it
   // is a good habit to follow.
   Vector v = new Vector();
   v = ( Vector )this.vectorWindows.clone();
   // Use another temporary Vector to hold the attributes to save.
   Vector temp = new Vector();
			
   for ( int i = 0; i < v.size(); i++ ) {
     // For each DesktopFrame, we'll save its path, display 
     // string, and its bounding Rectangle. If window-shading is 
     // in effect on an object, restore the full height before 
     // saving.
     DesktopFrame df = ( DesktopFrame )v.elementAt( i );
     temp.addElement( df.getPath() );
     temp.addElement( df.getLabel() );
     if ( df.getShade() ) {
      df.restoreHeight();
     }
     temp.addElement( df.getBounds() );
   }
   // Write the Vector contents to the .ser file.
   outStream.writeObject( temp );
   outStream.flush();
   outStream.close();
  }
  catch ( IOException e ) {
   System.out.println( "Couldn't save state." );
   System.out.println( "s = " + s );
   e.printStackTrace();
  }
}

// ----------------------------------
//		* restoreState
// ----------------------------------

private void restoreState() {

  // The Desktop data is stored in a file at the root level.
  // This step occurs near the end of the Desktop constructor, 
  // and so can use the root volume to build the path.
  DesktopImage di = 
   ( ( DesktopImage )this.vectorImages.elementAt( 1 ) );
  String s = new String( "\\Desktop.ser" );
  try {
   // Open the file, and read the contents. In this version
   // we know it's just one Vector.
   FileInputStream fis = new FileInputStream( s );
   ObjectInputStream inStream = new ObjectInputStream( fis );
   Vector v = new Vector();
   v = ( Vector )inStream.readObject();
   inStream.close();
  Rectangle r = new Rectangle();
   for ( int i = 0; i < v.size(); i++ ) {
     // Iterate over the Vector contents. We know the save format:
     // each field corresponds to a specific attribute of a 
     // DesktopFrame.
     // Create a new DesktopFrame using the retrieved path.
     s = ( String )v.elementAt( i );
     DesktopFrame df = new DesktopFrame( s );
				
     // Set its label using the next Vector element.
     i++;
     s = ( String )v.elementAt( i );
     df.setLabel( s );
     // Set its bounding Rectangle using the next Vector element.
     i++;
     r = ( Rectangle )v.elementAt( i );
     df.setBounds( r );
     // Prepare and display the DesktopFrame.
     df.pack();
     df.validate();
     df.show();
     df.toFront();
     df.repaint();
     // Add the object to the Desktop's Vector of open windows.
     Desktop.addWindow( df );
   }
  }
  catch ( ClassNotFoundException e ) {
   System.out.println( "ClassNotFoundException in retrieveState()."
     );
  }
  catch ( IOException e ) {
   System.out.println( "Couldn't retrieve state." );
   System.out.println( "s = " + s );
   e.printStackTrace();
  }
}

Packaging (Facade in a JAR)

Facade can be run from a Java Archive (JAR) file, or as a set of separate classes plus images. In addition, the Macintosh look-and-feel classes must be present (usually in a separate JAR). The system environment variables need to be setup properly in order for the Java runtime to find the classes.

The JAR file for Facade was created like this:

  jar cf Facade.jar /Facade/*.class /Facade/*.gif

Once the environment variables are set, Facade can be invoked as follows:

  java Facade

Other Classes

In addition to the java.awt classes already discussed, there are other packages and classes used often in Facade.

This program relies heavily on the java.util.Vector class for maintaining a semblance of order among the various objects. Several Vector instances are used for tracking icons and open windows. Figure 6 illustrates the core concept of a Vector: it is a growable array.


Figure 6. Creating and populating a Vector. The arrow represents a pointer to the current element at the end of the Vector.

The java.io.File class provides most of the file system operations for display and management. Refer to the references provided in the bibliography for API details. One platform-specific detail that was not discussed is the translation of a root path to a form that is valid for a File directory object. For example, calling the File.list() method on the path "c:\" will not return any file or folder names, but calling the same method for the path "/" will return the root directory contents.

Facade also uses the Java Foundation Classes (Swing) to provide a consistent look and feel across platforms, primarily for window scrolling operations. Swing runs a bit slow right now, but as peformance improves Swing classes can be substituted for some of the Facade custom classes. For example, the code that handles folder content display can be modified to show a tree structure. This capability should be easy to implement using the Swing classes, with little additional low-level drawing code.

Conclusion

Writing Java classes to model operating system functionality requires some choices, particularly in the selection of pre-defined GUI classes. Although many classes are available, you will need to create others, since performance of the pre-defined classes may be slow, or the behavior may not be exactly what you need. Both the appearance and behavior for custom GUI elements must be written.

This article touched on several key areas: desktop layout, menu and mouse handling, icon display and movement, the trash, and saving and restoring the desktop state. All of these functional areas can be modeled easily using the Java 1.1 classes, supplemented by JFC and custom-built classes.

References

  • Developing Java Beans, Robert Englander, O'Reilly & Associates, Inc., 1997.
  • Java in a Nutshell, David Flanagan, O'Reilly & Associates, Inc., 1997.
  • Exploring Java, Patrick Niemeyer and Joshua Peck, O'Reilly & Associates, Inc., 1997.
  • Programming with JFC, Scott Weiner and Stephen Asbury, John Wiley & Sons, Inc., New York, NY, 1998.

URLs


Andrew Downs is a Technical Lead for Template Software in New Orleans, LA, designing and building enterprise apps. When he's not dodging hurricanes, he watches his twin sons stress test Macintosh hardware. Andrew wrote the Macintosh freeware program Recent Additions, and the Java application UDPing. You can reach him at andrew@nola.template.com.

 
AAPL
$98.38
Apple Inc.
-0.64
MSFT
$43.89
Microsoft Corpora
-0.09
GOOG
$585.61
Google Inc.
-4.99

MacTech Search:
Community Search:

Software Updates via MacUpdate

Drive Genius 3.2.4 - Powerful system uti...
Drive Genius is an OS X utility designed to provide unsurpassed storage management. Featuring an easy-to-use interface, Drive Genius is packed with powerful tools such as a drive optimizer, a... Read more
Vitamin-R 2.15 - Personal productivity t...
Vitamin-R creates the optimal conditions for your brain to work at its best by structuring your work into short bursts of distraction-free, highly focused activity alternating with opportunities for... Read more
Toast Titanium 12.0 - The ultimate media...
Toast Titanium goes way beyond the very basic burning in the Mac OS and iLife software, and sets the standard for burning CDs, DVDs, and now Blu-ray discs on the Mac. Create superior sounding audio... Read more
OS X Yosemite Wallpaper 1.0 - Desktop im...
OS X Yosemite Wallpaper is the gorgeous new background image for Apple's upcoming OS X 10.10 Yosemite. This wallpaper is available for all screen resolutions with a source file that measures 5,418... Read more
Acorn 4.4 - Bitmap image editor. (Demo)
Acorn is a new image editor built with one goal in mind - simplicity. Fast, easy, and fluid, Acorn provides the options you'll need without any overhead. Acorn feels right, and won't drain your bank... Read more
Bartender 1.2.20 - Organize your menu ba...
Bartender lets you organize your menu bar apps. Features: Lets you tidy your menu bar apps how you want. See your menu bar apps when you want. Hide the apps you need to run, but do not need to... Read more
TotalFinder 1.6.2 - Adds tabs, hotkeys,...
TotalFinder is a universally acclaimed navigational companion for your Mac. Enhance your Mac's Finder with features so smart and convenient, you won't believe you ever lived without them. Tab-based... Read more
Vienna 3.0.0 RC 2 :be5265e: - RSS and At...
Vienna is a freeware and Open-Source RSS/Atom newsreader with article storage and management via a SQLite database, written in Objective-C and Cocoa, for the OS X operating system. It provides... Read more
VLC Media Player 2.1.5 - Popular multime...
VLC Media Player is a highly portable multimedia player for various audio and video formats (MPEG-1, MPEG-2, MPEG-4, DivX, MP3, OGG, ...) as well as DVDs, VCDs, and various streaming protocols. It... Read more
Default Folder X 4.6.7 - Enhances Open a...
Default Folder X attaches a toolbar to the right side of the Open and Save dialogs in any OS X-native application. The toolbar gives you fast access to various folders and commands. You just click... Read more

Latest Forum Discussions

See All

Note Review
Note Review By Jennifer Allen on July 29th, 2014 Our Rating: :: TOO SIMPLEiPhone App - Designed for the iPhone, compatible with the iPad Note is a note taking app that’s a little too short on features to be worth its asking price... | Read more »
Chainsaw Warrior Goes on Sale & Ther...
Chainsaw Warrior Goes on Sale & There’s a Chance to Win a Copy of the Original Board Game Posted by Jennifer Allen on July 29th, 2014 [ permalink | Read more »
It Came From Canada: Tiny Tower Vegas
If you go to a casino, you might make a lot of money. If you run a casino, you’re guaranteed to make a lot of money. The choice seems pretty obvious. So while waiting for your shady real estate deals to move forward, get prepared with Tiny Tower... | Read more »
Z Hunter Review
Z Hunter Review By Lee Hamlet on July 29th, 2014 Our Rating: :: RIGHT ON TARGETUniversal App - Designed for iPhone and iPad While it might not necessarily break new ground, Z Hunter has enough tricks up its sleeve to ensure that... | Read more »
Huge Update Comes To Duet, Adding 48 New...
Huge Update Comes To Duet, Adding 48 New Stages Posted by Jennifer Allen on July 29th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Sharknado: The Video Game Available Now....
Sharknado: The Video Game Available Now. Seriously. Posted by Rob Rich on July 29th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Frog Orbs 2 Review
Frog Orbs 2 Review By Nadia Oxford on July 29th, 2014 Our Rating: :: THIS MAGIC IS A TAD MONOTONOUS Universal App - Designed for iPhone and iPad Frog Orbs 2 is repetitive, but younger players should enjoy it nonetheless.   | Read more »
Puzzix Review
Puzzix Review By Jennifer Allen on July 29th, 2014 Our Rating: :: NICE IDEAUniversal App - Designed for iPhone and iPad A little like Tetris, Puzzix is all about piecing together blocks and watching them vanish. It could do with... | Read more »
Cannonball eMail is Now Live – Works Wit...
Cannonball eMail is Now Live – Works With Gmail, Yahoo, Outlook, Hotmail, and AOL Posted by Jessica Fisher on July 29th, 2014 [ permalink ] | Read more »
To The End Review
To The End Review By Lee Hamlet on July 29th, 2014 Our Rating: :: A VICIOUS CYCLEUniversal App - Designed for iPhone and iPad To The End will test players’ patience, timing, and dedication as they try to navigate all 13 levels in... | Read more »

Price Scanner via MacPrices.net

WaterField Unveils 15″ Outback Solo & 13″...
Hard on the heels of Apple’s refreshed MacBook Pro Retina laptops announcement, WaterField Designs has unveiled a 15-inch version of the waxed-canvas and leather Outback Solo and a 13-inch version of... Read more
New Roxio Toast 12 Delivers Digital Media Pow...
Roxio Toast 12 is a hub for sharing digital media to virtually any platform or device. has introduced two new additions to its Roxio Toast product family – Roxio Toast 12 Titanium and Roxio Toast 12... Read more
The lowest prices on leftover Retina MacBook...
Best Buy has dropped prices on leftover 13″ and 15″ Retina MacBook Pros by up to $300 off original MSRP on their online store for a limited time. Choose free local store pickup (if available) or free... Read more
Apple Updates MacBook Pro with Retina Display...
Apple today updated its MacBook Pro with Retina display with faster processors and double the amount of memory in both entry-level configurations. MacBook Pro with Retina display features a Retina... Read more
Up to $250 price drop on leftover 15-inch Mac...
B&H Photo has dropped prices on 2013 15″ Retina MacBook Pros by as much as $250 off original MSRP. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.3GHz Retina MacBook Pro: $2349... Read more
Updated MacBook Pro Price Trackers
We’ve updated our MacBook Pro Price Trackers with the latest information on prices, bundles, and availability on the new 2014 models from Apple’s authorized internet/catalog resellers as well as... Read more
Apple updates MacBook Pros with slightly fast...
Apple updated 13″ and 15″ Retina MacBook Pros today with slightly faster Haswell processors. 13″ models now ship with 8GB of RAM standard, while 15″ MacBook Pros ship with 16GB across the board. Most... Read more
Apple drops price on 13″ 2.5GHz MacBook Pro b...
The Apple Store has dropped their price for the 13″ 2.5GHz MacBook Pro by $100 to $1099 including free shipping. Read more
Apple drops prices on refurbished 2013 MacBoo...
The Apple Store has dropped prices on Apple Certified Refurbished 13″ and 15″ 2013 MacBook Pros, with model now available starting at $929. Apple’s one-year warranty is standard, and shipping is free... Read more
iOS 8 and OS X 10.10 To Support DuckDuckGo As...
Writing for Quartz, Dan Frommer reports that Apple’s forthcoming iOS 8 and OS X 10.10 operating systems version updates will allow users to select DuckDuckGo as their default search engine. He notes... Read more

Jobs Board

Sr Software Lead Engineer, *Apple* Online S...
Sr Software Lead Engineer, Apple Online Store Publishing Systems Keywords: Company: Apple Job Code: E3PCAK8MgYYkw Location (City or ZIP): Santa Clara Status: Full Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Sr. Product Leader, *Apple* Store Apps - Ap...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.