Next: , Previous: , Up: Classes   [Index]


X11TextEditorPane

X11TextEditorPane Class

Objects of X11TextEditorPane class create a X window which displays text, and editing commands to perform basic text editing operations.

There is an example text editor program that demonstrates a X11TextEditorPane object’s use at the end of this section.

Editing Commands

The set of editing commands that a X11TextEditorPane object uses is given here, along with their key bindings. You can bind them to different keys by modifying the handleKbdInput method.

Right, Ctrl-F       Next character
Left, Ctrl-B        Previous character
Up, Ctrl-P          Previous line
Down, Ctrl-N        Next line
PgDn, Ctrl-V        Next page
PgUp, Ctrl-T        Previous page
Home, Ctrl-A        Start of line
End, Ctrl-E         End of line
Ctrl-Q              Start of text
Ctrl-Z              End of text
Ctrl-D              Delete character under cursor

Alt-V               Paste text from the clipboard at the insertion point.
Alt-C               Copy the selected text to the clipboard.
Alt-X               Delete selected text and save the text on the clipboard.

Backspace           Delete previous character.  If selecting text, delete
                    the selection.
Del                 Delete the character under the cursor, or the
                    previous character if at the end of the text.
                    If there is selected text, delete the selection.
Esc                 Close the window and exit the program.

Mouse-1             Move the insertion point cursor to the click.
                    Click and drag the pointer to select text.
Mouse-2             Paste text of the X selection at the insertion point.

Cutting and Pasting Text with the X Selection

X11TextEditorPane objects can copy text selections to the X primary selection, and paste selected text from other X programs into the program’s text.

To select text to be pasted into another application, press the left pointer button and drag the pointer across the text that you want to select. The text should be highlighted with the color defined in the selectionBackgroundColor instance variable.

Then, switch to the window that you want to paste the text into, and press the center pointer button at the point where you want to insert the text (or press the left and right buttons simultaneously on machines with two buttons).

Conversely, to paste text into the X11TextEditorPane object’s contents, select the text in the other application’s window, then switch to the X11TextEditorPane object’s window, and press the center pointer button at the point where you want the text inserted.

If the program has text selected and another program tries to place its contents in the X primary selection, the class will allow the selection ownership to change to the other program. Any text that was selected in the X11TextEditor pane’s window will no longer be selected.

In general, X programs aren’t required to send their to the display’s X selection buffers. Many programs only use selected contents internally, and may require another command to send the content to the X display’s primary selection buffer. X11TextEditorPane objects maintain the contents of its selection buffer continuously when selecting, but they only send the contents to the X display’s primary selection when another program requests it.

Cutting and Pasting Text with the X Clipboard

X11TextEditorPane objects also provide generic support for copying and pasting text using the X clipboard.

Many graphical environments provide their own clipboard implementation, and X11TextEditorPane class doesn’t yet support them. For vanilla clipboard implementations, however, selecting text for the clipboard is similar to the the X selection’s process: press the left pointer button and drag the pointer across the text that you want to select. The text should be highlighted with the color defined by the selectionBackgroundColor instance variable.

However, the clipboard operations’ are performed entirely with keystrokes, and the key bindings are customizable, even though most text oriented applications use a standard set of key definitions for working with the clipboard:


Alt-X         Cut the selected text and save it on the clipboard.
Alt-C         Copy the selected text to the clipboard, without deleting it.
Alt-V         Paste the text from the clipboard at the point where the
              user clicks.

Fonts

The demonstration program, demos/x11/ctedit.ca, provides options to change the default font and point size. The X11 utility programs xfontsel(1) and fc-list(1) can display the X bitmap fonts and the Xft library’s scalable fonts that are available on the machine, respectively.

Programs configure X fonts within the window’s graphics context, using the instance variable fontVar, which is inherited from X11Pane class.

FreeTypeFonts need to be configured separately from the X window, but the parent X11Pane object also defines the ftFontVar instance variable, so the program can configure outline fonts before entering its event loop.

If a program is to be configurable for different machines, it should check which of the font libraries are present on the system, and which of the fontVar or ftFontVar instance variables the program has configured in the program’s initialization.

The X11TextEditorPane class uses monospaced fonts exclusively. If a program requests a proportionally spaced font, the pane’s libraries won’t maintain alignment between the displayed text and editing operations.

The sections, X11FreeTypeFont and X11Font contain more information about how to select fonts. See X11FreeTypeFont, See X11Font.

Instance Variables

bufLength

An Integer that records the size of the object’s text buffer. The class adjusts the buffer’s size automatically if necessary.

button

An Integer that records the state of the mouse buttons, i.e., whether they are pressed or not. The values that the the variable might contain are composed of these definitions.


#define BUTTON1MASK  (1 << 0)
#define BUTTON2MASK  (1 << 1)
#define BUTTON3MASK  (1 << 2)  

foregroundColor

A String that contains the window’s foreground color. The variable is included here to facilitate drawing the cursor in reverse video. The backgroundColor instance variable is declared in X11Pane class. See X11Pane.

An Integer that defines the right margin in character columns. Setting this to zero ‘0’ sets the line width limit to the line length, so the line width in character columns is calculated as:


lineWidth = (window_width_px - left_margin_px - right_margin_px) /
               character_width_px;

rightMargin

The distance in pixels from the right edge of the window, leftward to the right-hand limit of each line’s length.

point

An Integer that contains the current position in the text where editing occurs.

selectionBackgroundColor

A String that contains the background color of selected text. The foreground color is the same as normal text.

sStart
sEnd
selecting

The Integer variables sStart and sEnd record the beginning and end of selected text as character indexes into the text. The Boolean variable selecting is true while the pointer is being dragged across text while Button 1 is pressed.

shiftState

An Integer that records whether the Shift of Control keys are currently pressed.

textLength

An Integer that records the length of the object’s text.

Instance Methods

attachTo (Object parent_pane)

Attach a X11TextEditorPane object to its parent pane, which is typically a X11PaneDispatcher object. This method initializes the size of the pane’s window and buffers to the parent pane’s dimensions, and positions the pane at the upper left-hand origin of the main window.

background (String colorName)
foreground (String colorName)

Sets the foreground and backgrounds color of the pane’s window and buffers.

clearSelection (void)

Sets the sStart and sEnd instance variables to ‘0’, cancelling text selection.

defaultFormat (void)

Sets the document-wide margins and text text colors. If the pane is using an X11FreeTypeFont object to render text, the font needs to be configured before calling this method. See X11FreeTypeFont.

displayText (void)

Displays the text and editing cursor. Programs should call this method as soon as possible after the program starts the X event loop (which it does by calling the X11TerminalStream : openEventStream method), and after every editing operation.

gotoChar (Integer n)

Sets the point instance variable to the n’th character in the text. If n is greater than the length of the text, sets point to the end of the text.

new (String paneName)

Initializes the X11TextEditorPane object’s event handlers, and calls constructors in the X11TextEditorPane's superclasses to perform addition initialization. The method attachTo, declared in X11TextPane class, performs the actual dimensioning of the pane and its buffers. See X11TextPane.

subPaneKbdInput (X11TextEditorPane subPane, InputEvent event)

Handles Keypress and KeyRelease events from the X server. It’s possible to reconfigure the editing commands by modifying this method.

The method works in conjuction with the Ctalk library’s editing functions to translate alphanumeric and punctuation characters with the correct shift and control state, and to transmit special keys like arrow keys and Home/End keys untranslated.

subPaneButtonPress (X11TextEditorPane subPane, InputEvent event)

The handler for button press and button release events. This method sets the value of the button instance variable, in addition to performing other tasks.

subPaneMotionNotify (X11TextEditorPane subPane, InputEvent event)

The handler method for pointer motion events.

subPaneResize (X11TextEditorPane subPane, InputEvent event)

Handles resizing the X11TextEditor pane’s dimensions in response to a window resize event. This method is a no-op in the current release.

subPaneSelectionClear (X11TextEditorPane subPane, InputEvent event)

Updates the program’s state after receiving a a SelectionClear event. Normally this occurs when another program requests the X primary selection. The method updates this program’s state so that it is no longer selecting, and redraws the text.

Example Text Editing Program

/*
  ctedit.ca - Basic text editor using X11TextEditorPane class.

  Usage:

    ctedit [<options>] <filename>

  Typing, "ctedit -h" displays a list of options.

  Pressing Esc or selecting "Close" from the window menu
  exits the program and saves the edited text.
  
  If <filename> exists, ctedit renames the previous version
  of the file to <filename>.bak.  If <filename> doesn't
  exist, ctedit creates a new file.

  The editing commands are set in the X11TextEditorPane :
  handleKbdInput method.  They are:

     Right, Ctrl-F       Next character
     Left, Ctrl-B        Previous character
     Up, Ctrl-P          Previous line
     Down, Ctrl-N        Next line
     PgDn, Ctrl-V        Next page
     PgUp, Ctrl-T        Previous page
     Home, Ctrl-A        Start of line
     End, Ctrl-E         End of line
     Ctrl-Q              Start of text
     Ctrl-Z              End of text
     Ctrl-D              Delete character under cursor
     Backspace           Delete previous character
     Del                 At the end of the text, delete the
                         previous character.  Otherwise delete
                         the character under the cursor.
     Esc                 Close the window, save the edited text,
                         and exit the program.
 */

#define WIN_WIDTH 500
#define WIN_HEIGHT 340
#define WIN_X 25
#define WIN_Y 30
#define FIXED_FONT "fixed"
#define DEFAULT_BG "white"
#define DEFAULT_FG "black"
#define DEFAULT_FT_FONT "DejaVu Sans Mono"
#define DEFAULT_FT_PTSIZE 12.0

Application new ctEdit;
String new geomString;
String new infileName;
String new xFontName;
String new ftFontName;
Float new ftFontSize;
String new bgColor;
String new fgColor;

Boolean new createFile;

Boolean new useFtFonts;
X11FreeTypeFont new ftFont;
Boolean new useXFont;

void exit_help () {
  printf ("usage: ctedit [-h] | [-g <geom>] [-fg <color>] "
	  "[-bg <color>] [-fn <font> ] <filename>\n");
  printf ("-bg <color>    Set the window background to <color>.\n");
  printf ("-fg <color>    Display the text using <color>.\n");
  printf ("-fn <font>     Use the X <font> to display the text. See xfontsel(1).\n");
  printf ("-ft <font>     Use the FreeType <font> to display the text. See\n");
  printf ("               X11FreeTypeFont class.\n");
  printf ("-g  <geom>     Set the window geometry to <geom>. See XParseGeometry (3).\n");
  printf ("-h             Print this message and exit.\n");
  printf ("-xfonts        Use X bitmap fonts, even if outline fonts are available.\n");
  exit (1);
}

/* UNIX-compatible line ending. */
#define LF 10

X11TextEditorPane instanceMethod writeOutput (String infileName) {
  "Create a backup of the previous version of the file, if any,
   and check that the text ends with a UNIX-standard newline
   (ASCII 10) character."
  WriteFileStream new writeFile;
  Character new c;

  c = self text at (self text length - 1);
  if (c != LF) {
    self text += "\n";
  }
  
  if (!createFile)
    writeFile renameFile infileName, infileName + ".bak";
  writeFile openOn infileName;
  writeFile writeStream (self text);
  writeFile closeStream;

}

Application instanceMethod commandLineOptions (void) {
  Integer new i, nParams;
  String new param;


  nParams = self cmdLineArgs size;
  for (i = 1; i < nParams; i++) {

    param = self cmdLineArgs at i;

    if (param  == "-g") {
      ++i;
      geomString = self cmdLineArgs at i;
      continue;
    }
    if (param == "-fn") {
      ++i;
      xFontName = self cmdLineArgs at i;
      continue;
    }
    if (param == "-bg") {
      ++i;
      bgColor = self cmdLineArgs at i;
      continue;
    }
    if (param == "-fg") {
      ++i;
      fgColor = self cmdLineArgs at i;
      continue;
    }
    if (param == "-ft") {
      ++i;
      ftFontName = self cmdLineArgs at i;
      continue;
    }
    if (param == "-xfonts") {
      useXFont = True;
      continue;
    }
    if (param == "-pt") {
      ++i;
      ftFontSize = (self cmdLineArgs at i) asFloat;
      continue;
    }
    if (param == "-h" || param == "--help" || param == "--h" ||
	param at 0 == '-') {
      exit_help ();
    }
    
    infileName = param;

  }

}

Application instanceMethod winDimensions (void) {
  if (geomString length > 0) {
    self parseX11Geometry geomString;
    if (self winWidth == 0) {
      self winWidth = WIN_WIDTH;
    }
    if (self winHeight == 0) {
      self winHeight = WIN_HEIGHT;
    }
    if (self winXOrg == 0) {
      self winXOrg = WIN_X;
    }
    if (self winYOrg == 0) {
      self winYOrg = WIN_Y;
    }
  } else {
    self winWidth = WIN_WIDTH;
    self winHeight = WIN_HEIGHT;
    self winXOrg = WIN_X;
    self winYOrg = WIN_Y;
  }
}

Application instanceMethod findFtFonts (void) {

  if (useFtFonts && !useXFont) {
    ftFont initFontLib;
    ftFont selectFont ftFontName, 0, 80, 72, ftFontSize;
  }
  
}

int main (int argc, char **argv) {
  X11Pane new xPane;
  X11PaneDispatcher new xTopLevelPane;
  X11TextEditorPane new xEditorPane;
  InputEvent new e;
  Exception new ex;
  X11Cursor new watchCursor;
  ReadFileStream new readFile;
  String new winTitle;

  geomString = "";
  xFontName = FIXED_FONT;
  bgColor = DEFAULT_BG;
  fgColor = DEFAULT_FG;
  infileName = "";
  useFtFonts = True;
  useXFont = False;
  ftFontSize = DEFAULT_FT_PTSIZE;
  ftFontName = DEFAULT_FT_FONT;

  ctEdit parseArgs argc, argv;
  ctEdit commandLineOptions;
  ctEdit winDimensions;

  if (ftFont version < 10) {
    useFtFonts = false;
  } else {
    ctEdit findFtFonts;
  }
  

  if (infileName length == 0) {
    exit_help ();
  }

  if (!readFile exists infileName) {
    createFile = true;
    winTitle = infileName + "   (New file)";
  } else {
    readFile openOn infileName;
    xEditorPane text = readFile readAll;
    readFile closeStream;
    winTitle = infileName;
    createFile = false;
  }

  xPane initialize ctEdit winXOrg, ctEdit winYOrg,
    ctEdit winWidth, ctEdit winHeight, ctEdit geomFlags, winTitle;

  xTopLevelPane attachTo xPane;
  xEditorPane attachTo xTopLevelPane;
  xPane map;
  xPane raiseWindow;
  watchCursor watch;

  xPane openEventStream;

  /* This sets the maximum line width to the width of the window. */
  xEditorPane lineWidth = 0;

  if (!useFtFonts || useXFont) {
    xEditorPane foreground fgColor;
    xEditorPane font xFontName;
    xEditorPane defaultFormat;
  } else {
    xEditorPane defaultFormatFT ftFont;
  }

  xEditorPane background bgColor;
  xEditorPane clear;

  xPane defaultCursor;

  while (TRUE) {
    xPane inputStream queueInput;
    if (xPane inputStream eventPending) {
      e become xPane inputStream inputQueue unshift;
      xPane subPaneNotify e;
      if (ex pending)
 	ex handle;
      switch (e eventClass value) 
	{
	  /*
	   *  Handle both types of events in case the window
	   *  manager doesn't distinguish between them.
	   */
	case MOVENOTIFY:
	  break;
	case RESIZENOTIFY:
	  break;
	case EXPOSE:
	  xEditorPane displayText;
	  break;
	case WINDELETE:
	  xEditorPane writeOutput infileName;
 	  xPane deleteAndClose;
	  exit (0);
	  break;
	default:
	  break;
	}
    } else {
      if (xEditorPane requestClose) {
	xEditorPane writeOutput infileName;
	xPane deleteAndClose;
	exit (0);
      }
    }
  }
}

Next: , Previous: , Up: Classes   [Index]