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
$102.99
Apple Inc.
+0.52
MSFT
$44.38
Microsoft Corpora
-0.50
GOOG
$532.71
Google Inc.
+6.17

MacTech Search:
Community Search:

Software Updates via MacUpdate

jAlbum Pro 12.2.4 - Organize your digita...
jAlbum Pro has all the features you love in jAlbum, but comes with a commercial license. With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code!... Read more
jAlbum 12.2.4 - Create custom photo gall...
With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code! Beginner-friendly, with pro results Simply drag and drop photos into groups, choose a design... Read more
ExpanDrive 4.1.7 - Access remote files o...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more
Evernote 5.6.2 - Create searchable notes...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more
OmniOutliner 4.1.3 - Organize your ideas...
OmniOutliner is a flexible program for creating, collecting, and organizing information. Give your creativity a kick start by using an application that's actually designed to help you think. It's... Read more
BBEdit 11.0 - Powerful text and HTML edi...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
Apple Security Update 2014-005 - For OS...
Apple Security Update is recommended for all users and improves the security of Mac OS X. For information on the security content of this update, please visit this website: http://support.apple.com/... Read more
EyeTV 3.6.6 - Watch and record TV on you...
EyeTV brings a rich TV experience to your Mac. Watch live TV on your Mac. Pause, rewind, and record whenever you want. EyeTV gives you powerful control over what you watch and how you watch it. Put... Read more
RapidWeaver 6.0 - Create template-based...
RapidWeaver is a next-generation Web design application to help you easily create professional-looking Web sites in minutes. No knowledge of complex code is required, RapidWeaver will take care of... Read more
NTFS 12.0.39 - Provides full read and wr...
Paragon NTFS breaks down the barriers between Windows and OS X. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS, providing full read and write access to... Read more

Latest Forum Discussions

See All

Felllice (Games)
Felllice 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: EXCLUSIVE PRICE DROP! 50% OFF FOR A LIMITED TIME! EAT EAT EAT AND GROW ! | Read more »
The Arrow Game: by Grazie Media (Games)
The Arrow Game: by Grazie Media 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: Guide a flying arrow through skyscrapers and city streets to hit a distant target. Experience an endless... | Read more »
Worldly (Games)
Worldly 1.2 Device: iOS Universal Category: Games Price: $2.99, Version: 1.2 (iTunes) Description: | Read more »
Money Pro - EASY! Bills, Budgets and Acc...
Money Pro - EASY! Bills, Budgets and Accounts w/ Sync 1.0 Device: iOS Universal Category: Finance Price: $4.99, Version: 1.0 (iTunes) Description: Manage money like a pro. Money Pro is the next generation of Money app (over 2 million... | Read more »
Pro Strategy Football 2014 (Games)
Pro Strategy Football 2014 2014.141001 Device: iOS Universal Category: Games Price: $4.99, Version: 2014.141001 (iTunes) Description: Take the proven strategy of the PSF franchise and add in Casual Play, improved graphics and... | Read more »
Super Glyph Quest (Games)
Super Glyph Quest 1.01 Device: iOS Universal Category: Games Price: $2.99, Version: 1.01 (iTunes) Description: Adventure is back Questers! Combine elemental glyphs together to cast powerful spells and vanquish adorable monsters in... | Read more »
Fighting Fantasy: Caverns of the Snow Wi...
Fighting Fantasy: Caverns of the Snow Witch 1.0 Device: iOS Universal Category: Games Price: $5.99, Version: 1.0 (iTunes) Description: Travel to Northern Allansia’s perilous Icefinger Mountains to defeat the wicked Snow Witch in this... | Read more »
Star Warfare 2: Payback Review
Star Warfare 2: Payback Review By Blake Grundman on October 22nd, 2014 Our Rating: :: ONE-TRICK PONYUniversal App - Designed for iPhone and iPad Unfortunately, it doesn’t take long for Star Warfare 2’s free-firing fun to turn into... | Read more »
TinType by Hipstamatic (Photography)
TinType by Hipstamatic 1.0 Device: iOS iPhone Category: Photography Price: $.99, Version: 1.0 (iTunes) Description: Create hauntingly beautiful, soul capturing portraits with TinType by Hipstamatic. Inspired by daguerreotypes,... | Read more »
The Latest Update for Heroes of Dragon A...
The Latest Update for Heroes of Dragon Age Introduces Daily PvE Challenges Posted by Ellis Spice on October 22nd, 2014 [ permalink ] | Read more »

Price Scanner via MacPrices.net

Save with Best Buy’s College Student Deals
Take an additional $50 off all MacBooks and iMacs at Best Buy Online with their College Students Deals Savings, valid through November 1st. Anyone with a valid .EDU email address can take advantage... Read more
iPad Air 2 & iPad mini 3 Best Tablets Yet...
The new iPads turned out to be pretty much everything I’d been hoping for and more than I’d expected.”More” particularly in terms of a drinking-from-a-firehose choice of models and configurations,... Read more
Drafts 4 Reinvents iOS Productivity App
N Richland Hills, Texas based Agile Tortoise has announced the release of Drafts 4 for iPhone and iPad. Drafts is a quick capture note taking app with flexible output actions. Drafts 4 scales from... Read more
AT&T accepting preorders for new iPads fo...
AT&T Wireless is accepting preorders for the new iPad Air 2 and iPad mini 3, cellular models, for $100 off MSRP with a 2-year service agreement: - 16GB iPad Air 2 WiFi + Cellular: $529.99 - 64GB... Read more
Apple offering refurbished Mac Pros for up to...
The Apple Store is offering Apple Certified Refurbished 2013 Mac Pros for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The... Read more
Select MacBook Airs $100 off MSRP, free shipp...
B&H Photo has 2014 a couple of MacBook Airs on sale for $100 off MSRP. Shipping is free, and B&H charges NY sales tax only. They also include free copies of Parallels Desktop and LoJack for... Read more
13-inch 2.5GHz MacBook Pro on sale for $100 o...
B&H Photo has the 13″ 2.5GHz MacBook Pro on sale for $999.99 including free shipping plus NY sales tax only. Their price is $100 off MSRP. Read more
Strong iPhone, Mac And App Store Sales Drive...
Apple on Monday announced financial results for its fiscal 2014 fourth quarter ended September 27, 2014. The Company posted quarterly revenue of $42.1 billion and quarterly net profit of $8.5 billion... Read more
Apple Posts How-To For OS X Recovery
OS X 10.7 Lion and later include OS X Recovery. This feature includes all of the tools you need to reinstall OS X, repair your disk, and even restore from a Time Machine backup. OS X Recovery... Read more
Mac OS X Versions (Builds) Supported By Vario...
Apple Support has posted a handy resource explaining which Mac OS X versions (builds) originally shipped with or are available for your computer via retail discs, downloads, or Software Update. Apple... Read more

Jobs Board

Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, 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
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Position Opening at *Apple* - Apple (United...
…customers purchase our products, you're the one who helps them get more out of their new Apple technology. Your day in the Apple Store is filled with a range of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.