You are on page 1of 54

A Practical Guide To X Window

Programming : Developing
Applications with the XT Intrinsics and
OSF/Motif First Edition Keller
Visit to download the full and correct content document:
https://textbookfull.com/product/a-practical-guide-to-x-window-programming-developi
ng-applications-with-the-xt-intrinsics-and-osf-motif-first-edition-keller/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

How to Build Android Apps with Kotlin A practical guide


to developing testing and publishing your first Android
apps 2nd Edition Alex Forrester

https://textbookfull.com/product/how-to-build-android-apps-with-
kotlin-a-practical-guide-to-developing-testing-and-publishing-
your-first-android-apps-2nd-edition-alex-forrester/

Efficient R Programming A Practical Guide to Smarter


Programming 1st Edition Colin Gillespie

https://textbookfull.com/product/efficient-r-programming-a-
practical-guide-to-smarter-programming-1st-edition-colin-
gillespie/

Programming Excel with VBA A Practical Real World Guide


Flavio Morgado

https://textbookfull.com/product/programming-excel-with-vba-a-
practical-real-world-guide-flavio-morgado/

Window seat on the world my travels with the Secretary


of State First Edition Johnson

https://textbookfull.com/product/window-seat-on-the-world-my-
travels-with-the-secretary-of-state-first-edition-johnson/
Programming Kubernetes Developing Cloud Native
Applications 1st Edition Michael Hausenblas

https://textbookfull.com/product/programming-kubernetes-
developing-cloud-native-applications-1st-edition-michael-
hausenblas/

SQL Server 2017 Developer s Guide a professional guide


to designing and developing enterprise database
applications 1st Edition Dejan Sarka

https://textbookfull.com/product/sql-server-2017-developer-s-
guide-a-professional-guide-to-designing-and-developing-
enterprise-database-applications-1st-edition-dejan-sarka/

The Trouble with Maths A Practical Guide to Helping


Learners with Numeracy Difficulties 4th Edition Steve
Chinn

https://textbookfull.com/product/the-trouble-with-maths-a-
practical-guide-to-helping-learners-with-numeracy-
difficulties-4th-edition-steve-chinn/

Reservoir modelling: a practical guide First Edition


Cannon

https://textbookfull.com/product/reservoir-modelling-a-practical-
guide-first-edition-cannon/

Arthurian Magic A Practical Guide to the Wisdom of


Camelot First Edition John & Caitlin Mathews

https://textbookfull.com/product/arthurian-magic-a-practical-
guide-to-the-wisdom-of-camelot-first-edition-john-caitlin-
mathews/
A Practical Guide to
X Window
Programming
Developing Applications with the Xt Intrinsics
and OSF/Motif™
A Practical Guide to
X Window
Programming
Developing Applications with the Xt Intrinsics
andOSF/MotiFM

Brian J. Keller

CRC Press
Boca Raton Ann Arbor Boston
First published 1990 by CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742

Reissued 2018 by CRC Press

© 1990 by Multiscience Press, Inc.


CRC Press is an imprint of Taylor & Francis Group, an Informa business

No claim to original U.S. Government works

This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have
been made to publish reliable data and information, but the author and publisher cannot assume responsibility for
the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the
copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to
publish in this form has not been obtained. If any copyright material has not been acknowledged please write and
let us know so we may rectify in any future reprint.

Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or
utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including
photocopying, microfilming, and recording, or in any information storage or retrieval system, without written
permission from the publishers.

Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used only for
identification and explanation without intent to infringe.

Library of Congress Cataloging-in-Publication Data

A Library of Congress record exists under LC control number: 90081308

Publisher’s Note
The publisher has gone to great lengths to ensure the quality of this reprint but points out that some imperfections
in the original copies may be apparent.

Disclaimer
The publisher has made every effort to trace copyright holders and welcomes correspondence from those they
have been unable to contact.

ISBN 13: 978-1-315-89030-2 (hbk)


ISBN 13: 978-1-351-06940-3 (ebk)

Visit the Taylor & Francis Web site at http://www.taylorandfrancis.com and the
CRC Press Web site at http://www.crcpress.com
Once in a lifetime a person comes along
and really makes a difference in another person's life.
This book is dedicated to the person who made
that difference in mine.

To Kim
Contents

Preface xi

Acknowledgments xiii

Introduction 1
1.1. A Brief History of X 1
1.2. The X Window System Architecture 2
1.3. The X Programming Interface — Xlib 6
1.4. Reasons for Using Xt Over Xlib 7
1.5. Why a Practical Guide? 7

Fundamentals: A Helpful Review for Understanding Xt 9


2.1. Review of Structures and Pointers 9
2.2. Window System Basics 13
2.3. Event-Driven Programming 15
2.4. Object-Oriented Programming 16

Xt Basics: An Introduction to Xt-based Widgets 19


3.1. What Is a Widget, Really? 19
3.2. Classes of Widgets 20
3.3. The Components of a Widget 21
3.4. A Windowless Object: The OSF/Motif Gadget 23

Basic X Graphics: Text, Fonts, Bitmaps, and Colors 25


4.1. Text and X 25
4.2. Graphics Context 26
4.3. Handling GCs 27
4.4. Multi-Font Text 28
4.5. Fonts 28
4.6. Bitmaps for Icons 31
4.7. Foreground and Background 32
viii A Practical Guide to X Window Programming

5 Building Applications: Developing with Xt 33


5.1. Conventions 33
5.2. Application Structure 34
5.3. Providing Application Resources 42
5.4. Handling Events 52

6 Building Widgets: Primitive Widgets 99


6.1. Structure of a Primitive Widget 99
6.2. Inheritance in Xt 105
6.3. Requirements for the FieldEdWidget 106
6.4. Constructing the Widget 107
6.5. Summing Up 139

7 Building Widgets: Container Widgets 141


7.1. Composite Widget 141
7.2. Structure of a Composite Widget 141
7.3. Structure of a Constraint Widget 144
7.4. Summing Up 145

8 Sample Application: A Character-Oriented Client 147


8.1. Designing an Xt Application 147
8.2. Standardizing the Interface 148
8.3. Selecting From the Widget Sets 150
8.4. Building the Application 153
8.5. Summing Up 179

9 A Look at OSF/Motif 181


9.1 Motif Environment 181
9.2 Motif Window Manager 182
9.3 The Motif Widgets 187
9.4. Sample Motif Clients 194

10 A Sample Application: Motif Version 209


10.1. Client Components 209
10.2. Building the Client 209
10.3. Summing Up 232

11 Application Development: Advanced Topics 233


11.1. Inter-Client Communication 233
11.2. Using Multiple Displays 248
11.3. Summing Up 253
Contents ix

Appendix A
Widgets, Classing, and Exported Functions
OSF/Motif and Athena XAW (R4 and R3) 255
A.I. Motif Widgets 255
A.2. Motif Widget Classing 256
A.3. Motif Exported Functions 261
A.4. XAW R4 Widgets 265
A.5. XAW (R4) Classing 266
A..6 XAW R4 Exported Functions 270
A.7. XAW R3 Widgets 271
A.8. XAW R3 Classing 271
A.9. XAW R3 Exported Functions 273

Appendix B
Quick Xt Reference Guide XI1R4 275
B.l.Typedefs 275
B.2. BASE Widget Typedefs 276
B.3. Translation Management Typedefs 276
B.4. Intrinsic Specific Procedure Typedefs 276
B.5. Container Routines 283
B.6. Resource Conversion 284
B.7. Event Handling 284
B.8. Checking Routines 285
B.9. Selection Management 286
B.10. Geometry Management 286
B. 11. Translation Management 288
B.I2. Keycode and Keysym Procedures 290
B.13. Event Management 292
B. 14. Event Gathering Routines 294
B.15. Logic Macros 296
B.16. Widget State 296
B.17. Argument List 297
B.18. Information Gathering Routines 298
B. 19. Widget Mapping 299
B.20. Callbacks 299
B.21. Geometry Management 300
B.22. Pop-ups 300
B.23. Widget Creation 302
B.24. Toolkit Initialization 303
B.25. Error Handling 308
B.26. Memory Management 311
x A Practical Guide to X Window Programming

B.27. Work Procedures 312


B.28. Graphics Context 312
B.29. Selection Mechanisms 313
B.30. Grabs 315
B.31. Miscellaneous 317

Appendix C
Quick Guide to the OSF/Motif Widget Set 319
C.l.OSF Widgets 319
C.2. Convenience Routines 320
C.3. XmTextWidget Public Routines 321
C.4. Resource Values 325
C.5. Motif Callback Data Structures 327

Bibliography 339

Index 341
Preface

Application development is the art of filling erratic requests for unusual system
requirements in a "need it yesterday" mode from end users. Many who "... choose
to accept this mission" are confronted with rapid technological changes that must
be kept up with (if not for technological curiosity, then simply because "that's the
way to go"). For many, the X Window System has become "the way to go."
When X was first introduced, the documentation was limited to manuals and
"overview" documents. For those of us who started with X early on these were a
blessing, but learning how to create X clients was not easy or straightforward. There
were few examples and hardly any books that could explain the details of X
Window programming. This lack of a text spawned the idea to create a book that
would cover the details, with sufficient practical examples so that the army of
application writers who wanted to develop applications could do so without too
much pain.
To start, this book is not an Xlib book. Xlib is much too low-level for application
writers. Instead, this book addresses the layer of development referred to as the Xt
Intrinsics. This is a higher level of interaction with the X Window System than
Xlib. It is based on a notion called object-oriented programming, and can greatly
increase your productivity as you develop X Window clients. This book is a
practical guide to Xt, and can be used as a source for application examples. It covers
topics that are useful to the many application programmers who need education in
developing with the Intrinsics.
The audience for this book is anyone who wants to develop Xt-based X Window
clients. It is written with the end-user application writer in mind, so the style is
straightforward and direct. No complicated, technically confusing, "beat around
the bush" verbage! The assumption is that the reader is not creating four-
dimensional cyberspace artifical-reality applications. Instead, the reader develops
applications that are based on end-user requests (those erratic "need it yesterday"
specifications). These people have little time to discuss "byte splitting" or the
challenges involved in piping instructions to UNIX utilities. They need answers
now.

XI
xii A Practical Guide to X Window Programming

As a practical guide, this book continually builds on knowledge as it is acquired.


Chapter 1 begins with the history of X, so that you have an idea where it all started.
Chapter 2 is a fundamentals section that covers some important points in the C
language that you need to be comfortable with before starting Xt programming.
This chapter also includes Window System basics, event-driven programming, and
object-oriented programming concepts.
Chapter 3 is a basic introduction to Xt and the notion of widgets. Chapter 4
discusses several Xlib details that Xt application writers should be aware of,
including graphic contexts, font handling and naming, color allocation, and textual
display. Chapter 5 is the core part of the book. It uses several examples to discuss
all of the major components of the Xt Intrinsics (resource gathering, command-line
parsing, event handling, translations, etc.).
Chapter 6 is a detailed look at primitive widgets. This is accomplished through
the construction of a useful "field editor" widget. This widget is integrated into a
character-oriented application later in the book.
Chapter 7 is a basic overview of container widgets.
Chapter 8 looks into the details of designing Xt applications. It demonstrates the
use of several widgets for constructing interface components including pop-up
menus, pop-up option lists, command buttons, entry fields (using the widget from
Chapter 6), and help facilities. There are also sections that cover keyboard traversal
and ways to streamline development.
Chapter 9 introduces the commercial application environment called Motif
provided by the Open Software Foundation (OSF). The chapter explores, at a high
level, the various widgets and how to work with or customize the Motif Window
Manager (mwm). Some clients are developed to demonstrate the use of the Motif
widgets, including a client that demonstrates the mixing of widget sets (Athena and
Motif).
Chapter 10 shows how to port the application developed in Chapter 8, making
it a Motif-compliant application. This chapter demonstrates pop-up help, pull-
down menus, push buttons, text widget, field editing, keyboard traversal, and two
kinds of help mechanisms.
Finally, Chapter 11 discusses some of the advanced topics in the Intrinsics.
These topics include interclient communication, selection mechanisms in Xt, and
controlling multiple displays with the same client.
Technical books for the most part are not much fun. The style is often esoteric,
dry, and sometimes boring. From the beginning, I intended this project to be
different. I think the reader should enjoy the time spent reading. After all, you're
taking the time out of a busy schedule to read this book. Why not enjoy yourself
and learn at the same time? If I've done my job right, you'll have a few laughs and
learn quite a bit.
Acknowledgments

As we go through life, we seldom get a chance to publicly acknowledge those who


have had some influence on what we do. This book could not have been possible
if it weren't for a few individuals whose actions in one way or another made the
dream of writing into a reality.
Vincent G. Alonzi has been a friend and colleague for quite some time. As a
friend, he has made many a day very entertaining (/ believe you still owe me two
dozen bagels?), and as a colleague, every new job an adventure (Who could forget
Trevose, PAT). It was his "Psst, gotta job for you a t . . . " that triggered the idea for
this book. His thoughtful review and suggestions have greatly helped me in this
effort. (Can you actually believe it's done?)
Bennie Larrier has helped me in ways neither he nor I can understand. I don't
know many who would put themselves on the line to get someone an opportunity
like he did for me.
Paul Kavanaugh acted as the "network node" that brought this book to a real
publisher. His "It's good . . . . A bit too folksy for a Brit" made me realize that I
actually did hit the mark.
Alan Rose is the man behind the scenes. He gave me a chance, bought me some
lunch, got me the loaned computer, and gave me all the time I needed. Alan, thanks!
Hal Remish made the IBM PS/2 Model 70 (the development platform for all
clients in this book) available. I'm sure when he gave it to me he thought it would
be back shortly. Thanks, Hal, for understanding the delays.
Thanks to all the folks who had anything to do with creating and maintaining
the X Window System. If it weren't for their hard work and dedication to bringing
their dreams to realities, mine would not exist. The world needs more of you.
Lastly, Kimberly A. Lanning provided me with my inspiration. From the day I
met her I knew she was someone special. Her patience and understanding during
this long process has made me realize just how special she really is, and how lucky
I am to have her in my life. Thanks, Honey. I love you.

Brian J. Keller

XIII
1

Introduction

This chapter provides you with a brief history of the X Window System (also called
just X), its architecture, a discussion of Xlib, and reasons why Xt is better suited
than Xlib for most application development.

1.1. A Brief History of X


X started as a research project driven by the need to create a hardware-independent
display mechanism for Project Athena. Project Athena is a major research project
being conducted at the Massachusetts Institute of Technology (MIT) to advance
the state of technology for distributed systems. This project is heavily financed by
International Business Machines (IBM) and the Digital Equipment Corporation
(DEC).
The original system was designed by Robert Scheifler, Ron Newman, and Jim
Getty. It borrowed some design ideas from a window system created at Stanford
University called W. The current release, XI1, has been worked on by thousands,
and is still being improved as we all start to use it.
X was developed to provide a distributed mechanism to run applications (re-
ferred to as clients') across a network on a variety of hardware platforms. The
developers focused on providing highly portable code, so that the system could be
implemented on micros (IBM PCs), minis (MicroVaxes), workstations (IBM Rise
System 6000, Sun Spare), and supercomputers (Cray). The system had to be able
to run under several operating environments and provide high performance. And,
in keeping with open systems concepts, X had to be free from user interface policy.
The ability of X to run on and across different platforms makes it perhaps one
of the most innovative technologies to be developed in computing in recent years.
And for this very reason, major vendors (IBM, AT&T, DEC, HP, and Sun) have
embraced X as their display standard for advanced workstations.

1
2 A Practical Guide to X Window Programming

1.2. The X Window System Architecture

1.2.1. Client-Server

The X architecture is based on a client-server relationship. The server (called the


X server) is responsible for the display. A display is considered an X station (a
computer that runs the X server) with one or more CRT, keyboard, and mouse (or
other pointing device). A single instance of an X server is called a display;
therefore, a display (CRT) may have multiple displays by running multiple X
servers, as shown in Figure 1-1.

IBM PS/2 Model 70 Cray


Data Collection Analytical
Client Client

Xlib Xlib
Server Queue Server Queue

IBMRS/6000320

Portfolio
Pricing
Client X
Server
Xlib
Server Queue

Keyboard =—' CRT/Display Input Device

Figure 1-1 Client-server model.


Introduction 3

X is a network windowing system that allows a client to run on either the server
host or any other host on the network. The server sends and receives display
information (i.e., screen-writing commands, keyboard hits, or mouse movements).
This capability implies that a single display station could have numerous clients
from all over the network sending messages to it. An IBM PS/2 could have a client
running on a Cray, another running on an IBM Rise System 6000, and still another
locally. This is truly a distributed processing capability.

1.2.2. X Server Responsibilities

The server is responsible for five tasks:

1. Providing multi-client access.


2. Receiving and understanding client messages.
3. Sending user responses in the form of messages to the clients.
4. Performing all drawing.
5. Storing and maintaining data structures for limited resources (color maps,
cursors, fonts, and graphic information known as "graphics context").

As we mentioned before, the X server can handle client requests over a network.
This provides for the distributed nature of network computing. It is now feasible
to connect several processor classes in your network to handle specific applications.
What this really means is that additional computing power can be added incremen-
tally, allowing for a more controlled increase in a site's computing power.
When clients make requests to the server, the server must be able to decipher
what is being requested. The X server acts like a dispatcher directing traffic in a
city, who receives a request and must determine what the request is for. Based on
the requirements of the request, he must decide which type of vehicle to use: a cab,
a van, or a bus? The X server acts in a similar fashion. It must figure out what
drawing or action it should take based on the request received, and then take action
accordingly.
One of the primary tasks that the X server provides is the control of input and
output functions. Whenever a key is pressed, the server must determine which client
should be informed of it, if any. Similarly, when the mouse is moved the server
must inform one or more clients.
As a way of improving performance, the X server has the responsibility of
performing all drawing that the clients request. So, when a client intends to draw
a line or a character of text, it makes a request to the server, and the server performs
all the necessary steps for generating the graphics. This greatly improves perform-
ance since the client need not be concerned about the "how" of drawing. Addition-
ally, the X server maintains the resources required for generating the graphics.
Fonts, colors, window coordinates, and other graphical pieces of information
are the kinds of resources stored by the server. These data items are given
identification codes by the server so that clients may refer to them. This makes
4 A Practical Guide to X Window Programming

more sense than sending an entire graphics structure with large amounts of
information over a network. By doing it this way, X reduces the network traffic
and leaves bandwidth for other messages.

1.2.3. Window Management

X was developed as a generic mechanism for providing display capabilities in a


network environment. MIT did not enforce a particular style for user presentation;
rather, they provided a way of creating such display policies. One inclusion that is
different from other window systems is the separation of window management (i.e.,
moving, iconifying, resizing) from the client.
The window manager is the "ruler" of the screen (see Figure 1-2). It is respon-
sible for informing its windows about policy. The X Window System does not
commit to any particular window manager. It was felt that the vendors who
supported X would provide their own. This is demonstrated by the inclusion of a
window manager for OSF/Motif as well as AT&T XWIN (Open Look) interface
kits.

Root Window

Window Manager

! i

Client

Client

Figure 1-2 Window manager in X.


Introduction 5

The window manager has the right to enforce anything it wants with respect to
screen layout, overriding any and all client requests for space. It might elect to
move windows to make room for others, or it might inform the client that it can
only be a fraction of the size requested.
The notion that a requested window size may not be granted is significant to
application writers. Take great care in designing applications so as to eliminate any
dependency on a particular window manager's style. Your applications must be
able to cooperate with any window manager, and also without one. Noting this
early will save you a lot of time in the future.

1.2.4. X Protocol

I stated earlier that X has its own protocol, /^protocol is nothing more than an
agreed-upon form of communication. In the X world, this is accomplished via
network packets (chunks of information). There are four kinds of packets that exist
in X: events, replies, requests, and errors.
Events are things like a keyboard press, a mouse movement, or a screen update.
Just like in the real world, events can happen at any time. Clients must be ready
and able to cope with this. The client will never be able to know for sure if it has
to respond to a keystroke or to repaint itself. In order to accommodate this, the
client must inform the server of the events it cares about, and then provide
processing for when the event is reported. (This is discussed in greater detail in a
later section of this book.)
Requests are generated by a library function (Xlib) and sent to the server. A
request packet might contain drawing information, or perhaps a question about a
specific window. When the request is for locally stored information, it quite
obviously does not have to go through the server. Otherwise, the request is passed
to the server where it is acted on and a reply is sent.
Replies emanate from the server to Xlib only when a previous Xlib request was
for server-based information. This situation is considered a round-trip, and as might
be inferred, is quite costly. After all, the client pays the price for the request and
must also pay for the reply. Considering the network framework, this could be quite
substantial if the client makes many requests.
Errors are also sent by the server to Xlib. Xlib has two kinds of error-handlers:
recoverable and fatal. The error is not sent to the client until the client-server
connection is flushed (typically when an event is read). The reason for this latency
in error reporting is due to a design consideration. Since X is network based, and
it is more efficient to send chunks of data across a network, the designers chose to
have the server queue up events and errors while the client queues up requests. The
server gives the server queue to the client when the client initiates the transaction.
At that time the client gives the server its queue.
6 A Practical Guide to X Window Programming

1.3. The X Programming Interface — Xlib


All clients eventually will use Xlib. This is true if you write using straight Xlib or
a higher level library like Xt. As stated earlier, Xlib translates the request into a
network packet to be sent to the server.
As shown in Figure 1-3, Xlib is the lowest level that an application writer can
use for creating X-based clients. The functions that make up Xlib perform every-
thing that any client could possibly need. This includes things such as opening and
closing the display, getting a particular font or color, drawing a line, drawing text,
creating and destroying a window, getting user defaults, and parsing the command
line.
The library is rich with functions and is currently being expanded to include
extensions for 3-D drawing as well as Display PostScript. In any event, the
technique for creating an X-based client is the same in all cases, and the process
can be rather lengthy.

APPLICATION
CODE

Other Tools

Toolkit
Xt Intrinsics
Xlib
X Protocol
Operating System
Figure 1-3 X programming layers.
Introduction 7

1.4. Reasons for Using Xt Over Xlib


As any developer knows, a set of routines that perform the same task and are
gathered into a library is invaluable. After all, who wants to write the same tired
code all the time? If you were an Xlib developer, you would have to rewrite
window-creation and resource-gathering routines for every client. Also, event-han-
dling is not as intuitive in Xlib as it is in Xt. Lastly, the number of lines of code in
an Xt client can be far less than the same one written using Xlib.
When X was first introduced, a basic toolkit was provided. It was a collection
of routines that created display elements like scroll bars, command buttons, and
text editing mechanisms. The writer simply had to invoke these convenience
routines to create a window and add the functionality for a scroll bar. At this level,
an application writer would find it easier to develop interfaces, and this would be
the level most application writers prefer.
When the protocol changed from X10 to XI1, the developers of X took the
opportunity to re-create the toolkit. They did this by providing an objective
approach to building interface components. This included the Intrinsics as mecha-
nisms for using interface components and Athena widgets as samples of how to
write them.
Xt is not a set of widgets, rather it is a style of programming. It defines how a
widget must be written and how applications must use them, but it does not in itself
provide a particular widget set. The Athena widget set (Xaw) has been provided as
a model for application writers to get a feel for developing with and creating new
widgets. Most vendors provide these widgets as samples, and for that reason they
are used in many of the examples found in this book.
So why bother with widgets if you can create clients with Xlib? The reason is
quite simple: widgets are easy to use (if documented correctly), and can eliminate
many redundant steps that all X clients must perform. Also, Xt-based clients are
easier to write, especially when the interface becomes complex. Lastly, the code
savings is tremendous. This is due to the objective mechanisms that Xt employs
(you'll see why as you read on).

1.5. Why a Practical Guide?


Anyone who has attempted to write applications without samples is a true pioneer,
and deserves a tip of the cap. For the rest of us, an example goes a long way in
aiding understanding. Most everyone I have ever developed with found that source
code was the key to their success as developers. I must point out, though, that while
having examples is great, they are simply a possible solution, not the only one. You
are encouraged to use the techniques in this book, but you should also search for
new and perhaps more efficient ways of doing things.
This book demonstrates the majority of topics that application writers need to
address when they begin to write their own interfaces. Sure, you could do what I
8 A Practical Guide to X Window Programming

did to learn Xt. You would spend a lot of hours reading the pages of the Xt Intrinsics
code along with the source from the widget sets (Athena and HP). You would
attempt to use the MIT documents and search for examples over the network. You
would go to lunch with one of the creators of the XI1 Xt Intrinsics (Joel Mc-
Cormack) and discuss the philosophy of the design of Xt. Finally, you would attend
the X Technical Conference, purchase some Xlib books, and start to bang out code.
In the end, you would finally be clear on how to write Xt-based clients.
I would recommend you save yourself some time and use this book. Believe me,
you will get more out of this book than you realize. Enjoy!
Fundamentals: A Helpful
Review for Understanding Xt

In order to get a foundation from which to build a better understanding of Xt, it is


important to discuss a few concepts prior to diving in. This chapter is intended to
get everyone on the same playing field.

2.1. Review of Structures and Pointers


If you haven't figured it out yet, let me tell you: C is the language used to program
with Xt. For many an application programer this might cause a wince. After all, C
can be a bit of a pain to deal with. It gives great flexibility to get at the low levels
of the machine, but with that comes the ability to crash the system. (Has anybody
ever crashed a system with a C program? Let's see a show of hands.)
Perhaps the most problematic part of the C language for many are these things
called pointers. So, in an attempt to set you straight, let's discuss them for a bit.
A pointer is variable in the C language. Its sole purpose in life is to look at a
place in the computer's memory. The thing a pointer holds is called an address. An
address is simply a place in the computer's memory. You'll find the operating
system, data, and programs loaded there.
In C there are a variety of data types. The usual are int (short and long), float,
double, and char. Each of these can have an associated pointer type: int*, float*,
double*, char*. For example, if you saw the following definition in a C program:

int x, *xp;

it would read "x is of type int and xp is of type pointer-to-int." This means that xp
can contain the memory address of another variable that is of type int. The same
holds true for float, double, and char.
To get a pointer to point at something, you must assign it the thing's memory
address (see Figure 2-1). Recalling the earlier definition, you could have xp point
to x by doing the following:
9
10 A Practical Guide to X Window Programming

Pointer-to-Value
int ival,*ip;
ival = 12;
ip = &ival;

ip * ival
0x2000 storage location 0x1000

0x1 000 value at location 12

Pointer-to-Pointer-to-Value
char cv,*cp1 ,*cp2;
cv = 'A';
cp1 = &cv;
cp1 = cp2; /* pointers are already addresses */

cp2 E cp1 E cv
0x2018 storage location 0x2016 0x2010
0x2016 value at location 0x2010 A
Figure 2-1 Pointer.

xp - &x;

This reads "assign the address of x to xp." Since xp is a pointer type, xp now looks
atx.
Suppose you wanted to get the value that a pointer was looking at. How could
you do that? It is pretty simple, actually. The C language provides the asterisk "*"
as an operator for getting the value (not to be confused with multiplication or the
definition of the pointer).
For example, suppose the code looked like the following:

int x = 2,*xp;
int q;
xp = &x;

and you wanted to assign the value in x to q. It would be easy to assign the value
of x to q by simply saying
Fundamentals: A Helpful Review for Understanding Xt 11

x;

but you are using pointers and would rather see how to do this using them.
Therefore, to assign the value of x to q using the pointer xp, you write the following:

q = *XP;

This says "assign the value that xp is pointing at to q," so now q has the value 2.
This really isn't so bad. Now that you think you feel good about pointers, just
remember:
A Pointer is like 220 volts of electricity. If you don't ground it well, you could
lose your life!
That is, pointers are fantastic when used with care, and very dangerous when
they are not. Since they truly are memory addresses, you could be pointing to an
area that is in the data space of another program — or anywhere else, for that matter.
If you're not careful, eventually things will break and you'll either get that useful
message, "Segmentation violation" (the OS cop is out to get you), or worse, your
machine will start to reboot itself (the old pointer gremlin is at it again).
Now that you understand pointers better, let's look at another useful tool in C's
arsenal: the structure. Just like the name implies, a structure gives you a way of
placing data in a nice, neat, orderly manner.
If you have ever done database programming, you've come across structures
when you defined records for the database. As an example, suppose you are
interested in defining a structure for a trade (exchange of stocks or bonds) record.
You know that the members would include security, trader id, buy/sell flag,
quantity, and price. In C, this could look like the following:

struct {
char *security;
char *traderld;
char buy_or_sell;
int quantity;
float price;
} tradeRecord;

Another powerful feature of the C language is its ability to create new data types.
This is accomplished using a typedef statement. Essentially, you can create a
shorthand notation for a new storage class of your own. By far the most common
use of the typedef statement is with a structure. For example, if you wanted to use
the tradeRecord in other places in your program, you could create a typedef like
this:
12 A Practical Guide to X Window Programming

typedef struct _TradeRecord {


char *security;
char *traderld;
char buy_or_sell;
int quantity;
float price;
} TradeRecord;

You now have a new type called TradeRecord. With the new TradeRecord type
you can go about defining some structures in your program.

TradeRecord Equity =
{"IBM","BJK",'B',1000,100.25};

TradeRecord *PtrToIt;
PtrToIt - SEquity;

Now let's access some of the members:

printf("%s %c %d shares of %s at $ %f\n",


Equity.trader,Equity.buy_or_sell,
Equity.quantity, Equity.security,Equity.price);

This would print the following:

BJK B 1000 shares of IBM at $ 100.25

Notice that you used the "." (dot) operator to access the members. This is the way
C gets to the members of structures when the structure variable is not a pointer
type. Now let's use the pointer type PtrToIt to get the values:

printf("%s %c %d shares of Is at $ %f\n",


PtrToIt->trader,PtrToIt->buy_or_sell,
PtrToIt->quantity, PtrToIt->security,PtrToIt->price);

This would print the following:

BJK B 1000 shares of IBM at $ 100.25

Notice that you used the "->" (arrow) operator to access the members. This is the
way C gets to the members of structures when the structure variable is a pointer
type.
Since you are by now an expert at this, let's cover one last detail that is used
heavily in Xt. This is the opaque pointer type. The opaque pointer type used in the
Xt is "caddrj" (changed to XtPointer in X11R4) and is defined as either "char *"
or "void *" depending on the C compiler being used. The opaque pointer is allowed
Fundamentals: A Helpful Review for Understanding Xt 13

to assume the role of a pointer to int, pointer to float, or pointer to whatever, as in


the following code fragment:

caddr_t chameleon;
int x - 2;
chameleon • &X)
printf("%d\n",'chameleon);

If this brief review of pointers and structures isn't enough, refer to one of the
zillion books written on the C language. Or use the "default" book by Kerninghan
and Richie (the second edition is quite good).

2.2. Window System Basics


In order to write applications for X, you should get a feel for some of the basic
relationships that exist. X is built using a hierarchical window system termed a
window tree. There will always be one root window. The root window always
covers the entire display area, and all other windows are its descendants. Addition-
ally, windows on the same level in the tree are called siblings while the parent of
a child is called an ancestor to the child. This is shown in Figure 2-2.

Root Window <o

Window A <p> Window C


2 , (P>
p
Window B < >
Window A1 Window C1
2

Window B1 Window B2

1. Child Relationship
2. Sibling
(P) Parent Relationship

Figure 2-2 Parent/child/sibling.


14 A Practical Guide to X Window Programming

An X window can be viewed as a "roundtangle" — usually, but not quite always,


a rectangle. The reason for the new name is that for most of X's life all that
programmers could get were rectangles. However, with XI1R4, the folks at MIT
incorporated a "shapes" extension, so windows need not be rectangular.
The upper-left corner of an X window is considered to be its origin (see Figure
2-3). The x-axis increases as you go left while the y-axis increases as you go down.
All coordinates in X are relative, that is, from the window's point of view all things
start at 0,0. If a window is created and is offset from the root window at 100,100
the root window's perspective of the child's origin is 100,100 while the child views
it as 0,0.
The X server is where all windows live. Whenever a window is created, the
application must ask the X server to do it. The server adds the newly created
window to the window tree when the request is made. Once added, the client may
request to be mapped and hence viewable by the user.
There are times when windows are mapped yet are not viewable. These situa-
tions occur for three reasons:

1. One of the ancestors is not mapped.


2. One window completely obscures another (as in window C of Figure 2-4).
3. When an ancestor completely clips a window.

+y +y

/offset

x offset
height

width

Figure 2-3 Window geometry.


Another random document with
no related content on Scribd:
alcancem. Tratase hūa Historia de hum Ermitão, et hum
Salteador de caminhos» (Está en Braga, n. 151).
Cont. II. «Que as filhas devem tomar o conselho da sua boa may,
e fazer seus mandamentos. Trata de hūa que o não fez, e a
morte desastrada que ouve» (Braga, n. 152).
Cont. III. «Que as donzellas, obedientes, devotas e virtuosas, que
por guardar sua honra se aventurão a perigo da vida, chamando
por Deos, elle les acode. Trata de hūa donzella tal que he digno
de ser lido» (Braga, n. 153).
Cont. IV. «Que diz que as zombarias são perjudiciaes, e que he
bom não usar delles, concluesse autorizado con hum dito grave».
Es meramente un dicho sentencioso de un caballero de la Corte
de D. Juan III: «Senhor, não zombo, porque o zombar tem
resposta».
Cont. V. «Trata do que aconteceo en hūa barca zombando, e hūa
resposta sotil».
Son zumbas y motejos entre un corcobado y un narigudo, que
acabaron mal.
Cont. VI. «Que en toda parceria se deve tratar verdade, porque o
engano ha se de descobrir, e deixa envergonhado seu mestre.
Trata de dous rendeiros».
Historia insulsa que tiende á recomendar la buena fe en los
contratos.
Cont. VII. «Que aos Principes convem olhar por seus vassalos,
para lhe fazer merce. E os despachadores sempre devem folgar
disso, e não impedir o bõ despacho das partes. Trata hum dito
gravissimo de hum Rey que Deos tem».
Un Rey justiciero da á un mancebo de Tras os Montes el cargo
de contador del almojarifazgo que tenía su padre, y haciéndole
alguna observación su veedor de Hacienda sobre la inutilidad del
cargo, le replica: «Se nos não havemos mister o contador, o
mancebo ha mister o officio».
Cont. VIII. «Que os Prelados socorram com suas esmolas a seus
subditos, e os officiaes de sua casa lhe ajudem. Trata de hum
Arcebispo e seu veador».
El Arzobispo de Toledo de quien se trata es D. Alonso Carrillo, y
el cuento procede de la Floresta Española, como decimos en el
texto: «Vos faço saber que estes que me servem ham de ficar em
casa, porque eu os ey mister, e estes que me não servem,
tambem ficarão, porque elles me ham mister a mi».
Cont. IX. «Que ha hum genero de odios tam endurecido que
parece enxerido pello demonio. Trata de dous vezinhos
envejosos hum do outro» (Braga, II, 154).
Cont. X. «Que nos mostra como os pobres com pouca cousa se
alegram. E he hum dito que disse hum homen pobre a seus
filhos» (Braga, II).
Cont. XI. «Do que acontece a quem quebranta os mandamentos
de seu pay, e o proveyto que vem de dar esmolla, e o dano que
socede aos ingratos. Trata de hum velho e seu filho» (Braga, II,
157, con el título de O segredo revelado).
Cont. XII. «Que offerecendosemos gostos ou perda, o sentimento
ou nojo seja conforme a causa, concluindo con elle. Trata hum
dito de hum Rey que mandou quebrar hūa baixella».
Cont. XIII. «Que os que buscam a Deos sempre o achão. Trata
de hum hermitan, e hum pobre lavrador que quis antes un real
bem ganhado que cento mal ganhados» (Braga, n. 156).
Cont. XIV. «Que todo tabellião e pessoa que da sua fe em juizo,
deve attentar bem como a da. Trata hūa experiencia que fez hum
senhor para hum officio de Tabellião» (Braga, n. 158).
Cont. XV. «Que os pobres não desesperem nas demandas que
lhe armão tyrannos. Trata de dous irmãos que competiam em
demanda hum com outro, e outras pessoas» (Braga, 159).
Cont. XVI. «Que as molheres honradas e virtuosas devem ser
calladas. Trata de hūa que fallou sem tempo e da reposta que lhe
derão.
Anécdota insignificante, fundado en el dicho de una mujer de
Llerena.
Cont. XVII. «Como castiga Deos accusadores, e liura os
innocentes. Trata de hum Comendador que foy com falsidade
accusado diante del Rey» (Braga, n. 160, con el título de Don
Simão).
Cont. XVIII. «De quam bom he tomar conselho com sabedores e
usar delle. Trata de hum mancebo que tomou tres conselhos, e o
sucesso» (Braga, n. 161).
Cont. XIX. «Que he hūa carta do Autor a hūa senhora, com que
acaba a primeira parte destas historias e contos de proveito e
exemplo. E logo começa segunda, em que estão muitas historias
notaveis, graciosas, e de muito gosto, como se vera nella».
Parte 2.ª.
Cont. I. «Que trata quanto val a boa sogra, e como por industria
de hūa sogra esteve a nora bem casada com o filho que a
aborrecia» (Braga, n. 162).
Cont. II. «Que diz que honrar os Sanctos e suas Reliquias, e
fazerlhe grandes festas he muito bem, e Deos e os Sanctos o
pagão. Trata de hum filho de hum mercador, que con ajuda de
Deos e dos Sanctos veo a ser Rey de Inglaterra».
Cont. III. «Que diz nos conformemos com a vontade do Senhor.
Trata de hum Medico que dizia: Tudo o que Deos fez he por
melhor» (Braga, n. 163).
Cont. IV. «Que diz que ninguem arme laço que não caya nelle.
Trata de hum que armou hūa trampa para tomar a outro, e cahio
elle mesmo nella».
Cont. V. «Que diz que a boa mulher he joya que não tem preço, e
he mellior para o homen que toda a fazenda e saber do mundo
como se prova claro ser assi no discorso do conto».
Es un largo ejemplo moral.
Cont. VI. «Que nāo confie ninguem em si que sera bom, porque
ja o tem promettido: mas andemos sobre aviso fugindo das
tentações. Trata hum dito de hum arraez muito confiado».
Cont. VII. «Que nāo desesperemos nos trabalhos, e confiemos
em Deos que nos proverá, como fez a huma Rainha virtuosa con
duas irmãas que o nāo erão, do que se trata no conto seguinte»
(Braga, n. 164).
Cont. VIII. «Que o poderoso nāo seja tyranno, porque querendo
tudo, nāo alcança o honesto e perde o que tem. Como se ve em
hūa sentença sotil em caso semelhante» (Braga, n. 165).
Cont. IX. «Que diz que conformes com a vontade de Deos nosso
Senhor lhe demos louvores e graças por tudo o que faz. Trata de
hum dito do Marquez de Pliego, em tempo del Rey Don Fernando
Quinto de Castella».
Terceira parte.
Cont. I. «Que todos sejamos sojeitos a razam, e por alteza de
estado nāo ensoberbeçamos, nem por baixeza desesperamos.
Trata de hū Principe, que por soberbo hum seu vassallo pos as
mãos nelle, e o sucesso do caso he notavel» (Braga, n. 166).
Cont. II. «Que quem faz algum bem a outro, nāo lho deve lançar
em rosto, e que sempre se deve agradecer a quem nos da
materia de bem obrar».
Trátase de una carestía de Córdoba. Este cuento, ó más bien
dicho sentencioso y grave contra los que echan en cara los
beneficios recibidos, parece de origen castellano.
Cont. III. «Que diz quanto val o juizo de hum homen sabio, e
como por hum Rey tomar con elle, o tirou de huma duvida en que
estava com hum seu barbeiro» (Braga, n. 168).
El Rey invita á su barbero á que le pida cualquier merced,
prometiendo concedérsela. El barbero le pide la mano de la
princesa su hija. Sorprendido el rey de tal petición, consulta con
un sabio, el cual le aconseja que mande abrir la tierra en el sitio
donde había estado el barbero, porque sin duda habría puesto
los pies sobre un gran tesoro, que le daba humos para aspirar
tan alto. El tesoro aparece en efecto, y el rey lo reparte entre el
barbero y el letrado que dió tan buen consejo. Ignoro el origen de
este absurdo cuento.
Cont. IV. «Trata como dous mancebos se quiseran em estremo
grao, e como hum delles por guardar amizade se vio em grandes
necessidades, e como foy guardado do outro amigo».
Cont. V. «Que inda que nos vejamos em grandes estados nāo
nos ensoberbeçamos, antes tenhamos os olhos onde nacemos
para merecer despois a vir a ser grandes senhores, como
aconteceo a esta Marqueza de que he o conto seguinte». (Braga,
n. 107, con el título de Constancia de Griselia).
Cont. VI. «Em que mostra de quanto preço he a virtude nas
molheres, especialmente nas donzelas, e como hūa pobre
lavradora por estimar sua honra em muyto, veo a ser grande
senhora».
Cont. VII. «Neste conto atraz tratei hūa grandeza de animo que
por comprir justiça usou Alexandro de Medices Duque de
Florença com hūa pobre Donzela, e porque este he de outra
nobreza sua que usou com hūa pobre viuva, a qual he o
seguinte» (Braga, n. 169, O achado da bolsa).
Cont. VIII. «Em que se conta que estando hūa Raynha muyto
perseguida e sercada em seu Reyno, foy liurada por hum
cavaleyro de quem ella era en estremo enemiga, e ao fim veio a
casar com elle».
Cont. IX. «Que mostra de quanta perfeição he o amor nos bōs
casados, e como hum homen nobre se pos em perigo da morte
por conservar a hōra de sua molher, e por a liurar das miserias
em que vivia, e como lhe pagou com o mesmo amor».
Cont. X. «Em o qual se trata de hum Portuguez chegar a cidade
de Florença, e o que passou com o Duque senhor della, com hūa
peça que lhe den a fazer, o qual he exemplo muy importante para
officiaes».]
[199] Página 11 de la edición de Francisco Asensio.
[200] Vid. E. Cosquin, La Légende du Page de Sainte Elisabeth
de Portugal et le conte indien des «Bons Conseils», en la Revue
de Questions Historiques, enero de 1903.
[201] Á las comparaciones hechas por el primero en sus notas á
los Awarische Texte de A. Schiefner (n. 12) hay que añadir la
monografía del segundo sobre Quatro Novelline popolari livornesi
(Spoleto, 1880). Una nota de Teófilo Braga, que excuso repetir (II,
192-195), resume estas indagaciones. Pero para estudiarlas á
fondo, habrá que recurrir siempre a los fundamentales trabajos
de Köhler (Kleinere Schriften zur Märchenforschung von Köhler
Herausgegeben von Iohannes Bolte, Weimar, 1898, pp. 118, 143,
565 y ss.).
[202] Basque Legends: collected, chiefly in the Labourd, by Rev.
Wentworth Webster... Londres, 1879, pág. 176.
[203] Recuérdese lo que hemos dicho en la página LVII, nota 2.ª.
[204] Part. 1.ª, nov. XIV. «Alessandro duca di Firenze fa che
Pietro sposa una mugnaja che aveva rapita, e le fa far molto ricca
dote».
En el cuento siguiente de Trancoso (VII de la 3.ª Parte) hay
alguna reminiscencia (pero sólo al principio) de la novela XV,
parte 2.ª, de Bandello («Bell' atto di giustizia fatto da Alessandro
Medici, duca di Firenze contra un suo favorito cortegiano»),
[205] En las notas de Valentin Schmidt á su traducción alemana
de algunas novelas de Straparola puede verse, una indicación de
ellas.
Märchen-Saal. Sammlung alter Märchen mit Anmerkungen;
herausgegeben von Dr. Friedr. Wilh-Val. Schmidt. Erster Band.
Die Märchen des Straparola, Berlín, 1817.
Pero es mucho más completo el trabajo de G. Rua, Intorno alle
«Piacevoli dello Straparola (Giornale Storico della letteratura
italiana, vol. XV y XVI, 1890).
[206] Cap. 124. «Quod mulieribus non est credendum, neque
archana committendum, quoniam tempore iracundiae celare non
possunt». Ed. Oesterley, p. 473. Trae copiosa lista de paradigmas
en la página 732.
[207] «Pisti è dannato per micidiale, e gli è levato tutto l' hauere, e
son promessi premii a chi l' uccide, o vivo il dà nelle mani della
giustitia; Egli si fà offerire a' Signori, e libera la familia da disagio,
e se da pericolo. (Novella 5, prima deca de Gli Hecatommithi).
[208] «Caritea ama Pompeo, Diego innamorato della giouane, l'
uccide; Ella promette di darsi per moglie a chi le da il capo di
Diego. Le moue guerra il Re di Portogallo. Diego la difende, e fa
prigione il Re, poscia si pone in podestà della Donna, e ella lo
pliglia per marito» (Novella 1ª seconda deca).
[209]

Jupiter ambiguas hominum praediscere mentes,


Ad terras Phoebum misit ab arce poli.
Tunc duo diversis poscebant numina votis;
Namque alter cupidus, invidus alter erat.
His sese medium Titan; scrutatus utrumque,
Obtulit, et precibus ut peteretur, ait:
Praestabit facilis; nam quae speraverit unus,
Protinus haec alter congeminata feret.
Sed cui longa jecur nequeat satiare cupido,
Distulit admotas in nova lucra preces:
Spem sibi confidens alieno crescere voto,
Seque ratus solum munera ferre duo.
Ille ubi captantem socium sua praemia vidit,
Supplicium proprii corporis optat ovans.
Nam petit extincto ut lumine degeret uno,
Alter ut, hoc duplicans, vivat utroque carens.
Tunc sortem sapiens humanam risit Apollo,
Invidiaeque malum rettulit inde Jovi.
Quae dum proventis aliorum gaudet iniquis,
Laetior infelix et sua damna cupit.
[210] Vid. T. Braga, II, 27.
[211] Sigo, con algún ligero cambio, la antigua traducción
castellana de Juan Bautista de Morales, impresa por primera vez
en 1622.
Corte en aldea y noches de invierno de Francisco Rodríguez
Lobo... En Valencia: en la oficina de Salvador Fauli, año 1793.
Diálogo X. «De la materia de contar historias en conversación».
Diálogo XI. «De los cuentos y dichos graciosos y agudos en la
conversación». PP. 276-355.
[212] Vid. Serrano y Morales, La Imprenta en Valencia, pp. 285-
327. En la pág. 323 de este precioso libro está publicado el
testamento de Felipe Mey, que nombra entre sus hijos á
Sebastián, con lo cual queda plenamente confirmado lo que
sobre este punto conjeturó D. Nicolás Antonio.
[213] Fabulario en que se contienen fabulas y cuentos diferentes,
algunos nueuos y parte sacados de otros autores; por Sebastian
Mey. En Valencia. En la impression de Felipe Mey. A costa de
Filipo Pincinali a la plaça de Vilarasa.
8.º, 4 hs. prls. y 184 pp.
Aprobación del Pavorde Rocafull, 20 de enero de 1613.—Escudo
de Mey.—Prólogo.
«Harto trillado y notorio es, a lo menos a quien tiene mediana
licion, lo que ordena Platon en su Republica, encargando que las
madres y amas no cuenten a los niños patrañas ni cuentos que
no sean honestos. Y de aqui es que no da lugar a toda manera
de Poetas. Cierto con razon, porque no se habitue a vicios
aquella tierna edad, en que facilmente, como en blanda cera, se
imprime toda cosa en los animos, haviendo de costar despues
tanto y aun muchas vezes no haviendo remedio de sacarlos del
ruin camino, a seguir el cual nos inclina nuestra perversa
naturaleza. A todas las personas de buen juicio, y que tienen zelo
de bien comun, les quadra mucho esta dotrina de aquel Filosofo:
como quepa en razon, que pues tanta cuenta se tiene en que se
busque para sustento del cuerpo del niño la mejor leche, no se
procure menos el pasto y mantenimiento que ha de ser de mayor
provecho para sustentar el alma, que sin proporcion es de muy
mayor perficion y quilate. Pero el punto es la execucion, y este es
el fin de los que tanto se han desvelado en aquellas
bienaventuradas republicas, que al dia de hoy se hallan
solamente en los buenos libros. Por lo qual es muy acertada y
santa cosa no consentir que lean los niños toda manera de libros,
ni aprendan por ellos. Uno de los buenos para este efeto son las
fabulas introduzidas ya de tiempo muy antigo, y que siempre se
han mantenido: porque a mas de entretenimiento tienen dotrina
saludable. Y entre otros libros que hay desta materia, podra
caber este: pues tiene muchas fabulas y cuentos nuevos que no
están en los otros, y los que hay viejos estan aqui por diferente
estilo. Nuestro intento ha sido aprovechar con él a la republica.
Dios favorezca nuestro deseo».
Cada una de las fábulas lleva un grabadito en madera, pero
algunos están repetidos.
[214] Modern Language Notes, Baltimore, junio y noviembre de
1906.
[215] Para que nada falte á la descripción de tan raro libro,
pondremos los títulos de estas fábulas, con sus moralidades
respectivas:
Fábula I. El labrador indiscreto. Es la fábula del molinero, su hijo
y el asno, tornada probablemente de El Conde Lucanor, cap. 24
de la edición de Argote.

Quien se sujeta á dichos de las gentes,


Ha de caer en mil inconvenientes.
Fáb. II. El gato y el gallo. Hipócritas pretextos
del gato para matar al gallo y comérsele.
Con el ruin son por demás razones,
Que al cabo prevalecen sus pasiones.
Es la fábula 4.ª del «Isopo de la traslacion
nueva de Remigio» en la colección del infante
Don Enrique.
Fáb. III. El viejo y la muerte.
Los hombres llaman á la muerte ausente,
Mas no la quieren ver quando presente.
Fáb. IV. La hormiga y la cigala.
Quando estés de tu edad en el verano,
Trabaja, porque huelgues cuando anciano.
Fáb. VI. El álamo y la caña.
Mas alcanza el humilde con paciencia,
Que no el soberbio haziendo resistencia.
Fáb. VII. La raposa y la rana.
De la voz entonada no te admires,
Sin que primero de quien sale mires.
Fáb. IX. La raposa y las uvas.
Quando algo no podemos alcançar,
Cordura dizen que es dissimular.
Fáb. XI. El leon, el asno y la raposa.
Quando vemos el daño del vecino,
No escarmentar en él es desatino.
Fáb. XII. La mujer y el lobo.
La muger es mudable como el viento:
De sus palabras no hagas fundamento.
Fáb. XIV. El gallo y el diamante.
No se precia una cosa, ni codicia,
Si no es donde hay de su valor noticia.
Fáb. XV. El cuervo y la raposa.
Cuando alguno te loa en tu presencia,
Piensa que es todo engaño y apariencia.
Fáb. XVII. El leon y el raton.
No quieras al menor menospreciar,
Pues te podrá valer en su lugar.
Fáb. XIX. La liebre y el galápago.
Hazienda y honra ganarás obrando,
Y no con presuncion emperezando.
Fáb. XXI. La rana y el buey.
Con los mayores no entres en debate,
Que se paga muy caro tal dislate.
Fáb. XXII. El asno y el lobo.
Entienda cada qual en su exercicio,
Y no se meta en el ageno oficio.
Fáb. XXIV. El consejo de los ratones.
Ten por consejo vano y de indiscreto,
Aquel del qual no puede verse efeto.
Fáb. XXV. El grillo y la abeja.
De su trabajo el hombre se alimente,
Y á gente vagamunda no sustente.
Si fueres docto, y no seras discreto,
Seran tus letras de muy poco efeto.
Fáb. XXIX. Las liebres y las ranas.
Aunque tengas miseria muy notable,
Siempre hallarás quien es más miserable.
Fáb. XXX. El asno, el gallo y el leon.
Quien presume de sí demasiado,
Del que desprecia viene á ser hollado.
Fáb. XXXI. La raposa y el leon.
En aprender no tomes pesadumbre,
pues lo hace fácil todo la costumbre.
Fáb. XXXIII. El asno, el cuervo y el lobo.
Para bien negociar, favor procura:
Con él tu causa casi está segura.
Fáb. XXXIV. El asno y el lobo.
Uno que haziendo os mal ha envejecido,
Si hazeros bien ofrece, no es creido.
Fáb. XXXV. El raton de ciudad y el del campo.
Ten por mejor con quietud pobreza,
Que no desasosiegos con riqueza.
Fáb. XXXVI. La raposa y el vendimiador.
Si con las obras el traydor te vende,
En vano con palabras te defiende.
Fáb. XXXVII. La vieja, las moças y el gallo.
Huir de trabajar, es claro engaño,
Y de poco venir á grande daño.
Fáb. XXXIX. El asno y las ranas.
Quando un poco de mal te quita el tino.
Mira el que tienen otros de contino.
Fáb. XL. El pastor y el lobo.
Al que en mentir por su plazer se emplea.
Quando dize verdad, no hay quien le crea.
Fáb. XLII. El labrador y la encina.
Si favoreces al ruin, haz cuenta
Que en pago has de tener dolor y afrenta.
Fáb. XLIII. El leon enamorado.
Los casamientos hechos por amores
Muchas vezes son causa de dolores.
Fáb. XLIV. La raposa y el espino.
Acudir por socorro es grande engaño
A quien vive de hazer á todos daño.
Fáb. XLVIII. El Astrólogo.
¿Qué certidumbre puede dar del cielo
El que á sus pies aun ver no puede el suelo?
Fáb. L. El leon enfermo, el lobo y la raposa.
Algunas vezes urde cosa el malo
Que viene á ser de su castigo el palo.
Fáb. LII. La raposa y la gata.
Un arte vale más aventajada
Que muchas si aprovechan poco ó nada.
Fáb. LIV. Los ratones y el cuervo.
Algunos, por inútiles contiendas,
Pierden la posesion de sus haziendas.

[216] Es la fábula XLI de Mey y termina con estos versos:

Harta ceguera tiene la cuytada


Que tuvo hazienda y no ve suyo nada.

[217] Fábula XXIII:

Si no he de aprovecharme del dinero,


Una piedra enterrada tanto quiero.
[218] Fábula XXVI de Mey. Corresponde á la XVII del
«Isopo de la traslacion nueva de Remigio», en la del
infante D. Enrique.

[219] Calila é Dymna, p. 33 en la edición de Gayangos


(Escritores en prosa anteriores al siglo XV).
[220] Así en Firenzuola: «il buon uomo, o pur come dicemmo, lo
sciocco». En Mey: «el hombre bueno, o si se sufre llamarle
bovo».
También pudo consultar La moral filosophia del Doni (Venecia,
1552), que es una refundición del libro de Firenzuola.
[221] Del falso e del torpe.
Dixo Calila: «Dos homes eran en una compaña, et el uno dellos
era torpe, e el otro falso, e ficieron aparceria en una mercaderia;
et yendo por un camino fallaron una bolsa en que habia mil
maravedis, e tomáronla, e ovieron por bien de le tornar a la
cibdat. Et quando fueron cerca de la cibdat, dixo el torpe al falso:
«Toma la metad destos dineros, et tornaré yo la otra meatad». Et
dixo el falso, pensándose levar todos los maravedis: «Non
fagamos asi, que metiendo los amigos sus faziendas en manos
de otri fazen más durar el amor entre ellos; mas tome cada uno
de nos para gastar, e soterremos los otros que fincaren en algun
logar apartado, et quando hobiéremos menester dellos, tomarlos
hemos». E acordóse el torpe en aquello, et soterraron los
maravedis so un arbol muy grande, e fuéronse ende, e despues
tornó el falso por los maravedis, e levólos; e cuando fue dias,
dixo el falso al torpe: «Vayamos por nuestros maravedis, que yo
he menester que despienda». E fuéronse para el logar que los
posieron, e cavaron e non fallaron cosa; e comenzóse a mesar el
falso et a ferir en sus pechos, et comenzó a dezir: «Non se fie
home en ninguno desde aqui, nin se crea por él». E dixo al torpe:
«Tú tornaste aqui et tomaste los maravedis». Et comenzó el torpe
a jurar e confonderse que lo non feciera, e el falso diciendo: «Non
sopo ninguno de los maravedis salvo yo et tú, e tú los tomaste».
E sobre esto fuéronse pora la cibdat, e pora el alcall, e el falso
querellóse al alcall cómo el torpe le habia tomado los maravedis,
e dixo el alcall: «¿Tú has testigos?» Dixo el torpe: «Sí, que fio por
Dios que el arbol me será testigo, e me afirmará en lo que yo
digo». E sobre esto mandó el alcall que se diesen fiadores, et
díxoles: «Venid vos para mí e iremos al arbol que decides». E
fuese el falso a su padre et fízogelo saber e contóle toda su
fazienda, et díxole: «Yo no dixe al alcall esto que te he contado,
salvo por una cosa que pensé; si tú acordares comigo, habremos
ganado el haber». Dixo el padre: «¿Qué es?» Dixo el falso: «Yo
busqué el mas hueco arbol que pude fallar, e quiero que te vayas
esta noche allá e que te metas dentro aquel logar y donde
puedas caber, et cuando el alcall fuere ende, e preguntare quién
tomó los maravedis, responde tú dentro que el torpe los tomó...
«Et non quedó de le rogar que lo fiziese fasta que gelo otorgó. Et
fuese a meter en el arbol, e otro dia de mañana llegó el alcall con
ellos al arbol, e preguntóle por los maravedis, e respondió el
padre del falso que estaba metido en el arbol, et dixo: «El torpe
tomó los maravedis». E maravillóse de aquello el alcall e cuantos
ende estaban, e andudo alrededor del arbol, e non vió cosa en
que dudase, e mandó meter y mucha leña e ponerla en derredor
del arbol, e fizo poner fuego. E cuando llegó el fumo al viejo, e le
dió la calor, escomenzó de dar muy grandes voces e demandar
acorro; et entonces sacáronle de dentro del arbol medio muerto,
e el alcall fizo su pesquisa e sopo toda la verdat, e mandó
justiciar al padre e al fijo e tornar los maravedis al torpe; e así el
falso perdió todos los maravedis, e su padre fué justiciado por
cabsa de la mala cobdicia que ovo et por la arteria que fizo».
(Calila e Dymna, ed. Gayangos, pp. 32-33).
Cf. Johannis de Capua Directorium vitae humanae... ed. de
Derenbourg, París, 1887, pp. 90-92.
Agnolo Firenzuola, La prima veste de' discorsi degli animali, ed.
Camerini, pp. 241-242.
[222] The Facetiae or jocose tales of Poggio..., París, 1879, I,
187.
[223] Diporto de' Vindanti, nel quale si leggono Facetie, Motti e
Burle, raccolte da diversi e gravi autori. Pavia, Bartoli, 1589, 8.º.
Ésta es la más antigua de las ediciones mencionadas por Gamba
en su bibliografía novelística.
[224] Cento Novelle de' più nobili scrittori della lingua volgare
scelte da Francesco Sansovino... Venezia, appresso Francesco
Sansovino, 1561.
Hállase también en las ediciones de 1562, 1563, 1566, 1571,
1598, 1603 y 1610.
[225] Ancona, Le fonti del Novellino, p. 319.
[226] En Sansovino no es el Gobernador sino el Arzobispo.
[227] «En un gran banquete, que hizo un señor á muchos
caballeros, despues de haber servido muy diversos manjares,
sacaron barbos enteros, y pusieron á un capitan de una Nao, que
estaba al cabo de la mesa, un pez muy pequeño, y mientras que
los otros comian de los grandes, tomó él el pececillo y púsole á la
oreja. El señor que hacia el banquete, paróse mientes, y
preguntóle la causa. Respondió: «Señor, mi padre tenia el mismo
oficio que yo tengo, y por su desdicha y mía anegóse en el mar y
no sabemos adónde, y desde entonces á todos los peces que
veo, pregunto si saben de él. Díceme éste, que era chiquito, que
no se acuerda».
(Floresta Española... Sexta parte, Capítulo VIII, n. XII de «dichos
de mesa», pág. 254 de la ed. de 1790.)
Pequeñas variantes tiene el cuento de Garibay:
«Sirvieron a la mesa del Señor unos peces pequeños y al Señor
grandes. Estaba a la mesa un fraile, y no hacia más que tomar de
los peces chicos y ponellos al oido y echallos debajo de la mesa.
El Señor miró en ello, y díjole: «Padre ¿huelen mal esos peces?»
Respondió: «No, señor, sino que pasando mi padre un rio, se
ahogó, y preguntábales si se habian hallado a la muerte de mi
padre. Ellos me respondieron que eran pequeños, que no, que
esos de V. S.ª que eran mayores, podría ser que se hubiesen
hallado». Entendido por el Señor, dióle de los peces grandes,
diciéndole: «Tome, y pregúntesle la muerte de su padre» (Sales
Españolas, de Paz Melia, II, p. 52).
[228] Fáb. XVI.

De ser cantor no tenga presuncion


El que no sabe más de una cancion.

[229] Fáb. XIII. Es cuento de mentiras de cazadores.

No disimules con quien mucho miente,


Porque delante de otros no te afrente.

[230] Fáb. XXXII.

Hablale de ganancia al codicioso,


Si estás de hazerle burla deseoso.

[231] Fáb. XLVI.

Si hizieres al ingrato algun servicio,


Publicará que le hazes maleficio.

[232] Fáb. LI.

Harás que tu muger de ti se ria,


Si la dexas salir con su porfia.

[233] Fáb. LVII. El Maestro de escuela

Encomiendate a Christo y a Maria,


A tu Angel y a tu Santo cada dia.

[234] Fáb. XXXIV.

No cases con mochacha si eres viejo;


Pesarte ha si no tomas mi consejo.

[235] Il Novellino di Masuccio Salernitano, ed. de Settembrini,


Nápoles, 1874. Págs. 519 y ss.
[236] Cercando ultimamente tra virtuosi gesti, de prossimo me è
già stato da uno nobile oltramontano per autentico recontato, che
è ben tempo passato che in Toleto cità notevole de Castiglia fu un
cavaliero d' antiqua e generosa famiglia chiamato misser Piero
Lopez d' Aiala, il quale avendo un suo unico figliolo molto
leggiadro e bello e de gran core, Aries nominato...
En el exordio dice también que su novela ha sido «de virtuosi
oltramontani gesti fabbricata».
[237] Le Comte Lucanor... París, 1854, pág. 149.
[238] Dialogos de apacible entretenimiento, que contiene vnas
Carnestolendas de Castilla, Diuidido en las tres noches del
Domingo, Lunes, y Martes de Antruexo. Compvesto por Gaspar
Lucas Hidalgo. Procvra el avtor en este libro entretener al Letor
con varias curiosidades de gusto, materia permitida Para recrear
penosos cuydados a todo genero de gentes. Barcelona, en casa
de Sebastian Cormellas. Año 1605.
8.º, 3 hs. prls. y 108 folios.
Según el Catálogo de Salvá (n. 1.847), hay ejemplares del mismo
año y del mismo impresor, con diverso número de hojas, pero
con igual contenido.
Una y otra deben de ser copias de una de Valladolid (¿1603?),
según puede conjeturarse por la aprobación de Gracián Dantisco
y el privilegio, que están fechados en aquella ciudad y en aquel
año.
—Diálogos... Con licencia. En Logroño, en casa de Matias Mares,
año de 1606.
8.º, 3 hs. prls. y 108 folios. (N.º 2 520 de Gallardo.)
—Barcelona, 1606. Citada por Nicolás Antonio.
—Barcelona, en casa de Hieronimo Margarit, en la calle de
Pedrixol, en frente Nuestra Señora del Pino. Año 1609.
8.º, 5 hs. prls., 120 pp. dobles y una al fin, en que se repiten las
señas de la impresión.
—Brusselas, por Roger Velpius, impressor jurado, año 1610.
8.º, 2 hs. prls., 135 folios y una hoja más sin foliar.
—Año 1618. En Madrid, por la viuda de Alonsso Martin. A costa
de Domingo Gonçalez, mercader de libros.
8.º, 4 hs. prls. sin foliar y 112 pp. dobles.
—Con menos seguridad encuentro citadas las ediciones de
Amberes, 1616, y Bruselas, 1618, que nunca he visto.
D. Adolfo de Castro reimprimió estos Diálogos en el tomo de
Curiosidades Bibliográficas de la Biblioteca de Rivadeneyra, y
también se han reproducido (suprimiendo el capítulo de las
bubas) en un tomo de la Biblioteca Clásica Española de la Casa
Cortezo, Barcelona, 1884, que lleva el título de Extravagantes.
Opúsculos amenos y curiosos de ilustres autores.
[239] Tiene este vejamen una curiosa alusión al Brocense: «el
maestro Sánchez, el retórico, el griego, el hebreo, el músico, el
médico y el filósofo, el jurista y el humanista tiene una cabeza,
que en todas estas ciencias es como Ginebra, en la diversidad de
profesiones». «Este maestro (añade, á modo de glosa, Gaspar
Lucas Hidalgo), aunque sabía mucho, tenía peregrinas opiniones
en todas estas facultades».
La alusión á Ginebra no haría mucha gracia al Brocense, que ya
en 1584 había tenido contestaciones con el Santo Oficio y que
volvió á tenerlas en aquel mismo año de 1600, postrero de su
vida.
[240] Actus gallicus ad magistrum Franciscum Sanctium, «en el
grado de Aguayo», per fratrem Ildephonsum de Mendoza
Augustinum.
Está en el famoso códice AA-141-4 de la Biblioteca Colombina,
que dio ocasión á D. Aureliano Fernández Guerra para escribir
tanto y tan ingeniosamente en el apéndice al primer tomo de la
bibliografía de Gallardo.
El Maestro Francisco Sánchez, de quien se trata, es persona
distinta del Brocense, que asistió á su grado juntamente con Fr.
Luis de León y otros maestros famosos.
[241] Über eine spanische Handschrift der Wiener Hofbibliothek
(1867), pág. 89. Mussafia formó un pequeño glosario para
inteligencia de esta composición.
También la reproduce el Sr. Paz y Melia en sus Sales Españolas
(I, p. 249): «Carta increpando de corto en lenguaje castellano, ó
la carta del monstruo satírico de la lengua española».
[242] Hállase en el códice antes citado de la Biblioteca
Colombina.
[243] El Sr. Paz y Melia (Sales Españolas, I, pág. VIII) cita un
inventario manuscrito de los cuadros propios de D. Luis Méndez
de Haro y Guzmán que pasaron á la Casa de Alba, en el cual se
lee lo siguiente:
«Un cuadro de un Duque de Alba enfermo, echando mano á la
espada, y un médico con la jeringa en la mano y en la otra el
bonete encarnado de doctor. Es de mano de Diego Velázquez.
De dos varas y cuarta de alto y vara y cuarta de ancho».
Todavía se menciona este cuadro en otro inventario de 1755,
pero luego se pierde toda noticia de él.
[244] Parte primera del libro intitulado Noches de Inuierno.
Compuesto por Antonio de Eslaua, natural de la villa de
Sangüessa. Dedicado a don Miguel de Nauarra y Mauleon,
Marques de Cortes, y señor de Rada y Treybuenos. En
Pamplona. Impresso: por Carlos de Labayen, 1609.
8.º, 12 hs. prls., 239 pp. dobles y una en blanco.
Aprobaciones de Fr. Gil Cordon y el Licdō. Juan de Mendi
(Pamplona, 27 de noviembre de 1608 y 26 de junio de 1609).—
Dedicatoria al Marqués de Cortes:... «He procurado siempre de
hablar con los muertos, leyendo diversos libros llenos de historias
Antiguas, pues ellos son testigos de los tiempos, y imagenes de
la vida; y de los mas dellos y de la oficina de mi corto
entendimiento, he sacado con mi poco caudal, estos toscos y mal
limados Dialogos: y viendo tambien quan estragado está el gusto
de nuestra naturaleza, los he guisado con un saynete de
deleytacion, para que despierte el apetito, con título de Noches
de Invierno: llevando por blanco de aliviar la pesadumbre dellas;
alagando los oydos al Lector, con algunas preguntas de la
Philosophia natural y moral, insertas en apacibles historias».
Prólogo al discreto lector: «Advierte... una cosa que estás
obligado a disimular conmigo, mas que con ningun Autor, las
faltas, los yerros, el poco ornato y retorica de estos mis Dialogos,
atento que mi voluntad con el exercicio della, se ha opuesto a
entretenerte y aliviarte de la gran pesadumbre de las noches del
Invierno».
Soneto del autor á su libro. Véanse los tercetos:

Acogete a la casa del discreto,


Del curioso, del sabio, del prudente
Que tienen su morada en la alta cumbre.
Que ellos te ternan con gran respeto,
Vestiran tu pobreza ricamente,
Y asiento te daran junto a la lumbre.

Soneto de D. Francisco de Paz Balboa, en alabanza del autor.—


De un amigo al autor (redondillas).—Sonetos laudatorios del
Licenciado Morel y Vidaurreta, relator del Consejo Real de
Navarra; de Hernando Manojo; de Miguel de Hureta, criado del
Condestable de Navarra y Duque de Alba; de Fr. Tomás de Avila
y Paz, de la Orden de Santo Domingo; de un fraile francisco (que
pone el nombre de Eslava en todos los versos); de D. Juan de
Eslava, racionero de la catedral de Valladolid y hermano del autor
(dos sonetos).—Texto.—Tabla de capítulos.—Tabla de cosas
notables.—Nota final.
—Parte primera del libro intitvlado Noches de Inuierno.
Compuesto... (ut supra). Dirigido a don Ioan Iorge Fernandez de
Heredia Conde de Fuentes, señor de la Casa y varonia de Mora,
Comendador de Villafranca, Gouernador de la orden de
Calatraua... Año 1609. En casa Hieronymo Margarit. A costa de
Miguel Menescal, Mercader de Libros.
8.º, 236 pp. dobles.
Aprobación de Fr. Juan Vicente (Santa Catalina, 16 de setiembre
de 1609).—Licencia del Ordinario (18 de setiembre). Siguen los
preliminares de la primera edición, aunque no completos.
—Parte primera... (ut supra). Dedicado a D. Miguel de Nauarra y
Mauleon, Marquez (sic) de Cortes... En Brvsellas. Por Roger
Velpius y Huberto Antonio, Impressores de sus Altezas, à l'Aguila
de oro, cerca de Palacio. 1610. Con licencia.
12.º, 258 hs. Reproduce todos los preliminares de la de
Pamplona y añade un Privilegio por seis años á favor de Roger
Velpius y Huberto Antonio (Bruselas, 7 de mayo de 1610).
Existe una traducción alemana de las Noches de Invierno
(Winternächte... Aus dem Spanischen in die Teutsche Sprache...)
por Mateo Drummer (Viena, 1649; Nüremberg, 1666). Vid.
Schneider, Spaniens Anteil an der Deutschen Litteratur, p. 256.
Tabla de los capítulos en el libro de Eslava:
«Capitulo Primero. Do se cuenta la perdida
del Navio de Albanio.
Cap. 2. Do se cuenta cómo fue
descubierta la fuente del Desengaño.
Cap. 3. Do se cuenta el incendio del
Galeon de Pompeo Colona.
Cap. 4. Do se cuenta la sobervia del Rey
Niciforo, y incendio de sus Naves, y la Arte
Magica del Rey Dardano.
Cap 5. Do se cuenta la iusticia de Celin
Sultan gran Turco, y la vengaza de Zayda.
Cap. 6. Do se cuenta quien fue el esclavo
Bernart.
Cap. 7. Do se cuenta los trabajos y
cautiverio del Rey Clodomiro y la Pastoral
de Arcadia.
Cap. 8. Do se cuenta el nacimiento de
Roldan y sus niñerias.
Cap. 9. Do defiende Camila el genero
Femenino.
Cap. 10. Do se cuenta el nacimiento de
Carlo Magno Rey de Francia.
Cap. 11. Do se cuenta el nacimiento de la
Reyna Telus de Tartaria».
[245] Fue publicada por el misionero inglés Henry Callaway, con
otros cuentos de la misma procedencia, en la colonia de Natal,
en 1868. Véase H. Husson, La Chaîne traditionelle. Contes et
légendes au point de vue mythique (París, 1874), p. 115. Este
libro, aunque excesivamente sistemático, sobre todo en la
aplicación del mito solar, contiene, á diferencia de tantos otros,
muchas ideas y noticias en pocas palabras. No es indiferente
para el estudio de los romances castellanos, verbigracia: el de
Delgadina (mito védico de Prajapati—leyenda hagiográfica de
Santa Dina ó Dympna, hija del rey de Irlanda,—novela de
Doralice y Teobaldo, príncipe de Salerno, en Straparola), ó el de
la Infantina, emparentado con el cuento indio de Suria-Bai (pp. 57
y 111).
[246] Histoire poétique de Charlemagne, p. 432.
[247] Les Epopées Françaises, t. III, p. 11.
[248] Ueber die altfranzösischen Heldengedichte aus dem
Karolingischen Sagenkreise, Viena, 1883.
[249] Li Romans de Berte aus grans piés, précedé d'une
Dissertation sur les Romans des douze pairs, par M. Paulin Paris,
de la Bibliothèque du Roi. París, Techener, 1832.
Hay otra edición más correcta, publicada por Augusto Scheler,
conforme al manuscrito de la Biblioteca del Arsenal de París: Li
Roumans de Berte aus grans piés, par Adènes le Roi (Bruselas,
1874).
Mussafia publicó en la Romania (julio de 1874 y enero de 1875)
el texto del poema franco-italiano, anterior quizá en ochenta años
al de Adenet.
[250] Tanto en el poema de Adenès, como en el texto franco-
itálico, lo que distingue á Berta es únicamente el tener los pies

You might also like