X Window System From Scratch

download X Window System From Scratch

of 798

Transcript of X Window System From Scratch

  • 8/2/2019 X Window System From Scratch

    1/796

  • 8/2/2019 X Window System From Scratch

    2/796

    P R O G R A M M I N G S E R I E S

    scratchfromJ E S S E L I B E R T Y S

    from

    X Window

    Programming

    scratch

    A Division of Macmillan USA

    201 West 103rd Street,

    Indianapolis, Indiana 46290

    J. Robert Brown

  • 8/2/2019 X Window System From Scratch

    3/796

    X Window Programming from Scratch

    Copyright 2000 by Que Corporation

    All rights reserved. No part of this book shall be reproduced, stored in a

    retrieval system, or transmitted by any means, electronic, mechanical, photo-copying, recording, or otherwise, without written permission from the pub-lisher. No patent liability is assumed with respect to the use of the informationcontained herein. Although every precaution has been taken in the preparationof this book, the publisher and author assume no responsibility for errors oromissions. Neither is any liability assumed for damages resulting from the useof the information contained herein.

    International Standard Book Number: 0-7897-2372-7

    Library of Congress Catalog Card Number: 00-100691

    Printed in the United States of America

    First Printing: August 2000

    02 01 00 4 3 2 1

    TrademarksAll terms mentioned in this book that are known to be trademarks or servicemarks have been appropriately capitalized. Que Corporation cannot attest tothe accuracy of this information. Use of a term in this book should not beregarded as affecting the validity of any trademark or service mark.

    Warning and DisclaimerEvery effort has been made to make this book as complete and as accurate aspossible, but no warranty or fitness is implied. The information provided is onan as is basis. The authors and the publisher shall have neither liability nor

    responsibility to any person or entity with respect to any loss or damages aris-ing from the information contained in this book or from the use of the CD orprograms accompanying it.

    Associate PublisherTracy Dunkelberger

    Acquisitions EditorKatie Purdum

    Development EditorHugh Vandivier

    Managing EditorThomas F. Hayes

    Senior EditorSusan Ross Moore

    Copy EditorCynthia Fields

    ProofreadersHarvey Stanbrough

    Megan WadeTechnical Editor

    Ed Petron

    Team CoordinatorVicki Harding

    Media DeveloperMichael Hunter

    Interior DesignSandra Schroeder

    Cover DesignersMaureen McCartyAnne Jones

    Copy WriterEric Borgert

    ProductionDarin CroneSteve Geiselman

  • 8/2/2019 X Window System From Scratch

    4/796

    Contents at a GlanceIntroduction xvi

    Section One: Starting Points 1

    Part I: Absolute Zero 3

    Chapter 1 UNIX for Developers 5

    2 Programming Constructs 49

    3 A Word on C 83

    Part II: The Pieces of X 111

    Chapter 4 Windowing Concepts 113

    5 Widget Sets 125

    6 Components of an X Window Application 143

    7 Xlib Graphic Primitives 179

    Part III: Back to School 195

    Chapter 8 Vector Versus Raster Graphics 197

    9 Object Bounds Checking 203

    10 Trigonometric and Geometric Functions 211

    11 Graphic Transformations 22512 Coordinate Systems 253

    Section Two: Graphics Editor Application 257

    Part IV: Laying Out the Parts 259

    Chapter 13 Application Structure 261

    14 Program Flow 299

    15 Common Object Definition 305

    16 Object Manipulation 31917 Utilities and Tools 343

    18 File Formats 355

    19 Save and Restore 363

  • 8/2/2019 X Window System From Scratch

    5/796

    Part V: Adding Objects to the Editor 377

    Chapter 20 Latex Line Object 379

    21 Pencil Line Object 405

    22 Object Templates 41123 Arc Object 421

    24 VectorText Object 437

    Part VI: Adding a Print Driver 477

    Chapter 25 Introduction to PostScript 479

    26 Color Versus Black and White 491

    27 Working with XImages and Colormaps 495

    Part VII: Whats Next? 507Chapter 28 Extending the Graphics Editor 509

    29 Adding Context-Sensitive Help 513

    Part VIII: Appendixes 521

    A Command Shells and Scripting 523

    B Application Layout Code Listing 539

    C Additional Vector Font Sets and vector_chars.h 557

    Index 741

  • 8/2/2019 X Window System From Scratch

    6/796

    Table of ContentsIntroduction xvi

    Section One: Starting Points 1

    Part I: Absolute Zero 3

    Chapter 1 UNIX for Developers 5

    The man Command ................................................................................................6

    Organization and Navigation ................................................................................8

    Directories ......................................................................................................10

    Permissions ......................................................................................................15

    chmod ................................................................................................................17

    The cd Command ..........................................................................................18

    The C Compiler ..................................................................................................18

    Object Files ..........................................................................................................19

    Source Files ..........................................................................................................21

    The vi Editor ......................................................................................................22

    The make Utility ..................................................................................................24

    The cc Command ..........................................................................................25

    Makefile ..........................................................................................................31

    System Tools and Useful Commands ..................................................................44

    grep, Pipes, Redirection, and more ................................................................44

    The find Command ......................................................................................46

    Next Steps ............................................................................................................47

    Chapter 2 Programming Constructs 49

    Decisions ..............................................................................................................50

    The if Statement............................................................................................51

    The else Statement ........................................................................................52

    Types of Conditions ........................................................................................52

    The if else Statement ..................................................................................57

    The case Statement ........................................................................................58

    Loops ....................................................................................................................60

    The for Loop..................................................................................................60

    The while Loop ..............................................................................................62The do while Loop........................................................................................63

    Functions ..............................................................................................................64

    Declarations ....................................................................................................64

    Return Type ....................................................................................................66

    Function Name................................................................................................66

  • 8/2/2019 X Window System From Scratch

    7/796

    Parameters ......................................................................................................67

    Definition ........................................................................................................68

    The return Statement ....................................................................................68

    Data ......................................................................................................................69

    Data Types ......................................................................................................70Next Steps ............................................................................................................81

    Chapter 3 A Word on C 83

    Hello World..........................................................................................................84

    Comment Tokens ............................................................................................84

    The Function main ..........................................................................................85

    Code Bodies ....................................................................................................86

    Variable Scope ................................................................................................88

    Built-In Functions ..........................................................................................90

    Memory Management ..................................................................................100

    Dynamic Memory Allocation........................................................................105Memory Leaks ..............................................................................................107

    Definitions and Macros ................................................................................107

    Conclusion ..........................................................................................................109

    Next Steps ..........................................................................................................109

    Part II: The Pieces of X 111

    Chapter 4 Windowing Concepts 113

    Origins of the X Window System......................................................................113

    The Pieces of X ..................................................................................................114

    Client/Server Model......................................................................................114

    Window Hierarchy........................................................................................121

    Next Steps ..........................................................................................................124

    Chapter 5 Widget Sets 125

    The Power and Convenience of Using Widget Sets ........................................125

    The Athena Widget Set ....................................................................................129

    The CoreWidget ..........................................................................................131

    Widgets That Manage Other Widgets ........................................................135

    The Motif Widgets ......................................................................................140

    Next Steps ..........................................................................................................142

    Chapter 6 Components of an X Window Application 143Connecting to the X Server ..............................................................................144

    Employing Widget Resources Using Variable Argument Lists ..................144

    Creating the Application Interface ....................................................................151

    Creating Buttons ..........................................................................................159

    Creating Pixmap Icons ..................................................................................162

    Assigning Actions ..........................................................................................169

    vi X Window Programming from Scratch

  • 8/2/2019 X Window System From Scratch

    8/796

    Managing Windows............................................................................................175

    Processing Events ..............................................................................................176

    Summary ............................................................................................................176

    Next Steps ..........................................................................................................177

    Chapter 7 Xlib Graphic Primitives 179

    The Graphics Context........................................................................................179

    The GC Function............................................................................................182

    GCForeground and GCBackground ................................................................184

    GCLineWidth ..................................................................................................187

    GCTile ............................................................................................................188

    Graphic Primitive Functions..............................................................................189

    XDrawPoint ....................................................................................................190

    XDrawLine ......................................................................................................191

    XDrawRectangle ............................................................................................191

    XDrawArc ........................................................................................................192Filled Graphics ..............................................................................................193

    Next Steps ..........................................................................................................194

    Part III: Back To School 195

    Chapter 8 Vector Versus Raster Graphics 197

    Vector Graphics ..................................................................................................199

    Raster Graphics ..................................................................................................199

    Next Steps ..........................................................................................................201

    Chapter 9 Object Bounds Checking 203

    Point-ArrayBased Object Bounds ....................................................................204Arc Object Bounds ............................................................................................206

    Employing Object Bounds ................................................................................207

    Next Steps ..........................................................................................................209

    Chapter 10 Trigonometric and Geometric Functions 211

    Calculating Point and Line Intersections..........................................................211

    Calculating Slope................................................................................................216

    Calculating Point and Arc Intersections............................................................218

    Next Steps ..........................................................................................................224

    Chapter 11 Graphic Transformations 225

    Moving ................................................................................................................225

    Moving a Line ..............................................................................................226

    Moving an Arc ..............................................................................................231

    Scaling ................................................................................................................232

    Scaling a Line ................................................................................................234

    Scaling an Arc ................................................................................................243

    vContents

  • 8/2/2019 X Window System From Scratch

    9/796

    Rotating ..............................................................................................................247

    Rotating a Line..............................................................................................248

    Rotating an Arc..............................................................................................251

    Next Steps ..........................................................................................................252

    Chapter 12 Coordinate Systems 253

    Rectangular Coordinates ....................................................................................254

    Polar Coordinate System ..................................................................................254

    Next Steps ..........................................................................................................256

    Section Two: Graphics Editor Application 257

    Part IV: Laying Out the Parts 259

    Chapter 13 Application Structure 261

    Project Structure ................................................................................................262Laying Out the User Interface......................................................................265

    Parsing the Command Line ..............................................................................289

    The getopt Function ........................................................................................290

    The XtVaGetApplicationResources Function ................................................292

    Setting Up a Canvas ..........................................................................................296

    Building the Project............................................................................................297

    Next Steps ..........................................................................................................298

    Chapter 14 Program Flow 299

    Processing Events ..............................................................................................300

    X Event Hooks ..................................................................................................302

    Widget Callbacks ..........................................................................................302

    Event Handlers..............................................................................................302

    Widget Translation Tables ............................................................................303

    Next Steps ..........................................................................................................304

    Chapter 15 Common Object Definition 305

    Line Object Data Structure................................................................................305

    Text Object Data Structure ................................................................................307

    Understanding Vector Fonts ........................................................................309

    The GXText Data Structure................................................................................314

    Arc Object Data Structure ................................................................................314

    Common Object Data Structure........................................................................315Next Steps ..........................................................................................................318

    Chapter 16 Object Manipulation 319

    Copying an Object..............................................................................................319

    Deleting an Object ............................................................................................321

    viii X Window Programming from Scratch

  • 8/2/2019 X Window System From Scratch

    10/796

    Refreshing Objects ............................................................................................325

    Parsing for an Object..........................................................................................326

    Managing Object Handles ................................................................................327

    Managing the Status of an Object ....................................................................331

    Processing User Navigation of Objects ............................................................334Next Steps ..........................................................................................................341

    Chapter 17 Utilities and Tools 343

    Common Object Creation ................................................................................343

    Linked List Management..............................................................................346

    Creating a Graphics Context ............................................................................347

    Graphics Context Tiling ..............................................................................348

    Using the Cursor as State Indicator ..................................................................349

    Next Steps ..........................................................................................................354

    Chapter 18 File Formats 355

    Understanding Files ..........................................................................................357

    Binary File Formatting ......................................................................................357

    ASCII File Formatting ......................................................................................359

    Tagged File Formats......................................................................................359

    Position-Specific File Formats......................................................................360

    Magic Numbers ..................................................................................................361

    Next Steps ..........................................................................................................361

    Chapter 19 Save and Restore 363

    File Format Strategy ..........................................................................................363

    Save and Restore Program Hooks ....................................................................366

    Common-Object Save and Restore ..................................................................367Object-Specific Save and Restore ......................................................................373

    Next Steps ..........................................................................................................376

    Part V: Adding Objects to the Editor 277

    Chapter 20 Latex Line Object 379

    Creating a Latex Line Object ..........................................................................380

    Drawing and Erasing a Line Object..................................................................388

    Finding a Line Object ........................................................................................390

    Selecting and Deselecting a Line Object ..........................................................392

    Moving a Line Object ........................................................................................395Scaling a Line Object ........................................................................................398

    Copying a Line Object ......................................................................................400

    Saving and Restoring a Line Object..................................................................401

    Next Steps ..........................................................................................................403

    ixContents

  • 8/2/2019 X Window System From Scratch

    11/796

    Chapter 21 Pencil Line Object 405

    Creating a Pencil Object ..................................................................................406

    Pencil Object Management ..............................................................................410

    Next Steps ..........................................................................................................410

    Chapter 22 Object Templates 411

    The Box Object ..................................................................................................411

    TheArrow Object ..............................................................................................415

    Next Steps ..........................................................................................................419

    Chapter 23 Arc Object 421

    Creating anArc Object ......................................................................................422

    Drawing and Erasing anArc Object..................................................................427

    Finding anArc Object........................................................................................428

    Selecting and Deselecting anArc Object ..........................................................428

    Moving anArc Object........................................................................................431Scaling anArc Object ........................................................................................432

    Copying anArc Object ......................................................................................434

    Saving and Restoring anArc Object..................................................................435

    Next Steps ..........................................................................................................436

    Chapter 24 Vector Text Object 437

    Creating a Text Object ......................................................................................438

    Drawing and Erasing a Text Object..................................................................461

    Finding a Text Object ........................................................................................463

    Selecting and Deselecting a Text Object ..........................................................464

    Moving a Text Object ........................................................................................467

    Scaling a Text Object ........................................................................................469

    Copying a Text Object ......................................................................................472

    Saving and Restoring a Text Object..................................................................473

    Next Steps ..........................................................................................................475

    Part VI: Adding a Print Driver 477

    Chapter 25 Introduction to PostScript 479

    PostScript............................................................................................................479

    Learning PostScript............................................................................................480

    Stacks ............................................................................................................481

    PostScript Commands........................................................................................482Comments......................................................................................................482

    PostScript Programming....................................................................................482

    Viewing PostScript Files ....................................................................................488

    Comments Understood by Ghostscript ......................................................489

    Next Steps ..........................................................................................................490

    x X Window Programming from Scratch

  • 8/2/2019 X Window System From Scratch

    12/796

    Chapter 26 Color Versus Black and White 491

    Determining a Printers Capability ....................................................................491

    Defining Color Images for Black and White Printers......................................492

    Next Steps ..........................................................................................................494

    Chapter 27 Working with XImages and Colormaps 495

    Printing the Canvas ............................................................................................495

    Creating an XImage ..........................................................................................497

    Creating a PostScript Prolog ............................................................................499

    Parsing the X Colormap ....................................................................................500

    Writing the PostScript Page Definition File ....................................................502

    Directing the Output to a Printer or File ........................................................504

    Next Steps ..........................................................................................................506

    Part VII: Whats Next? 507

    Chapter 28 Extending the Graphics Editor 509

    Attributes ............................................................................................................509

    Color ..............................................................................................................509

    Line Attributes ..............................................................................................510

    Arc Angles......................................................................................................511

    Rotating Objects ................................................................................................511

    Next Steps ..........................................................................................................512

    Chapter 29 Adding Context-Sensitive Help 513

    Processing Help-Related Events........................................................................514

    Widget Paths ......................................................................................................516

    Relating Widgets to Text....................................................................................518

    Next Steps ..........................................................................................................519

    Part VIII: Appendixes 521

    Appendix A: Command Shells and Scripting 523

    UNIX Command Shells ....................................................................................523

    Command Shell Environment ......................................................................525

    Scripting with the Bourne Shell ........................................................................531

    Shell Variables................................................................................................532

    Writing a Script with Function Calls ..........................................................536

    Debugging Shell Scripts................................................................................538

    Appendix B: Application Layout Code Listing 539

    make.defines File Contents ........................................................................540

    GNUmakefile File Contents ..........................................................................542

    gxMain.c File Contents ................................................................................542

    xContents

  • 8/2/2019 X Window System From Scratch

    13/796

    gxGraphics.c File Contents ........................................................................544

    gxGx.c File Contents ....................................................................................547

    gxArc.c File Contents ..................................................................................549

    gxLine.c File Contents ................................................................................549

    gxText.c File Contents ................................................................................550gxGraphics.h File Contents ........................................................................550

    gxIcons.h File Contents ..............................................................................551

    gxBitmaps.h File Contents ..........................................................................552

    gxProtos.h File Contents ............................................................................555

    Appendix C: Additional Vector Font Sets and vector_chars.h 557

    Triplex Bold Italic Vector Font Set....................................................................539

    The vector_chars.h Header File ....................................................................560

    Index 741

    xii X Window Programming from Scratch

  • 8/2/2019 X Window System From Scratch

    14/796

    About the AuthorJ. Robert Brown started his path to a career in software development by earning a

    college scholarship for Performing Arts in his homeland of central Ohio, where heheld the misguided belief that he could be a movie star.

    After years of either sleeping in his car or working three jobs concurrently to fundhis way through an Electrical Engineering program, he found himself in Europe inthe late 1980s working for the Department of Defense.

    As a field engineer maintaining the mobile computer systems responsible for collect-ing and processing intelligence data, he realized that the position required too muchmanual labor. In 1991, he made his way through a Computer Science program at theEuropean Division of the University of Maryland and although he didnt exactly fin-

    ish in the top 10% of his class, he believes strongly that he helped those who did toget there.

    John was invited to join Los Alamos National Laboratory as a Computer Scientist in1996 where he remained until only recently. He now works for GTE Data Sourcesnear Tampa, Florida.

  • 8/2/2019 X Window System From Scratch

    15/796

    DedicationThere are people who exist in the world who, once youve encountered them, change you for-

    ever. Through the strength of their character, depth of their spirit, or simply their presence inthe world, they leave a lasting impression. I fear that we have one fewer such individualtoday due to the loss of Shel Silverstein in May, 1999. I hope for everyone there is someonewho touches his or her life as Shels works have touched mine.

    Those without whom my life would mean less and this effort would not have been possible aremy dear mother, Cindy Baker; my brother and best friend, Scott Brown; the absolute love ofmy life, Mikeala Elise; and the person who gave her to me, Kinnina McCray.

    AcknowledgmentsX Window Programming from Scratch is the result of efforts by many people. I amfilled with awe and gratitude for the level of professionalism and quality the staff atQue publishing brought to this effort: specifically, Hugh Red Vandivier, Susan Ineed this back by Monday Moore, Cynthia Did this change your meaning? Fields, andKatie Youd better meet the deadline Purdum. And although no one likes to be toldthey have made a mistake, technical editor Ed Um, you might want to check thisPetron was able to point out oversights in a way that never came close to woundingmy ego. With the help of these and many others behind the scenes, this text is muchbetter than I could ever have made it on my own.

    There are others who contributed indirectly to the project by offering their friend-ship, encouragement, and patience as I tried to keep my head above water: namely,Mike Koscielniak, Cindy Sievers, and Jennifer Brown.

  • 8/2/2019 X Window System From Scratch

    16/796

    Tell Us What You Think!As the reader of this book,you are our most important critic and commentator. We

    value your opinion and want to know what were doing right, what we could do bet-ter, what areas youd like to see us publish in, and any other words of wisdom yourewilling to pass our way.

    As an Associate Publisher for Que, I welcome your comments. You can fax, email, orwrite me directly to let me know what you did or didnt like about this book[md]aswell as what we can do to make our books stronger.

    Please note that I cannot help you with technical problems related to the topic of this book,and that due to the high volume of mail I receive, I might not be able to reply to every mes-sage.

    When you write, please be sure to include this books title and author as well as yourname and phone or fax number. I will carefully review your comments and sharethem with the author and editors who worked on the book.

    Fax: 317.581.4666

    Email: [email protected]

    Mail: Tracy DunkelbergerAssociate PublisherQue Corporation201 West 103rd StreetIndianapolis, IN 46290 USA

  • 8/2/2019 X Window System From Scratch

    17/796

    IntroductionWelcome toX Window Programming from Scratch. Youll soon discover that there is

    much more to the text than the X Window System.

    Because the X Window System is an environment, it rests upon a programming lan-guage as well as on an operating system. Skills using these as well as elements ofobject-oriented methodology, trigonometric and geometric functions, and thePostScript language will be detailed in this text.

    Clearly, this text is not for the faint of heart.

    Instead of requiring you to purchase separate manuals for the X Window System,programming language, operating system, and so forth, the intent of this text is toprovide an erector set for computer programmers. Within the covers of this text are

    all the pieces necessary for accomplishing a Graphics Editor project.

    Section One, Starting Points, introduces the many pieces and encourages you toexamine the ones with which you are less familiar.

    Section Two, Graphics Editor Application, leads you through the assembly of thepieces into a functional and rewarding project. You will be challenged to further theproject and integrate the editor into other applications that you may be responsiblefor professionally.

    Beyond the TitleWindow-based user interfaces are the mainstream in professional level softwaredevelopment, and the X Window System holds its share of the community.

    The title of this book indicates the attention that this text will pay to learning theX Window System, but there is more in store than just learning X.

    The programming language selected for use in the text to employ the X WindowSystem is the C programming language. This decision was made because of the fre-quency in the professional community of using C when doing X Window Systemprogramming.

    Other languages can be used, but the approach is less direct and not suitable forintroducing the environment.

    The X Window System is non-proprietary. Not only can it be used with any operat-ing system, but the source code is freely available as well.

  • 8/2/2019 X Window System From Scratch

    18/796

    xIntroduction

    Therefore, the next decision to make was what operating system to use. The decisionwas obvious: The targeted operating system is Linux, although the project has beentested on several operating systems.

    According to the January 2000 issue ofComputerWorld, of all PC operating systemsin use, Linux holds the lead with 38% of the market and growing. A close second isWindows NT with 25% of the market.

    Honing skills in the Linux operating system is imperative for continued success inthe software development profession.

    Software ChecklistThe required components for accomplishing the Graphics Editor project in this textinclude

    Linux Operating System

    C Compiler

    X Window System

    Linux Operating SystemYou have the following choices when acquiring the Linux operating system:

    Downloading Linux from the Internet

    The Linux operating system is freely available for download from the Internet.

    However, it is not small, and if being pulled through a modem, the process may takeawhile. Further, if you download it, you have to work out the kinks of installing andsupporting it.

    Generally, when downloading Linux the process of installing it consists of trans-ferring the many files comprising the Linux installation components to floppy disk.Using a utility called rawwrite.exe provided with the download, you must create abootdisk and a rootdisk. The images from which you create these disks are selectedbased on the system you are installing Linux on and the features of the hardware youwant to be supported.

    For instance, unique images exist for a variety of network cards, modems, videocards, and so forth. Review the README file to understand the differences betweenavailable images before creating your startup disks.

    After an image is selected and the necessary disks are created, you can put the bootdisk into your floppy drive and reboot to begin the first of many installationattempts.

  • 8/2/2019 X Window System From Scratch

    19/796

    I believe strongly that the following generalization is true:

    No one ever installs Linux once.

    After several iterations and plenty of research, youll have a mostly functionaloperating system.

    Alternately, you can purchase a distribution of Linux.

    Linux Distributions

    Linux is a free operating system protected by the GNU General Public License.However, many vendors offer for sale a Linux distribution.

    A distribution that requires you to pay more than the cost of the media and postageis generally enhanced in one of many ways.

    Either by adding an installation program that automates the selection of the properLinux kernel, or by adding features to the environment such as utilities to configureyour windowing environment or system options, the vendors earn and justify thecosts of a distribution.

    The vendors advancing Linux include Red Hat, Slackware, Debian, SuSE, andothers.

    Having experience with all of them, I am unabashedly (and free of charge) going torecommend Red Hats Linux.

    The kernel (core of the operating system) packaged with Red Hats distribution is

    not different from the version you could download from the Internet or purchase inanother distribution; however, the ease with which the Red Hat distribution installs,configures, and updates is worth the investment.

    During the authoring of this text and the development of the Graphics Editor pro-ject, I used Red Hat 6.1. This version is packaged for very easy installation and con-figuration with the XFree86 X Window System and the GNU C Compiler.

    The default X Windowing environment provided by the installation of Red Hat 6.1is the GNOME desktop using the Enlightenment Window Manager. This isreflected in the screen shots used in the text.

    To learn more about vendors distributing Linux as well as the availability for down-loading the Linux operating system, issue the following command in the search fieldof your favorite Internet portal:

    url: Linux

    xviii X Window Programming from Scratch

  • 8/2/2019 X Window System From Scratch

    20/796

    Because of the popularity of the Linux operating system, you will have to siftthrough many hundreds of matches.

    Optionally, you can go directly to http://www.redhat.com and read about their latest

    release.

    C CompilerIf you opt not to use a version of Linux provided by a vendor, it can be necessary todownload and install a C language compiler separately.

    Packaged with most distributions of Linux (including Red Hat) is the GNU CCompiler.

    Because Red Hats distribution of Linux used during the writing of the text includesthe GNU C Compiler, this is the primary compiler used during the development of

    the project.The project has been tested using other compilers and the text addresses compilerdifferences for managing the project, so feel free to use any C compiler available toyou.

    If you are using a version of Linux (or UNIX) that does not include a C compiler, itwill be necessary to acquire one. The GNU C Compiler is available for free down-load from the Internet.

    Refer to the Free Software Foundation Web site (http://www.fsf.com or search forurl:gnu using your favorite browser) for information on sites providing the latest

    version of the compiler and its associated tools.

    X Window SystemThe X Window System is free for downloading and is also provided with every dis-tribution of Linux purchased from the vendors mentioned above.

    Visit www.xfree86.com for the latest runtime and development environmentsincluded with most Linux distributions.

    Optionally, you might be able to ftp (File Transfer Protocol) the X Window Systemfrom a variety of sites on the Internet, including gatekeeper.dec.com and

    uunet.uu.net.

    xIntroduction

  • 8/2/2019 X Window System From Scratch

    21/796

    xx X Window Programming from Scratch

    Who Should Read This Book?The text has several starting points, allowing readers in the range of seasoned profes-sional developer to serious hobbyist to enter at the point they are most comfortable.

    Whether the choice is to start at Chapter 1 and learn the basics of the Linux operat-ing system or to delve into Part Two and begin structuring the project, readers witha wide range of abilities will benefit from this text.

    This book is intended for those seeking to

    Learn or further C programming skills

    Create Graphical User Interfaces with the X Window System

    Employ the Linux operating system for software development

    Gain a greater knowledge of computer graphics programming

    Challenge their computer problem-solving skills

    The learning curve for the text rises very quickly. Therefore readers should havesome understanding of structure programming concepts.

    Conventions Used in This BookSome of the unique features in this series include

    Geek Speak.An icon in the margin indicates the use of a new term. New termsappear in the paragraph in italics.

    geeks

    peak

    How To Pronounce It. Youll see an icon set in the margin next to a box that con-

    tains a technical term and how it should be pronounced. For example, cin is

    pronouncedsee-in, and cout is pronouncedsee-out.

    how toopro nouns it

    E X C U R S I O N S

    Excursions. These are short diversions from the main topic being discussed, and

    they offer an opportunity to flesh out your understanding of a topic.Concept Web. With a book of this type, a topic can be discussed in multiple places asa result of when and where we add functionality during application development. Tohelp make this all clear, weve included a Concept Web that provides a graphical repre-sentation of how all the programming concepts relate to one another. Youll find iton the inside front cover of this book.

  • 8/2/2019 X Window System From Scratch

    22/796

    xIntroduction

    Notes give you comments and asides about the topic at hand, as well as full

    explanations of certain concepts.

    Note

    Tips provide great shortcuts and hints on how to program more effectively.Tip

    Warnings warn you against making your life miserable and help you avoid the

    pitfalls in programming.

    Warning

    Code listings are provided throughout the book. Each code listing has a heading, andthese are numbered sequentially within a chapter.

    In addition, youll find various typographic conventions throughout this book:

    Commands, variables, and other code stuff appear in text in a special mono-spaced font.

    In this book, I build on existing listings as we examine code further. When Iadd new sections to existing code, youll spot it in bold monospace.

    Commands and such that you type appear in boldface type.

    Placeholders in syntax descriptions appear in amonospaced italic typeface.This indicates that you will replace the placeholder with the actual filename,parameter, or other element that it represents.

    This symbol at the start of a line of code means that a single line of code istoo long to fit on the printed page. Continue typing all characters after the as though they were part of the preceding line.

    Getting StartedIf youre motivated by the many benefits previously outlined and have assembled thenecessary software, you are ready to begin.

    Part One: Starting Points provides the information needed to help you get started.

  • 8/2/2019 X Window System From Scratch

    23/796

  • 8/2/2019 X Window System From Scratch

    24/796

    Starting PointsThe complexity of the Graphics Editor can introduce many concepts that are

    unfamiliar to you.I address as well the likelihood that I write for an audience gathered from a varietyof backgrounds, interests, and experience levels. Therefore, you, the reader, mustchoose where you enter the text.

    You might be comfortable with some of the ideas and disciplines employed by theGraphics Editor project and not with others. However, another reader might haveconfidence in areas you have not been exposed to during your pursuits.

    Therefore, the first portion of this text provides a variety of starting points. Choosethe one that best addresses your needs.

    Where to BeginI recommend that you spend sufficient time reviewing the areas that are new or lessfamiliar to you and perhaps give only a cursory review of the subjects in which youare already confident.

    Whats at the EndUpon completing this section of the text, I expect all readers to have the same foun-

    dation, understand the same vernacular, and be prepared for the next section of thetext.

  • 8/2/2019 X Window System From Scratch

    25/796

  • 8/2/2019 X Window System From Scratch

    26/796

    Part I

    Absolute Zero

  • 8/2/2019 X Window System From Scratch

    27/796

  • 8/2/2019 X Window System From Scratch

    28/796

    Chapter 1

    In this chapter (M04)

    This is styled M05

    You will learn amazing things and bewowed by the knowledge of Que

    You will learn amazing things

    You will learn amazing things and bewowed by the knowledge of Que

    If this is longer please ask editorial to editto fit

    Box size does not get adjusted

    UNIX for DevelopersThe development of each phase of the Graphics Editor requires use of a unique skillset. As an application developer, you must become acquainted with many aspects ofcomputer problem solving. Knowledge of the operating system, programming lan-guage, windowing environment, and project management is critical to excel in thetrade. This chapter introduces the operating system, compiler, editor, and projectfiles in sufficient depth to put you on the path of completing the Graphics Editorproject.

    Structured application development (writing computer programs using an appliedmethodology) begins with the operating system. At this level, you arrange, navigate,

    edit, and compile your source code. If your organizational skills are poor, you wontbe able to locate the file you need to advance the functionality of your application.An inability to utilize the capabilities of an editor fully means you will be makingchanges (assuming you can find the file) one character at a time when you could bemanipulating pages or regions. Worse, when the compiler tells you syntax error:line 1162, you have to press the down arrow key 1,162 times to fix the problembecause you dont know the go-to command.

    Looking into the Linux operating system, you see that many tools (commands) areavailable to you. Some are sharp and can do damage if used incorrectly; others areobscure and hard to understand, and not all of them are useful for programmers.

    In the following sections well take a few of the more pertinent tools out of the boxand look at them together. If you are already well acquainted with the Linux operat-ing system, feel free to move ahead to the next section.

    Chapter 1

    In this chapter

    The man Command

    Organization and Navigation

    The C Compiler

    Object Files

    Source Files

    The viEditor

    The make Utility

    System Tools and Useful Commands

    Next Steps

  • 8/2/2019 X Window System From Scratch

    29/796

    The man CommandHaving something to do with everything, man (short for manual) offers help for mostall Linux commands. Think ofman as a librarian and ask it questions when you want

    to read the manual for a specific topic.The output ofman is called a man page.

    Examining the use ofmanwill give insight into the way that most every command inLinux is formed. The basic syntax follows the pattern:

    command -flag(s) parameter(s)

    Aflag is usually a single letter following a hyphen (-) meant to instruct the com-mand to alter its behavior. Further, the command acts upon the parameter(s).

    Consider an example where man is the command, there are no flags specified, andman

    is the parameter to be acted on:bash[1]: man man

    Issuing the command man man results in the man command using its default behaviorto display the man page for itself. Only a portion of the command output is shown inFigure 1.1; however, it is important that you execute the command on your systemand review the entire output.

    Part I6 Absolute Zero

    geeks

    peak

    Figure 1.1

    Sample of theman man

    command.

  • 8/2/2019 X Window System From Scratch

    30/796

    You can know what flags or parameters a command accepts by looking at its manpage. Anything placed between square braces ([ ]) in the Synopsis area of a com-mands man page is optional input. Reading the man page for man, you see the flagsacdfFhkKtwWfall within an optional list; however, a topic name does not, and there-fore must be specified.

    If you use man followed by-k, the output is much different (as shown in Figure 1.2).Instead of getting the man page for a topic, you get a list of pages containing thestring specified.

    Chapter 1 7UNIX for Developers

    Commands distinguish between flags and parameters by use of the hyphen (-). A

    hyphen indicates to the command that what immediately follows is a flag.

    Note

    Figure 1.2

    Sample ofman -koutput.

    E X C U R S I O N

    An Alternative to the man -k Command

    A special notice of the -k option to man: On some UNIX systems man -k is a separate

    command called apropos, which iswell, more appropriate! Although the man commandand its -k flag will always exist, apropos can be an abbreviated option to the man -k com-

    mand on your version of UNIX.

    The man command is a suitable first command to discuss because it will assist you inlearning other commands to add to your repertoire. Feel free to issue the man com-mand for any commands or keywords that appear in upcoming sections.

  • 8/2/2019 X Window System From Scratch

    31/796

    Organization and NavigationThe organization of a new project must be carefully planned. Consider as an examplethe placement of files used by the Linux operating system. With great consistency,

    the directory structure and file locations in one version of UNIX (within a family)will resemble another.

    Part I8 Absolute Zero

    A UNIX familyis a branch within the evolutionary development tree of the operat-

    ing system (see Figure 1.3). In other words, following the inception of UNIX at

    AT&T Bell Labs, UNIX has taken on a life of its own, growing like a tree where

    the efforts of the original authors serve as the trunk. Further developed at both

    Berkeley and AT&T, every version of UNIX falls under one of these two flavors. A

    UNIX family which follows from the work at Berkeley is called BSD UNIX,

    whereas those that follow from AT&T are known as SYSV. Linux happens to be a

    BSD UNIX that borrowed things from SYSV.

    Note

    SYSVis pronounced as if it were written System 5.how too

    pro nouns it

    Digital UNIX

    OSF/1

    4.4 BSD

    Net 1 & Net 2

    BSD 2.x

    Berkeley SoftwareDistribution

    (BSD)

    1969-1979

    Computer ResearchGroup(Bell Labs)

    SYS V R4

    SYS V R3

    SYS V R2

    SYS V

    SYS III

    AT&T

    SunOS

    SYS V R3.2

    LINUX

    Coherent

    Solaris

    A/UX(mac)

    HP-UX

    Figure 1.3

    The UNIX family tree.

  • 8/2/2019 X Window System From Scratch

    32/796

    If you want to affect the way your operating system works, you know (based on theflavor of UNIX) where to find the configuration file needed (see Figure 1.4). Logicalorganization and consistency mean you dont have to search for the correct directoryand guess at the name of the file.

    Chapter 1 9UNIX for Developers

    /

    (root directory)

    tmp etc dev var usr lib sbin

    temporarystorage

    device filesdefining allphysical and

    virtual devicesknown by thesystem

    files, packages,libraries,executables,

    available toall users

    executablesfor systemadministration

    shared and static

    libraries used byexternal commandsand programs

    variable files such

    as message logsand mail or printspoolers

    system files usedat startup, define

    users, configurefilesystems, etc.

    Figure 1.4

    A sample of a UNIXlayout.

    How does something with the complexity of an operating system compare to applica-tion development?

    Professional-level software development implies a life cycle: The software has a start-ing point, it grows (sometimes painfully), it is changed, and eventually it matures.Even if you are the only programmer to support this cycle, you will have other pro-jects during the life of this one. The organization and structure of the project shouldenable you to find the directory, file, or function you need by a process of induction.

    Using induction to find a file or function means that by observing the conventionsused in any piece of the application, you can surmise (guess) the name and location ofthe module you are seeking. Contrast this to a deductive process where you wouldexamine every directory and every file one at a time, stopping only when you find

    what you are looking for.The example of poor project structure illustrated in Figure 1.5 might be an extreme,but Ive witnessed similar structures used in real-world projects. Clearly, movingfrom one directory or subdirectory to another is arbitrary. There is no clear way toknow which place to go to find anything.

    geeks

    peak

  • 8/2/2019 X Window System From Scratch

    33/796

    Reuse of directory names at multiple points in the poor project structure illustratedin Figure 1.5 and the seemingly meaningless names chosen make it impossible toinduce the location of a file or function within the project. In fairness, even meaning-less directory names could contribute to good organization if, for instance, all filesand functions named in the directory were prefaced with the directory name.

    After youve decided on the basic organization of your project, you are ready to openyour Linux toolbox and begin. The structure of the Graphics Editor project is shown

    in Figure 1.6.

    Part I10 Absolute Zero

    /home/proj/src

    Ck Xq Id

    A a A a A a

    Figure 1.5

    An example of poor pro-ject structure.

    2d-editor/

    src/

    gxMain.o

    gxGx.cgxGraphics.cgxArc.c

    gxText.cgxlLine.cGNUmakefile

    include/

    gxGraphics.h

    gxIcons.hgxProtos.h

    vfonts/

    i86-linux/

    gxMain.o

    gxGx.ogxGraphics.ogxArc.o

    gxText.ogxLine.o

    GNUmakefile

    make.defines

    make.target

    Figure 1.6

    The Graphics Editorproject layout.

    DirectoriesAs George Carlin pointed out, having a place for our stuff is a long-standing concernof mankind. The age of technology offers relief from this dilemma, however, becausedirectories provide locations for storing the files created as part of a project. In fact,directories are the basic building blocks to a projects structure, allowing you to applythe organization that was carefully planned.

    The mkdir Command

    The Linux command to create a directory is mkdir. It stands for make directory.Issuing the command with only a name causes the new directory to be placed in thecurrent working directory. If you give an explicit or relative path to the command,the new directory is placed there.

  • 8/2/2019 X Window System From Scratch

    34/796

    E X C U R S I O N

    What Is a Command Shell?

    A command shell(or simply shell) is assigned to every user of a UNIX system. The shell

    provides a window into the system, enabling you to issue commands, view the output, and

    navigate the file system.

    Commands available to a user are grouped into two categories: internaland external.

    External commands are provided by the UNIX operating system and will be available to all

    users regardless of the shell assigned because external commands reside as executable

    files on the UNIX file system.

    Internal commands are shell specific, meaning that shells differ in the commands they pro-

    vide internally. Generally, internal commands offered by a shell determine its suitability forscripting as discussed in Appendix A, Command Shells and Scripting.

    Just as shells differ in the internal commands they understand, they differ in the syntax or

    conventions they accept. These differences determine, in part, the shortcuts that the shell

    understands.

    Table 1.1 provides a brief description of common UNIX shells. A more detailed discussion

    of command shells, conventions, and scripting can be found in Appendix A.

    Table 1.1 UNIX Shells

    Shell Name Command Description

    Bourne sh The Bourne shell is the original shell provided with UNIX.

    Internal commands understood by sh and its derivative

    ksh (Korn Shell) include export, for, while, and case.

    These shells provide no navigational shortcuts.

    C csh The C shell, and its variation the tcsh (T C Shell), fol-

    low closely the syntax of the C programming language.

    Internal commands include setenv, foreach, and while.

    Chapter 1 1UNIX for Developers

    An explicitpath is one where every component of the path is spelled out:

    mkdir /home/users/jbrown/2d-editor

    In a relativepath, shortcuts are used to specify the location. UNIX provides two

    valid shortcuts for your use. They include a single dot for referring to the current

    directory (.) and two dots for referring to the current directorys parent directory

    (..). For instance, by using ../ in a directory specification, the path will be rela-

    tive to the directory one level up:

    mkdir ../2d-editor

    In this example, the new directory 2d-editor is placed in the directory above the

    current one.

    Alternately, the command shellbeing used can provide other shortcuts.

    Note

    continues

  • 8/2/2019 X Window System From Scratch

    35/796

    Shortcuts include the tilde (~/) for referencing your home

    directory or ~userid/ for referencing another users home.

    For instance, csh and tcsh accept the following relativepath:

    mkdir ~/2d-editor.

    This command creates a directory called 2d-editor in

    your home directory.

    Bourne Again bash The Bourne Again Shell is a combination of sh, ksh, and

    csh conventions.

    As the default shell assigned to user accounts under

    Linux, bash is a very capable shell. The shortcuts under-

    stood by csh are also known to bash.

    The rmdir command

    To remove a directory, use the command rmdir:

    rmdir /home/users/jbrown/2d-editor

    The rmdir command, which stands for remove directory, only works if the direc-tory is empty; this is important to remember. To remove a directory with somethingin it, issue the rm -r command:

    rm -r /home/users/jbrown/2d-editor

    The rm command with the -r flag is one of the sharpest tools in our box! You use therm command to remove a file, but when told to be recursive (-r), directories andtheir contents are considered for removal as well, even if the directory contains otherdirectories and those directories contain other directories, and so on. The -r flagsends the rm command to the lowest level of the directory structure, where it beginsremoving everything it finds as it works its way back up to the starting point. This isillustrated in Figure 1.7.

    When using the rm command, you must specify the name of what you want toremove.

    Part I12 Absolute Zero

    Table 1.1 Continued

    The way to specify names for command completion under Linux can be very

    flexible when employing wildcards. Of course, this flexibility makes the rm com-

    mand even more dangerous.

    Note

  • 8/2/2019 X Window System From Scratch

    36/796

    Unlike other operating systems, Linux has no undo or undelete command for recov-ering files removed in error. When you unintentionally delete something (notice Isaid when and not if), remember two magic words and utter them over and overuntil you get a response from your system administrator. The words are backups. Iguess thats only one word. You may have to appendplease to it for it to be magic!

    Wildcardsfor command-line completion use a single character to represent multiplecharacters.

    Commonly understood wildcards and their functions include:

    * Replaces any number of characters (broadest substitution)for example,

    bash[2]: rm ca* expands to remove capable, cannibal, canister, cat, cap,

    cal, and cab.

    ? Replaces only a single characterfor example, bash[2]: rm ca? expands to

    remove only cat, cap, cal, and cab.

    [a-d] Replaces only occurrences of a single letter which falls between the specified

    range for example, bash[2]: rm ca[a-d] removes only cab.

    Not to minimize the amount of caution that should be used when exercising the rmcommand, especially if using wildcards, but a safety net, calledpermissions, is built

    into Linux.A look at permissions follows in the next section on directory listings.

    Chapter 1 1UNIX for Developers

    bash[10]: rm-r/home/users/jbrown/2deditor

    src/

    gxMain.ogxGx.c

    gxGraphics.cgxArc.cgxText.c

    gxlLine.cGNUmakefile

    include/

    gxGraphics.hgxIcons.hgxProtos.h

    vfonts/

    i86-linux/

    gxMain.ogxGx.o

    gxGraphics.ogxArc.ogxText.o

    gxLine.o

    GNUmakefile

    make.definesmake.target

    Figure 1.7

    Recursive rm command.

    geeks

    peak

  • 8/2/2019 X Window System From Scratch

    37/796

    The ls Command

    Requesting a directory listing determines whether anything is in a directory. Thelisting command is ls, and it accepts many flags to alter its behavior or output.

    The -l flag passed to ls tells it to issue a long listing. A long listing includes infor-mation about permissions, ownership, modification date, and size. The default out-put for ls (no flags specified) is to list only the names of the files. Any file with aperiod (.) as the first character of its name is considered a hidden file, and you mustexplicitly request that ls display such a file by passing the -a flag.

    Part I14 Absolute Zero

    When specifying multiple flags to a command, group them together following a

    single hyphen. Everything after the hyphen and until the next space is interpreted

    as flags and acted on accordingly. Issuing ls -al requests that the listing com-

    mand displays all files in a long listing format.

    Note

    Figure 1.8 shows sample use of the ls command, including examples of the -l and-a flags.

    Figure 1.8

    The ls, ls -a, andls-al commands.

    Notice that when displaying all (ls -a) files in a directory you see . and .. listed.The . (current directory) and .. (parent directory) are special files Linux uses tomaintain information about these directories. When you ask for a listing of yourcurrent directory, ls displays some of the information contained in the . file.

    geeks

    peak

    A . in UNIX is always pronounced as dot.how too

    pro nouns it

  • 8/2/2019 X Window System From Scratch

    38/796

    PermissionsPermissions serve several functions within the Linux operating system. They providesecurity, safety, and control. However, as with any tool, they must be used correctly.

    You must give thought to the permissions that are applied to the files and directoriesyou create and manage.

    You can find permissions for a specific file or directory in the first column of a long list-ing (ls -l) as you saw in Figure 1.8. Several groupings make up the permission field.Dissecting them into their groupings will make permissions very easy to understand.

    drwxrwxr-x 9 jrb jrb 4096 Nov 7 05:32 ObjCntrl

    The first character of permissions is the designator field. This character indicates thetype of entry in the listing. By the d in the first column of the example, you knowthat the entry is a directory. Other possible characters found in this position are -

    (hyphen) when the entry is a file or lwhen the entry is a symbolic link. I havent dis-cussed links yet but youll soon see their usefulness to multi-platform applicationdevelopment. For now, remember what it means when you see an l in the designatorfield of permissions.

    drwxrwxr-x 9 jrb jrb 4096 Nov 7 05:32 ObjCntrl

    The next grouping to consider in the permissions is the owner accessfield. As thename implies, this determines the accessibility for the owner. Clearly, owning theentry means that as owner you can alter any access field within the permissions.However, access doesnt just limit; it also protects. If used properly, you will have a

    safety net that prevents accidents.The first character of the owner access field governs read permission. The presenceof the r in the first column of this field indicates that read access has been granted. Ifaccess were not granted, there would be a - (hyphen) placeholder. The second char-acter of the owner access field determines write permission, where a w indicates thecapability to write to the file, and a - (hyphen) placeholder means that no write per-mission is granted. Last is execute permission as seen with either an x indicatingpermission to execute or a - for no permission to execute.

    Chapter 1 1UNIX for Developers

    Having execute permission is not always meaningful. For instance, writing a letterto a loved one and assigning execute permission to the file does not cause any-

    thing useful to happen. The file does not become a command by simply granting

    execute permission. (If accomplishing things on a computer were so easy, you

    probably wouldnt need this book.) However, if the file you create is a series of

    valid Linux or shell commands, giving execute permission creates a script or

    shell script for which execute permission is meaningful. (Shell scripting is dis-

    cussed in Appendix A.)

    Note

  • 8/2/2019 X Window System From Scratch

    39/796

    drwxrwxr-x 9 jrb jrb 4096 Nov 7 05:32 ObjCntrl

    Following the owner access field is the field governinggroup access. In addition to aunique ID assigned to all Linux user accounts, everyone is placed into at least onegroup. This grouping is useful for allowing files and directories to be shared.

    E X C U R S I O N

    WhatGroupAm I In?

    You have several ways to determine into which groups you have been placed. For

    instance, you can execute the id or the groups command. The output of the id command

    provides a lot of information about your Linux account, including the group assignments.

    The groups command will simply list the groups to which you are assigned.

    The group access field manages sharing within a group. Applying the same

    read/write/execute pattern as for the owner access field, you can quickly determinethat in the example anyone belonging to the same group as the group ownership ofthis entry may read, write, and execute.

    E X C U R S I O N

    How to Determine Group Ownership

    The SYSV family of UNIX does not show what the group assignment for an entry in a direc-

    tory listing is unless you explicitly ask. To request that group ownership be displayed in the

    output of the ls command, you must pass the -g flag.

    drwxrwxr-x 9 jrb jrb 4096 Nov 7 05:32 ObjCntrl

    The last field represents permissions that pertain to a collection of users known asthe world. Any user who does not own the entry and is not assigned to the samegroup as the group ownership is considered part of the world. Users accessing theentry based on the merit of world permissions include anyone who shares an accounton the system (and possibly network). For this reason, world permissions are gener-ally not very giving, as you have no way to know or control those in the worldbeyond these permissions.

    In the example, those in the world may only read and execute the entry. Note that a- placeholder resides in the write column, indicating no write access is granted.

    Beyond the Obvious

    What exactly can a user do with read, write, and execute permission?

    Part I16 Absolute Zero

  • 8/2/2019 X Window System From Scratch

    40/796

    Read Permission

    Granting read permission enables users not only to view what has been placed into afile or directory, but also to copy it. In fact, you must have read permission to exe-cute the cp (copy) command successfully.

    Write Permission

    Write permission allows users to modify any entry for which they have permission towrite. Most importantly, though, having write permission enables users to remove afile or directory. You must have write permission to execute the rm or mv (move) com-mand successfully. For this reason, if you are not actively changing a file or directory,removing write permission also removes your ability to delete a file in error.

    Execute Permission

    Being able to execute a file, as discussed earlier, means that each of the commands

    the script contains is performed as if it were typed at the command line. In the caseof a compiled program, execute permission allows the user to run the program.However, if the entry is a directory, execute permission is required to change intothat directory. If you do not have execute permission for a directory, it is effectivelyclosed and the cd command will fail.

    chmod

    With an understanding of the power and utility of permissions, you must know howto change them. The chmod command, which stands for change mode, allows youto modify the permissions of anything you own.

    Chapter 1 1UNIX for Developers

    The chmod command is pronounced as if it were written change mod.how too

    pro nouns it

    Syntax of the chmod command is direct.

    chmod [ugoa][+ or -][rwx] name

    where:

    Item Means

    u user/owner

    g group

    o world/others

    a all

    + add

  • 8/2/2019 X Window System From Scratch

    41/796

    - remove

    r read

    w write

    x execute

    name item to be changed

    For instance, the following command changes the permissions ofObjCntrl from theexamples above to add write permission for the world:

    bash[5]: chmod o+w ObjCntrl

    To remove execute permission for both group and world, you could use the follow-ing command:

    bash[5]: chmod go-x ObjCntrl

    Any questions? Just askman (man chmod).

    The cd CommandA discussion on organization and navigation would not be complete if I didnt men-tion something about navigation. The cd or change directory command navigatesaround the Linux file system. It expects a single parameter to indicate to whichdirectory you wish to change. If you execute the cd command without any parame-ters, you are returned to your home directory.

    Part I18 Absolute Zero

    Unlike other operating systems, Linux is case sensitive.When trying to change to

    a directory you know exists but Linux disagrees with, check the case because

    ./src and ./Src are unique names to Linux.

    Note

    With an understanding of basic Linux commands, you are ready to advance to com-mands specific to software development.

    The C CompilerThe C Compiler, known as cc, translatessource code that a programmer has written

    into object code that the machine understands.

    Source code can be read and written by you, a programmer. It spells out program-ming language elements such as keywords, variables, start of body markers, and endof body markers. A computer, however, knows nothing of the letters or charactersthat are meaningful to programmers. Instead, the computer expects that when you

  • 8/2/2019 X Window System From Scratch

    42/796

    enter the letterA as part of a program solution, it will be translated into the machinecode equivalent 0100 0001. Accomplishing this translation is the function of thecompiler..

    E X C U R S I O N

    A Closer Look at Machine Code

    Machine code is ultimately a collection of 0s and 1s, which is all any machine can under-

    stand. At this level the collection of 0s and 1s is represented in the binarynumbering sys-

    tem. Unlike the everyday decimalnumbering system that consists of ten digits (09), the

    binary numbering system has only two digits, 0 and 1. Use of binary numbering to repre-

    sent machine code can be very tedious to humans, so we also use the hexadecimal(16

    digits) and octal(8 digits) numbering systems.

    Table 1.2 shows various characters represented using the different numbering systems.

    Table 1.2 Data Representation

    Character Decimal Binary Hexadecimal Octal

    1 49 0011 0001 0x31 \0061

    2 50 0011 0010 0x32 \0062

    > 62 0011 1110 0x3E \0076

    @ 64 0100 0000 0x40 \0100

    A 65 0100 0001 0x41 \0101

    B 66 0100 0010 0x42 \0102

    a 97 0110 0001 0x61 \0141

    Determining which numbering system to use is largely a matter of convention based on

    how the data is used. This decision is also influenced by the size of the data being dis-

    played. For instance, representing addresses in computer memory is most often done

    employing the hexadecimal numbering system.

    Data representation is largely for the convenience of programmers; this is important to

    remember. The computer only understands 0s and 1s.

    Object FilesStating that the compiler translates the letter A from the source file into the machinecode equivalent for the object file is an over-simplification.

    It is true thatA is translated to its machine code equivalent, but only if it is a literal.If it is a keyword, it is translated into an op code (code specifying an operation). IfA ispart of a variable name, it is translated into an offset(distance from the value of aninternal control pointer). If part of a function name,A is translated to ajump point

    Chapter 1 1UNIX for Developers

  • 8/2/2019 X Window System From Scratch

    43/796

    (distance from the base address of the application to where the function definitionexists). IfA is a function parameter, it is translated as an offset of thestack pointer(aninternal control pointer that manages program execution), and on and on.

    The complexity of the compiler is boggling, and Ive only given a very high-leveloverview of its role. Entire books are dedicated to the subject of compiler design.For this reason, compilers are not generally given away for free, except, of course,the GNU C Compiler (gcc), which I will discuss shortly.

    To review, an object file consists of only the machine codes (op codes, jump points, off-sets, and so forth) translated from what youve written in the source file using a high-level language such as C.

    Object files have the suffix .o so that you can distinguish them from files you author.Any attempt to edit or view the contents of an object file will make it instantly clearthat there is nothing in it that you can affect.

    Part I20 Absolute Zero

    Object files, because of their .o extension, are referred to as dot-ohs.how too

    pro nouns it

    Object files are platform specific: You cannot use an object file generated on an x86PC platform on a platform of a different architecture. This is important to know.

    The object file is the translation of what was written in the source file into a formatthat the computer understands. Not all computers do things in the same way. If youhad an 80286-generation computer and you now own a Pentium, it is clear to youthat processors are very different. The most notable difference in this example isspeed. Performance, however, is not always a noticeable difference, but when it is,many factors contribute to it, such as the language set available to the processor orthe manner in which it groups data into internal representations.

    The Pentium processor is boasted to be a 32-bit processor, whereas the 80286processors were only 16-bit architecture. The different number of bits (0s and 1s)supported by the processor means that the word size (internal bit groupings) will bedifferent for each. Although a Pentium may be able to understand a 16-bit word size(grouping), an 80286 can never understand a 32-bit word.

    E X C U R S I O N

    Computer Processor Instruction Sets

    A processors instruction set consists of the op codes(operational codes) available to it.

    These instructions are internal to the processor and dictate everything the processor

    knows how to do. Basic processor instructions include directions for moving data, arith-

    metic operations, program flow control, and more.

    Instruction sets fall into two categories: Reduced Instruction Code Set (RISC) or Complex

  • 8/2/2019 X Window System From Scratch

    44/796

    Instruction Code Set (CICS)). RISC-based processors know fewer commands than CICS

    processors but operate more quickly as a result. In other words, the op codes contained

    within one processors instruction set may not be the same as those of another processors

    of a different architecture (and similar doesnt count). The differences in instruction sets of

    varying architectures introduce another level of binary incompatibility.

    How does all this affect the object files? If you generated an object file on a 32-bitplatform, the calculated offsets to memory for representing variables, for instance,would not align to valid memory addresses on the 16-bit system, nor would thejump-to addresses. The distance of the jump would likely be well outside theintended user memory area on the 16-bit platform. This illustrates, of course, onemanner in which object files are platform specific.

    Ive barely mentioned the internal representation of data by a processor. In additionto word size (data grouping), some processors expect the order of the bytes (four-bit

    grouping) of data to be formatted differently from others.

    One method of byte ordering is least significant bit first, called little-endian, andanother is most significant bit first, called big-endian.

    Think of little-endian as little end first, big-endian as big end first, and endian as end-ed.

    E X C U R S I O N

    Waiter, Id Like To Order Some Bytes.The determination of which byte order to employ for a given platforms architecture is

    largely a decision of the design engineers. It has occurred in the history of processor

    design that the decision to elect one method of byte ordering over another was based

    solely on a desire to avoid patent infringement.

    Source FilesPreviously, I spoke at length on the complexity of an object file as generated by the

    compiler. Figure 1.9 demonstrates the compile process with emphasis on the sourcefiles asplain text, meaning that they are understandable to programmers and containno word processor type formatting. The figure further illustrates that the output ofthe compiler is not in human readable format, but rather in a format that satisfies acomputers requirements.

    Chapter 1 2UNIX for Developers

    geeks

    peak

  • 8/2/2019 X Window System From Scratch

    45/796

    Knowing the complexity of the compile process that a source file undergoes to betranslated into something the computer can understand should make you appreciatethat the compiler considers every character of a source file. In effect, as the compiler

    parses the source file it anticipates the next character or token it expects. If what isanticipated is not what it reads from the file, a syntax error is issued. For this reason,the source files must be plain text to prevent the extra control symbols used in wordprocessing from confusing the very literal compiler.

    Even the most basic text formatting performed by a word processor is accomplishedby inserting control characters into the document so that the word processing appli-cation knows when to turn on and off the formatting. These control characters are,in fact, characters (not usually printable) that would be considered by the compiler asinput. The choice of editor is important, as is how you choose to save the file if theeditor supports multiple file formats.

    An editor is available in all versions of UNIX to ensure that your authored sourcefiles contain only text. This is because it is incapable of word processing functionssuch as bolding, italicizing, and underlining.

    The vi EditorA popular choice among UNIX programmers is the vi editor. The fact that it isreadily available on every version of UNIX, it does not require a lot of systemresources, and it is fairly easy to master makes it a solid choice.

    Certainly, other editors exist that satisfy the requirement of being able to save sourcefiles without any extra formatting data. A popular editor called GNU Emacs willenable you to write and save source files as required in addition to telling your for-tune and generating whimsical quips. However, we must concern ourselves withavailability and system requirements. Emacs is very large and will not always beinstalled on the system on which you must work.

    Part I22 Absolute Zero

    Source File

    Source File

    Source File

    Source File

    Source File

    Plain

    Tex

    t

    Ma

    chineCode

    Compiler

    Object File

    Object File

    Object File

    Object File

    Object File

    Figure 1.9

    An illustration of thecompile process.

  • 8/2/2019 X Window System From Scratch

    46/796

    To start vi, simply execute the command specifying the name of the file that youwant to edit:

    bash[2]: vi gxArc.c

    If the file didnt exist previously, vi informs you that it was created. When loading anexisting file, vi informs you of the number of characters read.

    There are three modes in vi: command mode, last-line mode, and edit mode. vi always

    starts in command mode waiting for input. To move from command mode to editmode, you must enter an appropriate command. Some commands enab